<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-tag class="tag_NO">{{ dtName }}</el-tag>
      <!-- <span class="title">{{ cardData.title }}</span> -->
      <el-button icon="el-icon-plus" type="primary" @click="handleAdd"
        >新增数据</el-button
      >
    </div>
    <!-- body -->
    <el-table
      ref="singleTable"
      :data="tableList"
      height="300"
      width="100%"
      highlight-current-row
      @row-click="
        (row, e, column) => handleCurrentChange(row, e, column, cardData)
      "
      style="width: 100%"
    >
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  >删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in columns"
        :prop="item.key"
        :key="item.key"
        :label="item.value"
      >
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="gettableListHandler(tableKeyWatcher)"
    />
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <k-form-build
        class="formBuild"
        ref="addFromRef"
        :dynamicData="dynamicData"
        :defaultValue="defaultValue"
        @submit="tempSubBtn"
        @change="formChangeHandler"
        :value="jsonData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editConfirmHandler">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  delTableData,
  dragTableInfo,
  listTable,
  unionListTableData,
  getInfoBySqlKey,
  addTableData,
  batchEdit,
} from "@/api/tablelist/commonTable";
import { inputDisableComplete } from "@/utils/other";

import { camelCase } from "@/utils";
import { CloudFog } from "lucide-vue";
import { bottom } from "@antv/x6/lib/registry/port-layout/line";
export default {
  name: "RelateTableCard",
  props: ["cardData", "index", "tableKey", "sort"],
  components: {},
  data() {
    return {
      // 总条数
      total: 0,
      tableList: [],
      newsort: "",
      queryParams: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页大小
        orderByColumn: "", // 根据某列排序
        isAsc: "", // desc（降序）或 asc（升序）
        // 基本查询参数
        basicMap: {
          tableName: "drag_form",
        },
        // 当前表字段筛选参数
        queryMap: {
          // 当前查询基本参数
          // ... key : value         当前页面的筛选条件
          // 超级查询的唯一值
          queryCriteriaValue: "",
          // tableCondition: ''
        },
      },
      columns: [],
      // 回显表格数据,
      defaultValue: {},
      currentValue: {},
      //存放表单渲染数据
      jsonData: {},
      // 弹出层标题
      title: "",
      // cru 弹窗
      open: false,
      // 回显表格数据,
      currentRow: null,
      // 用户表格数据
      tableList: [],
      // 排序方式 默认降序
      sortOrder: true,
      // 当前模版信息
      templateInfo: {},
      tableName: "",
      queryFromWhere: "",
      condition: [],
      dtName: "",
      // 下拉框动态数据
      dynamicData: {},
      row: null,
      myContion: null,
      preRow: {},
    };
  },
  computed: {
    // currentValues
    cardDataWatcher: function () {
      return this.cardData;
    },
    tableKeyWatcher: function () {
      return this.tableKey;
    },
    sortWatcher: function () {
      return this.sort;
    },
  },
  watch: {
    cardDataWatcher: {
      handler(newval, oldval) {
        // debugger;
        this.currentValue = newval;
        this.$refs.singleTable?.doLayout();
      },
      deep: true,
      immediate: true,
    },
    tableKeyWatcher: {
      handler(newval) {
        // console.log(newval)
        this.gettableListHandler(newval);
      },
      deep: true,
      immediate: true,
    },
    sortWatcher: {
      handler(newval) {
        this.newsort = newval;
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    // 根据tablekey请求数据表头数据
    async gettableListHandler(tableKey, paramsContion = [], defaultVal = {}) {
      const res = await dragTableInfo({ queryMap: { tableKey: tableKey } });

      this.getTableHandle(res, (paramsContion = []), (defaultVal = {}));
    },
    // 处理表格表头
    async getTableHandle(res) {
      this.columns = [];
      // 得到当前模版信息 --- sql columns queryWhere
      this.templateInfo = res.data.resultMap;
      console.log(1111, this.templateInfo.template);
      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.dtName = this.templateInfo.template.dtName;
      // 得到查询条件
      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");

        this.condition = [];

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

        this.queryParams.orderByColumn = camelCase(
          this.queryParams.orderByColumn || ""
        );
        // 根据sql语句查询当前表数据
        this.contion =
          this.templateInfo.template.dtTableName +
          "." +
          this.templateInfo.template.primaryKey;

        this.$nextTick(async () => {
          console.log(this.preRow);
          if (this.newsort == 0) {
            // 第一张表请求表数据不需要条件
            await this.getDataHandler();
          } else {
            if (this.myContion && this.preRow) {
              console.log("111", this.myContion, this.preRow);
              await this.getDataHandler(this.myContion, this.preRow);
              console.log(this.myContion, this.preRow);
            }
          }
        });

        //处理三张不同表的依赖关系
        // 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]
        //     })
        //   }
        // })
      }
    },
    // 获取表格数据
    async getDataHandler(contion, list) {
      console.log(contion, list);
      this.myContion = contion;
      this.preRow = list;
      // console.log(list);
      // 处理请求下一张表数据的依赖条件
      let tableLists = {};
      console.log(this.newsort);
      if (contion && list) {
        let key = contion.split(".");
        console.log(contion, list, key[1]);
        this.queryParams.queryMap["#{" + contion] = "'" + list[key[1]] + "'";
        // this.queryParams.queryMap["#{" + contion] = list[key[1]];

        this.queryParams.queryMap.sqlkey = this.templateInfo.template.sqlKey;

        this.tableList = [];
        tableLists = await unionListTableData(this.queryParams);
      } else if (this.newsort == 0) {
        console.log(contion);
        tableLists = await unionListTableData(this.queryParams);
      }
      if (tableLists.code == 200) {
        // 默认根据这张表的第一条数据请求下一张表的数据
        this.$emit("getDefaultCardData", this.index);
        this.tableList = [];
        tableLists.rows.forEach((item) => {
          this.tableList.push(item.resultMap);
        });
        // this.tableList = tableLists.rows.filter((item) => item.resultMap);

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

      this.total = tableLists.total;

      this.loading = false;
    },
    // 处理列表信息
    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;
    },
    // 调用父组件方法更新表格数据
    handleCurrentChange(row, event, column, val) {
      this.row = row;
      // console.log(row);
      this.$emit("updateData", row, this.index);
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      // this.reset();
      this.defaultValue = {};
      getInfoBySqlKey(this.templateInfo.template.sqlKey).then(({ data }) => {
        if (!data || !data.dfVueTemplate) {
          this.$message.error("当前表格未绑定表单!");
          return;
        }
        if (data.dfFormSql) {
          let dynamicData = JSON.parse(data.dfFormSql);
          Object.assign(this.dynamicData, dynamicData);
        }
        this.jsonData = JSON.parse(data.dfVueTemplate);
        this.open = true;
        this.title = "添加信息";
        // this.form.password = this.initPassword;
        this.$nextTick(() => {
          this.$refs.addFromRef.reset();
          inputDisableComplete();
        });
      });
    },
    // 下一表数据
    getNextCardData() {
      this.handleCurrentChange(this.row);
    },
    // 根据表格第一条数据请求下一个表格的数据
    getDefaultCard() {
      this.handleCurrentChange(this.tableList[0]);
    },
    // 使用提交数据类型的按钮获取数据
    tempSubBtn(getData) {
      getData()
        .then((values) => {
          console.log("验证通过", values);
        })
        .catch(() => {
          console.log("验证未通过，获取失败");
        });
    },
    //提交编辑结果按钮回调
    editConfirmHandler() {
      this.$refs.addFromRef
        .getData()
        .then(async (values) => {
          let data = {
            basicMap: {
              tableName: this.tableName,
            },
            addListMap: [values],
            commMap: {},
          };
          if (Object.keys(this.defaultValue).length) {
            let updateData = {
              // 基本参数
              basicMap: {
                // 表名
                tableName: this.tableName,
              },
              conditionMap: {},
              commMap: {},
            };

            // 后台接收需要是表中字段真实的名称，无所谓驼峰。
            updateData.conditionMap[this.templateInfo.template?.primaryKey] =
              this.defaultValue[
                camelCase(this.templateInfo.template?.primaryKey)
              ];
            Object.keys(values).map((k) => {
              updateData.commMap[k] = values[k];
            });
            let res = await batchEdit(updateData);
            if (res.code == 200) {
              this.$modal.msgSuccess("修改成功");
            } else {
              this.$modal.msgError("修改失败");
            }
          } else {
            // data;
            let defaultData = this.getDefaultData();

            data.addListMap.forEach((item) => {
              Object.assign(item, defaultData);
            });

            let res = await addTableData(data);
            if (res.code == 200) {
              this.$modal.msgSuccess("添加成功");
            } else {
              this.$modal.msgError("添加失败");
            }
          }
          // this.tableList = []
          if (this.index == 0) {
            this.getDataHandler();
          } else {
            // 判断修改是否点击了上一表格的数据
            if (this.row) {
              this.$emit("getChildData", this.index);
            } else {
              this.$emit("getEditHandle", this.index);
            }
          }
          this.defaultValue = {};
          this.open = false;
        })
        .catch((res) => {
          console.log(res);
          this.$modal.msgError("表单校验失败,请规范填写数据");
        });
    },
    getDefaultData() {
      console.log(this.queryFromWhere);
      console.log(this.preRow);
      let res = {};
      this.queryFromWhere.forEach((item) => {
        let { conditionDefaultValue, conditionField } = item;
        res[camelCase(conditionField.split(".")[1])] =
          conditionDefaultValue.includes(".")
            ? this.preRow[conditionDefaultValue.split(".")[1]]
            : conditionDefaultValue;
      });
      return res;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.defaultVal = {};
      // this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let obj = {};
      for (let key in row) {
        let modifiedTable = key
          .replace(/[A-Z]/g, (match) => `_${match}`)
          .toLowerCase();
        obj[modifiedTable] = row[key];
      }

      getInfoBySqlKey(this.templateInfo.template.sqlKey).then(({ data }) => {
        if (!data || !data.dfVueTemplate) {
          this.$message.error("当前表格未绑定表单!");
          return;
        }
        Object.assign(this.defaultValue, obj);
        // console.log(this.defaultValue)
        this.jsonData = JSON.parse(data.dfVueTemplate);
        this.open = true;
        this.title = "修改信息";
        // this.form.password = this.initPassword;
        this.$nextTick(() => {
          this.$refs.addFromRef.setData(obj);
        });
      });
      return;
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.$set(this.form, "postIds", response.postIds);
        this.$set(this.form, "roleIds", response.roleIds);
        this.open = true;
        this.title = "修改当前信息";
        this.form.password = "";
      });
    },
    // k-form-build表单变化回调
    formChangeHandler(value, label) {
      // console.log(value, label);
    },
    /** 删除按钮操作
     *
     * 删除提示信息语句（标识）
     * */
    handleDelete(row) {
      let delIds = this.ids;
      let primary = camelCase(this.templateInfo.template?.primaryKey);
      if (row[primary] != undefined && row[primary] != null) {
        delIds = [];
        delIds.push(row[primary]);
      }
      let data = {
        basicMap: {
          tableName: this.tableName,
        },
        conditionMap: {
          // id: delIds,
        },
      };
      data.conditionMap[this.templateInfo.template?.primaryKey] = delIds;
      this.$modal
        .confirm('是否确认删除"' + delIds + '"的数据项？')
        .then(function () {
          return delTableData(data);
        })
        .then(() => {
          // 调用子组件查询方法 目的是携带上子组件中的查询参数
          // this.$refs.mychild.pageList();
          this.$modal.msgSuccess("删除成功");
          this.gettableListHandler(this.tableKey);
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 0px;
  padding-bottom: 10px;
}
.item {
  margin-bottom: 18px;
}

.clearfix {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.box-card {
  width: 100%;
}
.title {
  display: block;
  max-width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
