<template>
  <div class="bigBox">
    <div class="info">
      <p class="tt">基础信息</p>
      <div v-for="item in infoData[0]" :key="item.title">
        <span class="titlestyle">{{ item.value }}</span>
        <span
          class="infostyle"
          v-for="(val, index) in infoData[1]"
          :key="index"
          >{{ val[item.key] }}</span
        >
      </div>
    </div>
    <div class="tableBox">
      <div class="top">
        <div class="left" v-if="tableCount[0]">
          <p>{{ tableCount[0].statisticTitle }}</p>
          <i>{{ tableCount[0].result }}</i>
        </div>
        <div class="right">
          <p>是否外协</p>
          <el-checkbox v-model="checked"></el-checkbox>
        </div>
      </div>
      <!-- 按钮组 -->
      <el-button-group>
        <el-button v-for="(item, index) in controlBtnArr" :key="index">
          <template>
            <span @click="clickHandler(item, row)"
              ><svg-icon
                v-if="item.btnIcon"
                class="pre-icon"
                slot="prefix"
                :icon-class="item.btnIcon"
              />{{ item.btnName }}</span
            >
          </template>
        </el-button>
      </el-button-group>

      <el-form ref="tableform" :model="tableDataForm">
        <el-table
          border
          :data="tableData[1].data"
          style="width: 100%; margin-bottom: 20px"
        >
          <el-table-column
            v-for="item in tableData[0].column"
            :prop="item.key"
            :label="item.value"
            :key="item.value"
            width="180"
          >
            <template slot-scope="scope">
              <el-input
                :v-if="scope.row[item.key]"
                v-model="scope.row[item.key]"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            v-if="isShowExcuteCol"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <Menu
                :row="scope.row"
                v-for="btnObj in excuteBtnArr"
                :key="btnObj.id"
                :listAll="btnObj"
                @excuteHandler="excuteHandler"
              ></Menu>
            </template>
          </el-table-column>
        </el-table>

        <div>
          <b>统计信息 </b>
          <span v-for="(item, index) in subCount" :key="index"
            >{{ item.statisticTitle }}: {{ item.result }}</span
          >
        </div>

        <el-form-item>
          <el-button class="addBtn" icon="el-icon-plus" @click="addBtnHandler"
            >新增</el-button
          >
          <el-button
            class="saveBtn"
            icon="el-icon-document-checked"
            @click="saveBtnHandler"
            >保存</el-button
          >
        </el-form-item>
      </el-form>

      <div></div>
    </div>
  </div>
</template>

<script>
import { dragGroupTableInfo } from "@/api/relateTable/index";
import {
  btnCommonApi,
  dragTableInfo,
  unionListTableData,
} from "@/api/tablelist/commonTable";
import { camelCase } from "@/utils";
import Menu from "@/views/tablelist/commonTable/BtnMenu.vue";
import {
  getProcessPopupTableInfo,
  getProcessPopupTableList,
} from "@/api/dragform/form"; //新的弹窗数据请求

export default {
  components: { Menu },
  data() {
    return {
      // 基础信息行数据
      infoData: [],
      listInfo: {},
      // 是否外协
      checked: false,
      tableData: [],
      // 动态增加表格数据
      editData: [],
      tableDataForm: {},
      tableLists: [],
      queryParams: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页大小
        orderByColumn: "", // 根据某列排序
        isAsc: "", // desc（降序）或 asc（升序）
        // 基本查询参数
        basicMap: {
          tableName: "drag_form",
        },
        // 当前表字段筛选参数
        queryMap: {
          // 当前查询基本参数
          // ... key : value         当前页面的筛选条件
          // 超级查询的唯一值
          queryCriteriaValue: "",
          // tableCondition: ''
        },
      },
      columns: [],
      // 排序方式 默认降序
      sortOrder: true,
      tableName: "",
      // 当前模版信息
      templateInfo: {},
      queryFromWhere: "",
      condition: [],
      // 当前点击按钮的数据
      currentBtnData: {},
      // 操作列 按钮数据
      excuteBtnArr: [],
      // 新增保存的数据
      addListData: [],
      controlBtnArr: [],
    };
  },
  props: ["groupKey", "rowobj", "tableCount", "subCount", "subTableName"],
  computed: {
    isShowExcuteCol() {
      return !this.excuteBtnArr?.every((arr) => arr.children.length == 0);
    },
  },
  methods: {
    // 新增
    addBtnHandler() {
      let obj = {
        // id:'',
      };
      this.addListData.push(obj);
      this.tableData[1].data.push(obj);
    },
    // 保存
    saveBtnHandler() {
      console.log(this.addListData);
      let data = {
        addListMap: this.addListData,
        basicMap: {
          btnType: 10,
          tableName: this.subTableName,
          visible: true,
        },
        commMap: {},
        conditionMap: {},
      };
      btnCommonApi(data).then((res) => {
        console.log("保存", res);
      });
    },
    // 获取弹窗信息
    async getLists(payload) {
      // let res = await dragGroupTableInfo({ queryMap: { groupKey: groupKey } });
      let resTableInfo = await getProcessPopupTableInfo({ queryMap: payload });
      let resTableData = await getProcessPopupTableList({ queryMap: payload });
      // 获取表格tablekey 和 sort
      console.log(resTableData);
      this.tableLists = JSON.parse(res.msg);

      this.tableLists.forEach(async (item) => {
        // 基础信息
        if (item.sort == 0) {
          const res = await dragTableInfo({
            queryMap: { tableKey: item.tableKey },
          });
          this.getTableHandle(res, item.sort).then((result) => {
            console.log("result:", result);
            this.infoData.push(result);
            this.$set(this.infoData);
          });

          //表格数据
        } else if (item.sort == 1) {
          const res = await dragTableInfo({
            queryMap: { tableKey: item.tableKey },
          });
          this.excuteBtnArr = res.data.resultMap.button;
          this.getTableHandle(res, item.sort).then((result) => {
            // 表头数据
            this.tableData.push({
              column: result,
            });
          });

          // 统计状态 和 按钮
        } else if (item.sort == 2) {
          const res = await dragTableInfo({
            queryMap: { tableKey: item.tableKey },
          });
          // 按钮
          this.controlBtnArr = res.data.resultMap.button[0];
          this.controlBtnArr = this.controlBtnArr.children;
        }
      });
    },
    // 获取基础信息 表头数据
    async getTableHandle(res, sort) {
      this.columns = [];
      // 得到当前模版信息 --- sql columns queryWhere
      this.templateInfo = res.data.resultMap;

      // console.log(res.data.resultMap.querySql);
      this.queryParams.orderByColumn =
        res.data.resultMap.querySql.orderByColumn;

      this.sortOrder = JSON.parse(res.data.resultMap.querySql.sortOrder);
      // 根据拖拽时设置当前列表排列顺序
      this.queryParams.isAsc = this.sortOrder ? "DESC" : "ASC";
      this.tableName = this.templateInfo.template.dtTableName;
      // 得到查询条件
      this.queryFromWhere = res.data.resultMap.where;

      //  得到当前列表信息
      this.columns = this.columnsHandler(
        JSON.parse(this.templateInfo.template.dtColumnName)
      );
      if (this.templateInfo) {
        this.tableCondition = this.templateInfo.querySql.tableCondition;
        this.tableCondition = this.tableCondition.split("AND");
        // console.log(this.tableCondition);
        this.condition = [];

        // 调用查询需要携带当前table的唯一标识
        this.queryParams.queryMap.sqlkey = this.templateInfo.template.sqlKey;

        this.queryParams.orderByColumn = camelCase(
          this.queryParams.orderByColumn || ""
        );
        // 根据sql语句查询当前表数据

        let k;
        this.tableCondition.forEach((item, i) => {
          let val = item.split("=");
          if (i !== 0) {
            k = val[0].split(".");
            let str = k[0].trim() + "." + k[1];
            this.condition.push({
              key: k[0].trim(),
              value: k[1],
            });
          }
        });

        this.getDataHandler(this.tableCondition[1]).then((res) => {
          // console.log(res);
          if (sort == 0) {
            this.infoData.push(res);
            // this.$set(this.infoData)
          } else if (sort == 1) {
            this.tableData.push({
              data: res,
            });
            // this.$set(this.tableData)
          }
        });
        // console.log('columns', this.columns);
        return this.columns;
      }
    },
    // 获取表数据
    async getDataHandler(contion) {
      let con = contion.split("=");
      let key = con[1].trim();

      let value = key.split(".");

      // 拼接请求数据依赖条件
      this.queryParams.queryMap[key] = "'" + this.rowobj[value[1]] + "'";

      let tableLists = await unionListTableData(this.queryParams);

      if (tableLists.code == 200) {
        this.tableList = [];
        tableLists.rows.forEach((item) => {
          this.tableList.push(item.resultMap);
        });

        // 驼峰转换
        this.tableList = this.tableList.map((item) => {
          let kv = {};
          for (let itemKey in item) {
            kv[camelCase(itemKey)] = item[itemKey];
          }
          return kv;
        });

        return this.tableList;
      }
    },
    // 处理列表信息
    columnsHandler(columns) {
      let resArr = [];
      columns.forEach((item) => {
        for (const key in item) {
          let tempObj = {};
          tempObj.key = camelCase(key);
          tempObj.value = item[key];
          resArr.push(tempObj);
        }
      });
      return resArr;
    },
    // 操作列回调
    excuteHandler(btnData, row) {
      let { btnType, btnParams } = btnData;
      this.currentBtnData = btnData;
      switch (
        btnType //3:内链  6:目录  7:外链  8:修改  9:删除
      ) {
        case "3":
          this.routerHandler(btnData, btnType);
          break;
        case "7":
          this.routerHandler(btnData, btnType);
          break;
        case "8":
          this.handleUpdate(row, btnData);
          break;
        case "9":
          this.handleDelete(row, btnData);
          break;
        default:
          break;
      }
    },
    // 内链页面跳转
    routerHandler(btnData, type) {
      let link = btnData.btnParams;
      if (type == "3") {
        this.$router.push(link);
      } else {
        window.open("http://" + link, "_blank");
      }
    },
    // 删除
    handleDelete(row, btnData) {},
    // 修改
    handleUpdate(row, btnData) {
      console.log(row);
    },
    // 按钮组点击
    clickHandler(item, row) {},
  },
  mounted() {
    // this.getLists()
  },
};
</script>

<style scoped lang="scss">
.bigBox {
  margin: auto;
  display: flex;
  ::v-deep .info[data-v-32a636fc] {
    min-width: 200px !important;
  }
  .info {
    margin-right: 60px;
    .tt {
      font-size: 18px;
      font-weight: 700;
    }
    span {
      display: inline-block;
    }
    .titlestyle {
      background-color: #34bfa3;
      /* width: 50px; */
      display: inline-block;
      /* height: 25px; */
      line-height: 1;
      padding: 5px;
      margin-bottom: 20px;
      margin-right: 5px;
      text-align: center;
      color: white;
      border-radius: 20px;
    }
    .infostyle {
      background-color: #ebedf2;
      color: #e84e95;
    }
  }

  .tableBox {
    .svg-icon[data-v-c8a70580] {
      margin-right: 5px;
    }
    min-width: 300px;
    .addTable {
      margin: 0px 0px 20px 0px;
    }
    .titleitem {
      text-align: center;
      font-size: 20px;
      margin-top: 20px;
    }
    .addBtn {
      background-color: #0275d8;
      color: white;
    }
    .saveBtn {
      background-color: #34bfa3;
      color: white;
    }
    .top {
      padding: 20px;
      box-sizing: border-box;
      background-color: #53b0f8;
      display: flex;
      justify-content: space-around;
      color: white;
      flex: 1;
      /* width: 90%; */
    }
    .el-button-group {
      width: 100%;
      margin: 10px;
      background-color: white;

      .el-button:first-child {
        color: blue;
        border: 1px solid blue;
      }
      .el-button:nth-child(2) {
        color: palevioletred;
        border: 1px solid palevioletred;
      }
      .el-button:nth-child(3) {
        color: green;
        border: 1px solid green;
      }
      .el-button:last-child {
        color: burlywood;
        border: 1px solid burlywood;
      }
      .custom {
        width: 120px;
      }
    }
  }
}
</style>
