<template>
  <div>
    <div style="padding:10px 0">
      <el-button size="mini" type="primary" @click="moveBottom"> 移动到下表格</el-button>
      <el-button @click="handleStateMent()" size="mini" type="primary">报表设计</el-button>
      <el-button @click="createReport()" size="mini" type="primary">报表预览</el-button>
      <el-button @click="querySet()" size="mini" type="primary">查询设置</el-button>
      <el-button @click="getDirTreeSearch()" size="mini" type="primary">目录序列树</el-button>
    </div>
    <el-table v-loading="tableLoading" :data='tableData' border @selection-change="handleSelectionChange"
      @sort-change="customSortSearch($event)"
      max-height="300">
      <el-table-column align="center" type="selection" width="60"></el-table-column>
      <el-table-column sortable v-for="(ele, index) in JSON.parse(Alltable.tableShow)" :key="index" :prop="ele.columnName"
        :min-width="ele.width" :label="ele.columnChnName" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="ele.columnName === 'fonds_no'">
            {{ (fondsList.filter(f => f.fondscode === scope.row[ele.columnName])[0] || {}).codeName }}
          </span>
          <span v-if="ele.columnName !== 'fonds_no'">{{ scope.row[ele.columnName] }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
      layout="total, prev, pager, next, sizes" :page-size="pagination.pageSize" :page-sizes="[10, 20, 30, 50]"
      :current-page="pagination.pageNum" :total="pagination.total">
    </el-pagination>
    <div style="padding:5px 0">
      <el-button type="primary" @click="moveUp" size="mini">移动到上表格</el-button>
      <el-button type="primary" @click="file" size="mini" v-if="showButtons.gd">文件归档</el-button>
    </div>
    <el-table :data='tableTwo' @selection-change="handleSelectionChanges" border max-height="300">
      <el-table-column align="center" type="selection" width="60"></el-table-column>
      <el-table-column sortable v-for="(ele, index) in JSON.parse(Alltable.tableShow)" :key="index" :prop="ele.columnName"
        :min-width="ele.width" :label="ele.columnChnName" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="ele.columnName === 'fonds_no'">
            {{ (fondsList.filter(f => f.fondscode === scope.row[ele.columnName])[0] || {}).codeName }}
          </span>
          <span v-if="ele.columnName !== 'fonds_no'">{{ scope.row[ele.columnName] }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :close-on-click-modal="false" v-dialogDrag title="文件归档" :visible.sync="fileStatus" width="30%" top="0px"
      :before-close="cancel">
      <el-form :model="form" label-width="100px" :rules="rules" ref="ruleForm">
        <el-form-item label="全宗号：" prop="fondscode">
          <el-select size="mini" v-model="form.fondscode" @change="changeFonds">
            <el-option v-for="(op,index) in fondsList" :label="op.codeName" v-model="op.fondscode" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年度：" prop="year">
          <el-input-number size="mini" v-model="form.year" controls-position="right" @blur="blur">
          </el-input-number>
        </el-form-item>
        <el-form-item label="目标门类：" prop="targetClassId">
          <el-select size="mini" v-model="form.targetClassId" @change="changeClass">
            <el-option v-for="(op,index) in classList" :label="op.className" :value="op.id" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-for="(item,key) in dhForm" :key="key">
          <el-form-item
            v-if="item.segmentName!='fonds_no'  && item.segmentName!='filing_year' && item.segmentName!='piece_no'"
            label-width="100px" :prop="item.segmentChnName">
            <span slot="label">{{item.segmentChnName}}</span>
            <el-input v-if="item.segmentName==='archive_ctg_no'" @click.native="focus" style="width:60%" size="mini"
              v-model="item.value">
            </el-input>
            <el-select v-if="item.segmentName==='retention'" style="width:60%" size="mini" v-model="item.value">
              <el-option v-for="(ele,index) in safekeeping" :key="index" :label="ele.label"
                :value="item.segmentVal==='值'?ele.value:ele.label">
              </el-option>
            </el-select>
            <el-input
              v-if="item.segmentName!='archive_ctg_no' &&item.segmentName!='retention' && item.segmentName!='piece_no' "
              style="width:60%" size="mini" v-model="item.value"></el-input>
          </el-form-item>
        </div>
        <el-form-item label=" ">
          <el-button :disabled="!dhForm.length" @click="submit()" size="mini" type="primary">确定</el-button>
          <el-button @click="cancel" size="mini" type="info">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-dialogDrag width="60%" title="选择实体分类号" :close-on-click-modal="false" :visible.sync="NumFlage"
      :before-close="cancels" append-to-body top="10px">
      <div class="enClass">
        <el-card class="treeClass">
          <el-tree v-loading="treeLoading" highlight-current :data="treeData" :props="defaultProps" default-expand-all
            @node-click="handleNodeClick">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <!--可以根据情况，以数据类型来显示不同的图标或图片-->
              <svg-icon icon-class="wjj" style="margin-right: 5px; color: rgb(255, 207, 92)"
                v-if="data.classType === 'L'" class="iconfont icon-folder-open-fill" />
              <svg-icon icon-class="wj" style="margin-right: 5px; color: rgb(255, 207, 92)" v-else
                class="iconfont icon-wenjian" />
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </el-card>
        <el-card class="tableClass">
          <el-table border :data='entityData' max-height="300">
            <el-table-column align="center" type="index" width="60" label="序号"></el-table-column>
            <el-table-column align="center" prop="archiveScope" label="归档范围"></el-table-column>
            <el-table-column align="center" prop="retention" label="保管期限"></el-table-column>
          </el-table>
          <div style="padding:5px 0;text-align:right">
            <el-button @click="submitEntity" size="mini" type="primary" :disabled="JSON.stringify(entreeRow)==='{}'">确定
            </el-button>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { clearObjValue, message } from "@/utils/common";
import {
  getArchiveCtgTree,
  getTableList,
} from "@/api/system-management/fileSettings";

import { mapState } from "vuex";
export default {
  props: {
    fondsList: {
      type: Array,
      default: () => [],
    },
    Alltable: {
      type: Object,
      default: () => {},
    },
    treeRow: {
      type: Object,
      default: () => {},
    },
    showButtons: {
      type: Object,
      default: () => {},
    },
    fondsList: {
      type: Array,
      default: () => [],
    },
    safekeeping: {
      type: Array,
      default: () => [],
    },
    classList: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapState({
      pagination: (state) => state.filing.pagination,
    }),
    dhForm: {
      get() {
        return this.$store.state.filing.dhForm;
      },
      set(val) {
        this.$store.state.filing.dhForm = val;
      },
    },
    tableLoading: {
      get() {
        return this.$store.state.filing.tableLoading;
      },
      set(val) {
        this.$store.state.filing.tableLoading = val;
      },
    },
    tableData: {
      get() {
        return this.$store.state.filing.tableData;
      },
      set(val) {
        this.$store.state.filing.tableData = val;
      },
    },
  },

  data() {
    return {
      rules: {
        fondscode: [
          {
            required: true,
            message: "请输入全宗号",
            trigger: "blur",
          },
        ],
        year: [
          {
            required: true,
            message: "请输入归档年度",
            trigger: "blur",
          },
        ],
        targetClassId: [
          {
            required: true,
            message: "请选择门类",
            trigger: "change",
          },
        ],
      },
      multipleSelection: [],
      multipleSelections: [],
      tableTwo: [],
      fileStatus: false,
      form: {
        fondscode: "",
        year: undefined,
        targetClassId: "",
      },
      dhArr: [],
      treeData: [],
      treeLoading: false,
      NumFlage: false,
      entityData: [],
      defaultProps: {
        children: "childArchive",
        label: "codeAndName",
      },
      entreeRow: {},
    };
  },
  methods: {
    customSortSearch({ column}){
      let orderObj = {};
      orderObj.sortKey = column.property;
      orderObj.sortType = column.order=='descending'?'desc':'';
      this.$emit('customSort',orderObj)
    },
    handleStateMent() {
      this.$emit("handleStateMent");
    },
    createReport() {
      this.$emit("createReport",this.multipleSelection);
    },
    querySet() {
      this.$emit("handleQuery");
    },
    getDirTreeSearch(){
      this.$emit('getDirTreeSearch');
    },
    // 点击树节点
    handleNodeClick(data, node) {
      this.entreeRow = data;
      let info = {
        archiveCtgCode: data.archiveCtgCode,
        fondscode: this.form.fondscode,
        page: 1,
        limit: 1000,
      };
      getTableList(info).then((res) => {
        this.entityData = res.body.list;
      });
    },
    focus() {
      this.treeLoading = true;
      let data = {
        fondscode: this.form.fondscode,
        year: this.form.year,
      };
      getArchiveCtgTree(data)
        .then((res) => {
          if (!res.body.list.length) {
            message("warning", "请先配置当前年份的实体分类号", 3000);
            return;
          }
          this.treeData = res.body.list;
          this.NumFlage = true;
          this.treeLoading = false;
        })
        .catch((err) => {
          this.treeLoading = false;
        });
    },
    changeFonds() {
      if (this.form.targetClassId && this.form.year) {
        let data = {
          fondscode: this.form.fondscode,
          targetClassId: this.form.targetClassId,
          filingYear: this.form.year,
        };
        this.$store
          .dispatch("filing/showFileArchive", data)
          .then((res) => {
            this.dhForm.forEach((item) => {
              if (item.segmentName === "fonds_no") {
                item.value = this.form.fondscode;
              }
              if (item.segmentName === "filing_year") {
                item.value = this.form.year;
              }
              item.filingYear = this.form.year;
              item.id = 0;
            });
            // dhForm
          })
          .catch((err) => {
            this.dhForm = [];
          });
      }
    },
    blur() {
      if (this.form.year.toString().length != 4) {
        message("warning", "请输入正确的年度", 2000);
        return;
      }
      if (this.form.fondscode && this.form.targetClassId) {
        let data = {
          fondscode: this.form.fondscode,
          targetClassId: this.form.targetClassId,
          filingYear: this.form.year,
        };
        this.$store
          .dispatch("filing/showFileArchive", data)
          .then((res) => {
            this.dhForm.forEach((item) => {
              if (item.segmentName === "fonds_no") {
                item.value = this.form.fondscode;
              }
              if (item.segmentName === "filing_year") {
                item.value = this.form.year;
              }
              item.filingYear = this.form.year;
              item.id = 0;
            });
          })
          .catch((err) => {
            this.dhForm = [];
          });
      }
    },
    changeClass() {
      if (!this.form.year) {
        message("warning", "请输入年度", 3000);
        return;
      }
      if (!this.form.fondscode) {
        message("warning", "请选择全宗", 3000);
        return;
      }
      let data = {
        fondscode: this.form.fondscode,
        targetClassId: this.form.targetClassId,
        filingYear: this.form.year,
      };
      this.$store
        .dispatch("filing/showFileArchive", data)
        .then((res) => {
          this.dhForm.forEach((item) => {
            if (item.segmentName === "fonds_no") {
              item.value = this.form.fondscode;
            }
            if (item.segmentName === "filing_year") {
              item.value = this.form.year;
            }
            item.filingYear = this.form.year;
            item.id = 0;
          });
        })
        .catch((err) => {
          this.dhForm = [];
        });
    },
    moveBottom() {
      if (!this.multipleSelection.length) {
        message("warning", "请先至少选择一个项目", 3000);
        return;
      }
      this.multipleSelection.forEach((item) => {
        this.tableTwo.push(item);
      });
      this.multipleSelection.forEach((item) => {
        this.tableData = this.tableData.filter((a) => a.id != item.id);
      });
    },
    moveUp() {
      if (!this.multipleSelections.length) {
        message("warning", "请先至少选择一个项目", 3000);
        return;
      }
      this.multipleSelections.forEach((item) => {
        this.tableData.push(item);
      });
      this.multipleSelections.forEach((item) => {
        this.tableTwo = this.tableTwo.filter((a) => a.id != item.id);
      });
    },
    file() {
      if (!this.multipleSelections.length) {
        message("warning", "请先至少选择一个项目", 3000);
        return;
      }
      this.dhForm = [];
      this.form.fondscode = this.multipleSelections[0].fonds_no;
      this.form.year = this.multipleSelections[0].year;
      this.form.targetClassId = "";
      this.fileStatus = true;
    },
    submit() {
      let data = {
        targetClassId: this.form.targetClassId,
        sourceClassId: this.treeRow.id,
        ids: this.multipleSelections.map((ele) => ele.id).join(","),
        archivenoFormatList: this.dhForm,
      };
      try {
        this.dhForm.forEach((ele) => {
          if (!ele.value && ele.segmentName != "piece_no") {
            throw ele.segmentChnName;
          }
        });
      } catch (err) {
        message("warning", `请填写${err}`, 3000);
      }
      // if (!this.dhForm.filter(ele => !ele.value).length) {
      this.$store.dispatch("filing/createArchives", data).then((res) => {
        this.tableTwo = [];
        this.$emit("handleNodeClick", this.treeRow);
        this.fileStatus = false;
      });
      // }
    },
    cancel() {
      this.fileStatus = false;
      clearObjValue(this.form);
      this.form.year = undefined;
    },
    cancels() {
      this.NumFlage = false;
    },
    submitEntity() {
      this.dhForm.forEach((item) => {
        if (item.segmentChnName === "实体分类号") {
          item.value = this.entreeRow.codeAndName;
        }
      });
      this.cancels();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChanges(val) {
      this.multipleSelections = val;
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.$emit("getData", 0);
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.pageNum = 1;
      this.$emit("getData", 0);
    },
  },
};
</script>
<style lang="scss" scoped>
.enClass {
  display: flex;
  justify-content: space-around;

  .treeClass {
    width: 30%;
  }

  .tableClass {
    width: 69%;
  }
}
</style>
