<template>
    <div>
      <el-dialog title="报表设计" top="12" :visible.sync="visible" width="96%" v-dialogDrag :close-on-click-modal="false"
        :before-close="cancel">
        <div class="dia-box">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form ref="form" label-width="80px">
                <el-form-item label="excle名称">
                  <el-select size="mini" style="width:70%" placeholder="请选择导入的excel" v-model="selectId"
                    @change="ysjBtn(selectId)">
                    <el-option v-for="(item,key) in options" :key="key" :label="item.templateName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
  
              <el-table :data="tableData" border max-height="500px" @row-click="rowDblclick" show-overflow-tooltip
                :row-style="{height: '50px'}" @selection-change="handleSelectionChange" @select="handleSelect">
                <el-table-column type="selection" width="100">
                </el-table-column>
                <el-table-column prop="excelParameter" label="模板字段名称" align="center">
                </el-table-column>
                <el-table-column prop="columnChnName" label="字段中文名" align="center">
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12">
              <statement-Table ref="statement" />
            </el-col>
          </el-row>
          <div style="text-align:right;margin:15px 0 20px;">
            <el-button type="primary" size="mini" @click="submit">
              生成报表
            </el-button>
            <el-button size="mini" @click="cancel">关闭</el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog v-dialogDrag title="选择目标字段" :visible.sync="zdStatus" :close-on-click-modal="false" width="40%"
        :before-close="cancelsZds">
        <el-form ref="ruleForm" :model="form" label-width="120px" style="padding:10px 20px">
          <el-form-item label="源表字段：">
            <el-input size="mini" style="width:80%" v-model="form.Sname" disabled></el-input>
          </el-form-item>
          <el-form-item label="目标表字段：" prop="Tname">
            <el-select filterable size="mini" style="width:80%" v-model="form.Tname" @change="selectChange" placeholder="请输入关键字搜索">
              <el-option v-for="(item,key)  in DList" :key="key" :label="item.columnChnName" :value="item.columnChnName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-button @click="save" size="mini" type="primary">保存 </el-button>
            <el-button @click="backout()" size="mini" type="primary">撤销 </el-button>
          </el-form-item>
        </el-form>
  
      </el-dialog>
    </div>
  
  </template>
  
  <script>
  import { message } from "@/utils/common";
  import {
    queryEntity,
    showPdf,
    saveReportMatching,
    queryEntityLevel,
    defaultReportMatching,
  } from "@/api/reportTemplate";
  import { getData } from "@/api/dataManagement/dataImport";
  import statementTable from "./statementTable.vue";
  export default {
    props: {
      visible: {
        type: Boolean,
        default: () => false,
      },
    },
    components: {
      statementTable,
    },
    data() {
      return {
        treeRow: {},
        treeData: [],
        options: [],
        tableData: [],
        selectId: "",
        zdStatus: false,
        fileType: null,
        DList: [],
        newDList: [],
        multipleSelection: [],
        cyclicType: 0,
        form: {
          Sname: "",
          tableId: null,
        },
        rowData: {},
        templatePath: "",
        rules: [],
        picUrl: undefined,
        templateName: "",
        newJsonp: {},
        selectChangeVal: "",
      };
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.tableData.forEach((item) => {
          val.forEach((k) => {
            if (item.excelParameter == k.excelParameter) {
              this.$set(item, "cyclicType", 1);
            }
          });
        });
      },
      handleSelect(selection, row) {
        this.tableData.forEach((item) => {
          if (item.excelParameter == row.excelParameter) {
            if (this.multipleSelection.length) {
              if (item.cyclicType == 1) {
                this.$nextTick(() => {
                  this.$set(item, "cyclicType", 0);
                });
              } else if (item.cyclicType == 0) {
                this.$nextTick(() => {
                  this.$set(item, "cyclicType", 1);
                });
              }
            }
          }
        });
      },
      backout() {
        this.form.Tname = "";
      },
      save() {
        if (this.form.Tname === "") {
          return;
        }
        this.DList.forEach((item, index) => {
          if (item.columnChnName === this.selectChangeVal) {
            this.tableData.forEach((k, j) => {
              if (k.tableId === this.form.tableId) {
                this.$set(k, "columnChnName", item.columnChnName);
                this.$set(k, "columnName", item.columnName);
                this.$set(k, "tableName", item.tableName);
              }
            });
          }
        });
        this.form.Tname = "";
        this.zdStatus = false;
      },
      cancel() {
        this.tableData = [];
        this.$refs.statement.picUrl = undefined;
        this.selectId = "";
        this.$emit("cancel");
      },
      submit() {
        let rname;
        let dataAll = [];
        this.treeData.forEach((item) => {
            if(item.childClass[0].childClass.length==0){ // 二层
                return item.childClass.forEach((i)=>{
                    if (i.className == this.treeRow.className && i.pid == this.treeRow.pid) {
                        rname = item;
                    }
                })
            }else{ // 三层
                return item.childClass.forEach((i) => {
                    i.childClass.forEach((k) => {
                        if (k.className == this.treeRow.className && k.pid == this.treeRow.pid) {
                            rname = item;
                        }
                    });
                });
            }
            
        });
        this.tableData.forEach((item) => {
          let data = {
            companyId: rname.id,
            classId: this.treeRow.id,
            fileType: this.fileType,
            reportName: this.templateName,
            templatePath: this.templatePath,
            cyclicType: item.cyclicType || 0,
            templateField: item.excelParameter,
            sourceField: item.columnName,
          };
          dataAll.push(data);
        });
        saveReportMatching(dataAll).then((res) => {
          if (res.code === "100") {
            this.$message.success("匹配成功");
            this.tableData = [];
            this.$refs.statement.picUrl = undefined;
            this.selectId = "";
            this.$emit("cancel");
          }
        });
      },
      async ysjBtn(val) {
        this.options.map((item, index) => {
          if (item.id === val) {
            this.templatePath = item.templatePath;
            this.templateName = item.templateName;
            return item.excelParameter.map((k, i) => {
              return {
                excelParameter: k,
                tableId: i,
              };
            });
          }
        });
        let data = {
          entityId: this.rowData.entityId,
          templateId: val,
        };
        this.showPdf();
        const res = await defaultReportMatching(data);
        if (res.code == "100") {
          this.tableData = res.body.list;
          this.tableData.forEach((k, j) => {
            this.$set(k, "tableId", j);
          });
        }
        this.getEntityLevel();
      },
      showPdf() {
        let data = {
          templatePath: this.templatePath,
          token: sessionStorage.getItem("token"),
        };
        showPdf(data).then((res) => {
          let arr = [];
          arr.push(res);
          this.$refs.statement.picUrl = window.URL.createObjectURL(
            new Blob(arr, { type: "application/pdf" })
          );
        });
      },
      selectChange(val) {
        this.$nextTick(() => {
          this.form.Tname = val;
        });
        this.selectChangeVal = val;
      },
      rowDblclick(row) {
        this.getTableFieldList();
        this.form.Sname = row.excelParameter;
        this.form.tableId = row.tableId;
        this.zdStatus = true;
      },
      // 撤销
      cancelsZds() {
        this.form.Tname = "";
        this.zdStatus = false;
      },
      getList() {
        let data = {
          templateName: "",
          page: "",
          limit: "",
        };
        queryEntity(data).then((res) => {
          if (res.code === "100") {
            let { body } = res;
            this.options = body.list.map((item) => {
              return {
                excelParameter: item.excelParameter.split(","),
                templatePath: item.templatePath,
                templateName: item.templateName,
                id: item.id,
              };
            });
          }
        });
      },
      getTableFieldList() {
        let data = { entityId: this.rowData.entityId };
        let _this = this;
        getData(data).then((res) => {
          const { body } = res;
          if (res.code == "100") {
            _this.DList = body.list1;
          }
        });
      },
      getEntityLevel() {
        queryEntityLevel({ entityId: this.rowData.entityId }).then((res) => {
          if (res.code === "100") {
            this.fileType = res.body.entityLevel;
          }
        });
      },
    },
    mounted() {
      this.getList();
    },
  };
  </script>
  <style lang="scss" scoped>
  ::v-deep
    .el-table__header
    .el-table-column--selection
    .cell
    .el-checkbox:after {
    color: #0b142b;
    content: "循环";
    text-align: center;
    margin-left: 10px;
    font-weight: bold;
  }
  </style>
  