<template>
  <el-dialog v-dialogDrag width="75%" :title="title" :close-on-click-modal="false" :before-close="cancel"
    :visible.sync="diaFlage" top="5px">
    <div style="min-height: 500px">
      <el-scrollbar style="height: 100%">
        <el-form class="form" ref="ruleForm" size="mini" :model="ruleForm" label-width="110px">
          <el-form-item v-for="(ele, key) in form" :prop="ele.fieldName" :key="key"
            :style="{ width: ele.width, padding: '5px' }" :rules="[
              {
                required: ele.require === true ? true : false,
                message: `${ele.label}为必填项`,
                 trigger:  ele.ctype === 'select'? 'change':'blur',
              },
            ]">
            <template slot="label">
              <span style="font-weight: 500">{{ ele.label }}</span>
            </template>
            <el-input
              v-if="ele.ctype === 'input'  && ele.label!='全宗号' && ele.label!='实体分类号' && ele.fieldName!='filing_year' && ele.label!='档号' && ele.label!='案卷档号' &&ele.label!='案卷级档号'&&ele.label!='文件级档号'"
              v-model="ruleForm[ele.fieldName]" :placeholder="['created_date','doc_start_time','doc_end_time'].includes(ele.fieldName) ?'例：20220101':'请输入'" clearable
              @blur="bluerInput(ele.fieldName,ruleForm[ele.fieldName])"
              :disabled="Alltable.length === 2 && tablekey == 1 &&  rusult.filter((ese)=>ese.segmentName===ele.fieldName).length!=0">
            </el-input>
            <el-input size="mini" @focus="focusYear(ruleForm[ele.fieldName])" @blur="blurYear(ruleForm[ele.fieldName])"
              v-if="ele.fieldName==='filing_year' " v-model="ruleForm[ele.fieldName]" placeholder="请输入" clearable
              :disabled="Alltable.length === 2 && tablekey == 1&&  rusult.filter((ese)=>ese.segmentName===ele.fieldName).length!=0">
            </el-input>
            <el-input size="mini" @click.native="focus" @blur="bluerInput(ele.fieldName,ruleForm[ele.fieldName])"
              v-if="ele.fieldName==='archive_ctg_no' " v-model="ruleForm[ele.fieldName]" placeholder="请输入" clearable
              :disabled="Alltable.length === 2 && tablekey == 1&&  rusult.filter((ese)=>ese.segmentName===ele.fieldName).length!=0">
            </el-input>
            <!-- {{ele}} -->
            <el-input size="mini" @click.native="focusdh" v-if="ele.fieldName==='folder_no'" readonly
              v-model="ruleForm[ele.fieldName]" placeholder="请输入" clearable
              :disabled="Alltable.length === 2 && tablekey == 1">
            </el-input>
            <el-input size="mini" @click.native="focuswjjdh" v-if="ele.fieldName==='archive_no' " readonly
              v-model="ruleForm[ele.fieldName]" placeholder="请输入" clearable>
            </el-input>
            <!-- 文本框 -->
            <el-input v-if="ele.ctype === 'text'" v-model="ruleForm[ele.fieldName]" type="textarea" placeholder="请输入"
              :rows="2" @blur="bluerText(ele.fieldName,ruleForm[ele.fieldName])"></el-input>
            <!-- 下拉框 -->
            <el-select v-if="ele.ctype === 'select'  && ele.label!='全宗号'" style="width:100%"
              v-model="ruleForm[ele.fieldName]" clearable placeholder="请选择"
              @change="bluerInput(ele.fieldName,ruleForm[ele.fieldName])"
              :disabled="Alltable.length === 2 && tablekey == 1 &&  rusult.filter((ese)=>ese.segmentName===ele.fieldName).length!=0">
              <el-option v-for="(op,index) in ele.note.note" :label="op.label" v-model="op.label" :key="index">
              </el-option>
            </el-select>
            <!-- 下拉框 --全宗 -->
            <el-select size="mini" style="width:100%" v-if="ele.label=='全宗号'  " v-model="ruleForm[ele.fieldName]"
              clearable placeholder="请选择" @change="changeQZ(ruleForm[ele.fieldName])"
              :disabled="Alltable.length === 2 && tablekey == 1">
              <el-option v-for="(op,index) in fondsList" :label="op.codeName" v-model="op.fondscode" :key="index">
              </el-option>
            </el-select>
            <!-- 年 -->
            <el-date-picker style="width:100%" v-if="ele.ctype === 'datetime'" v-model="ruleForm[ele.fieldName]"
              type="date" placeholder="选择日期时间"></el-date-picker>
            <el-date-picker v-if="ele.ctype === 'datetimerange'" v-model="ruleForm[ele.fieldName]" type="datetimerange"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="btnClass">
          <el-button type="primary" size="mini" @click="sumbit('ruleForm')">
            保存
          </el-button>
          <el-button type="info" size="mini" @click="cancel"> 返回 </el-button>
        </div>
      </el-scrollbar>
    </div>
    <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(treeRow)==='{}'">确定
            </el-button>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
  import {
    message,
    repairZero,
    repairZeros,
    getcode
  } from "@/utils/common";
  import {
    getArchiveCtgTree,
    getTableList,
  } from "@/api/system-management/fileSettings"
  import {
    getList,
    autoArchiveScope,
    autoPieceNo,
    autoYearFolderNo
  } from "@/api/archives-management/fileManagement/notStoredArchives"
  export default {
    data() {
      return {
        currentbluerObj:{}, // 当前失去焦点对象
        widthStyle: {
          width: "",
        },
        entityData: [],
        treeData: [],
        treeRow: {},
        dhList: [],
        treeLoading: false,
        NumFlage: false,
        defaultProps: {
          children: "childArchive",
          label: "codeAndName",
        },
        referenceList: [],
        oldYear: "",
        rusult: [],
        automaticData: {
          archive_no: "",
          target_table_name: "",
          id: "",
          type: 1
        }
      };
    },
    filters: {
      widthTransformation(status) {
        const statusMap = {
          8: "33%",
          12: "50%",
          24: "100%",
        };
        return statusMap[status];
      },
    },
    props: {
      fondsList: {
        type: Array,
        default: () => [],
      },
      diaFlage: {
        type: Boolean,
        default: () => false,
      },
      form: {
        type: Array,
        default: () => [],
      },
      ruleForm: {
        type: Object,
        default: () => {},
      },
      classTree: {
        type: Object,
        default: () => {},
      },
      title: {
        type: String,
        default: () => "",
      },
      tablekey: {
        type: Number,
        default: () => null,
      },
      Alltable: {
        type: Array,
        default: () => [],
      },
    },
    methods: {
      //选择实体分类号
      submitEntity() {
        this.ruleForm.archive_ctg_no = this.treeRow.codeAndName
        this.$refs["ruleForm"].validateField('archive_ctg_no')
        this.focusdh()
        this.cancels()
      },
      // 点击树节点
      handleNodeClick(data, node) {
        this.treeRow = data
        let info = {
          archiveCtgCode: data.archiveCtgCode,
          fondscode: this.ruleForm.fonds_no,
          page: 1,
          limit: 1000
        }
        getTableList(info).then(res => {
          this.entityData = res.body.list
        })
      },
      focus() {
        if (!this.ruleForm.fonds_no) {
          message('warning', '请先选择全宗号', 2000)
          return
        }
        if (!this.ruleForm.filing_year) {
          message('warning', '请先输入年度', 2000)
          return
        }
        this.treeLoading = true
        let data = {
          fondscode: this.ruleForm.fonds_no,
          year: this.ruleForm.filing_year
        }
        this.treeData = [{
          id: '-1',
          archiveCtgCode: "",
          archiveCtgName: "",
          archiveCtgSort: "1",
          childArchive: [],
          classType: "L"
        }]
        this.fondsList.forEach(item => {
          if (item.fondscode === this.ruleForm.fonds_no) {
            this.treeData[0].codeAndName = " [" + item.fondscode + "] " + item.fondsname
            this.treeData[0].archiveCtgCode = item.fondscode
          }
        })
        getArchiveCtgTree(data).then(res => {
          if (!res.body.list.length) {
            message("warning", "请先配置当前年份的实体分类号", 3000)
            return
          }
          this.treeData[0].childArchive = res.body.list
          this.NumFlage = true
          this.treeLoading = false
        })
      },
      //年度聚焦
      focusYear(value) {
        this.oldYear = value
      },
      //年度失焦
      blurYear(value) {
        if (value.length != 4) {
          message("warning", "请输入正确的年度", 3000)
          if (this.Alltable.length === 1) {
            if (this.ruleForm.hasOwnProperty("archive_no")) {
              this.ruleForm["archive_no"] = ""
            } else {
              this.ruleForm["folder_no"] = ""
            }
            if (this.oldYear != value) {
              this.clearYear()
            }
          }
          return
        }
        if (this.ruleForm['fonds_no']) {
          if (this.oldYear != value) {
            this.clearYear()
          }
          if (this.Alltable.length === 3) {
            // this.focusdh()
          }
        }
      },
      changeQZ(val) {
        if (val && this.ruleForm['filing_year']) {
          this.clearYear()
        }
      },
      //年度全宗清空
      clearYear() {
        let data = {
          classId: this.classTree.id,
          fondscode: this.ruleForm.fonds_no,
          year: this.ruleForm.filing_year
        }
        getList(data).then(res => {
          if (!res.body.list.length) {
            message("warning", "请先配置当前年度的档号规则", 3000)
            this.referenceList = []
          }
          this.referenceList = res.body.list.filter(ele => ele.segmentName != 'fonds_no' && ele.segmentName !=
            'item_id' && ele.segmentName != 'filing_year')
          this.referenceList.forEach(item => {
            if (item.segmentName != 'retention') {
              this.ruleForm[item.segmentName] = ""
            }
          })
          if (this.Alltable.length === 1) {
            if (this.ruleForm.hasOwnProperty("archive_no")) {
              this.ruleForm["archive_no"] = ""
            } else {
              this.ruleForm["folder_no"] = ""
            }
          }
        })
      },
      //文件级档号 
      focuswjjdh() {
        if (!this.ruleForm.piece_no) {
          message('warning', '请先输入件号', 2000)
          return
        }
        if (this.Alltable.length === 2 || this.Alltable.length === 3) {
          this.ruleForm.archive_no = this.ruleForm.folder_no + "-" + repairZero(this.ruleForm.piece_no)
        }
      },
      //简化档号或案卷级档号设置
      focusdh() {
        if (!this.ruleForm.fonds_no) {
          message('warning', '请先选择全宗号', 2000)
          return
        }
        if (!this.ruleForm.filing_year) {
          message('warning', '请先输入归档年度', 2000)
          return
        }
        let data = {
          classId: this.classTree.id,
          fondscode: this.ruleForm.fonds_no,
          year: this.ruleForm.filing_year
        }
        getList(data).then(res => {
          this.rusult = res.body.list
          if (!this.rusult.length) {
            message("warning", "请先配置当前年度的档号设置", 3000)
            this.referenceList = []
            return
          }
          try {
            this.rusult.forEach(item => {
              for (let key in this.ruleForm) {
                if (item.segmentName === key && !this.ruleForm[key]) {
                  throw (item)
                }
                if (item.segmentName === key && this.ruleForm[key]) {
                  this.$set(item, "value", this.ruleForm[key])
                }
              }
            })
          } catch (val) {
            if (val.segmentName != "piece_no" && val.segmentName != "year_folder_no") {
              message("warning", `请填写${val.segmentChnName}`, 2000)
              return
            }
          }
          if (this.Alltable.length === 1 && !this.ruleForm.hasOwnProperty("folder_no")) {
            this.automaticData.target_table_name = this.Alltable[this.tablekey].tableName
            this.getJh()
          }
          if (this.Alltable.length === 1 && this.ruleForm.hasOwnProperty("folder_no")) {
            this.automaticData.target_table_name = this.Alltable[this.tablekey].tableName
            this.getAjh()
          }
          if (this.Alltable.length === 2 && this.tablekey == 1) {
            this.automaticData.target_table_name = this.Alltable[this.tablekey].tableName
            this.getCtJh()
          }
          if (this.Alltable.length === 2 && this.tablekey == 0) {
            this.automaticData.target_table_name = this.Alltable[this.tablekey].tableName
            this.getAjh()
          }
          if (this.Alltable.length === 3 && this.tablekey === 1) {
            this.automaticData.target_table_name = this.Alltable[this.tablekey].tableName
            this.getThreeAjh()
          }
          if (this.Alltable.length === 3 && this.tablekey === 2) {
            this.automaticData.target_table_name = this.Alltable[this.tablekey].tableName
            this.getThreeJh()
          }
        })
      },
      bluerInput(name, value) {
        this.currentbluerObj = {name:name,maxNum:value};
        if (this.referenceList.length && value) {
          if (this.referenceList.filter(ele => ele.segmentName === name).length) {
            this.focusdh()
          }
        }
        if ((name === "year_folder_no" && !value) || ((name === "piece_no" && this.Alltable.length === 1) && !value)) {
          this.focusdh()
        }
        if (name === "piece_no") {
          if (this.Alltable.length === 2) {
            this.focuswjjdh()
          }
        }
      },

      // //得到第三层案件号
      getThreeJh() {
        this.automaticData.archive_no = this.ruleForm["folder_no"]
        autoPieceNo(this.automaticData).then(res => {
          // [...this.rusult].pop().value = res.body.num
          this.ruleForm["piece_no"] = res.body.num
          this.focuswjjdh()
          // this.automatic()
        })
      },
      // //得到第三层案卷号
      getThreeAjh() {
        this.automaticData.archive_no = ""
        this.rusult.forEach((item, key) => {
          if (key != this.rusult.length - 1) {
            this.automaticData.archive_no = this.automaticData.archive_no + (item.segmentChnName === "实体分类号" ? item
              .value.substring(item.value.indexOf("[") + 1, item.value.indexOf("]")) : (item.segmentVal ===
                "值" ? getcode(item,
                  this.form) :
                (
                  item.segmentZero === "取值" ? item.value :
                  repairZero(item.value)))) + (key === this.rusult.length - 2 ? "" : item.segmentSeparator)
          }
        })
        if(this.title=='新增'){
          if(this.currentbluerObj.name == 'year_folder_no'){
            this.automatic()
          }else{
            autoYearFolderNo(this.automaticData).then(res => {
              [...this.rusult].pop().value = res.body.num
              this.ruleForm[[...this.rusult].pop().segmentName] = res.body.num
              this.automatic()
            })
          }
          
        }else{
          autoYearFolderNo(this.automaticData).then(res => {
            //[...this.rusult].pop().value = res.body.num
            [...this.rusult].pop().value = this.ruleForm.year_folder_no;
            //this.ruleForm[[...this.rusult].pop().segmentName] = res.body.num;
            this.ruleForm[[...this.rusult].pop().segmentName] = this.ruleForm.year_folder_no;
            this.automatic()
          })
        }
      },
      //得到案卷号
      getAjh() {
        this.automaticData.archive_no = ""
        this.rusult.forEach((item, key) => {
          if (key != this.rusult.length - 1) {
            this.automaticData.archive_no = this.automaticData.archive_no + (item.segmentChnName === "实体分类号" ? item
              .value.substring(item.value.indexOf("[") + 1, item.value.indexOf("]")) : (item.segmentVal ===
                "值" ? getcode(item,
                  this.form) :
                (
                  item.segmentZero === "取值" ? item.value :
                  repairZeros(item.value)))) + (key === this.rusult.length - 2 ? "" : item.segmentSeparator)
          }
        })
        // 如果是新增 首先自动带出案卷号，同时支持手动修改；如果是修改回显后支持手动修改
        if(this.title=='新增'){
          if(this.currentbluerObj.name == 'year_folder_no'){
            this.automatic()
          }else{
            autoYearFolderNo(this.automaticData).then(res => {
              [...this.rusult].pop().value = res.body.num
              this.ruleForm[[...this.rusult].pop().segmentName] = res.body.num
              this.automatic()
            })
          }
          
        }else{
          autoYearFolderNo(this.automaticData).then(res => {
            [...this.rusult].pop().value = this.ruleForm.year_folder_no;
            this.ruleForm[[...this.rusult].pop().segmentName] = this.ruleForm.year_folder_no;
            this.automatic()
          })
        }
      },
      //得到传统的卷内件号、
      getCtJh() {
        this.automaticData.archive_no = this.ruleForm["folder_no"]
        autoPieceNo(this.automaticData).then(res => {
          // [...this.rusult].pop().value = res.body.num
          this.ruleForm["piece_no"] = res.body.num
          this.focuswjjdh()
          // this.automatic()
        })
      },
      //得到简化件号
      getJh() {
        this.automaticData.archive_no = ""
        this.rusult.forEach((item, key) => {
          if (key != this.rusult.length - 1) {
            this.automaticData.archive_no = this.automaticData.archive_no + (item.segmentChnName === "实体分类号" ? item
              .value.substring(item.value.indexOf("[") + 1, item.value.indexOf("]")) : (item.segmentVal ===
                "值" ? getcode(item,
                  this.form) :
                (
                  item.segmentZero === "取值" ? item.value :
                  repairZero(item.value)))) + (key === this.rusult.length - 2 ? "" : item.segmentSeparator)
          }

        })
        if(this.title=='新增'){
          if(this.currentbluerObj.name == 'piece_no'){
            this.automatic()
          }else{
            autoPieceNo(this.automaticData).then(res => {
              [...this.rusult].pop().value = res.body.num;
              this.ruleForm[[...this.rusult].pop().segmentName] = res.body.num;
              this.automatic()
            })
          }
          
        }else{
          autoPieceNo(this.automaticData).then(res => {
            //[...this.rusult].pop().value = res.body.num
            [...this.rusult].pop().value = this.ruleForm.piece_no;
            //this.ruleForm[[...this.rusult].pop().segmentName] = res.body.num;
            this.ruleForm[[...this.rusult].pop().segmentName] = this.ruleForm.piece_no;
            this.automatic()
          })
        }

      },
      //自动生成档号
      automatic() {
        //判断是简化archive_no，还是传统folder_no
        if (this.ruleForm.hasOwnProperty("folder_no")) {
          this.ruleForm.folder_no = ""
          this.rusult.forEach((item, key) => {
            this.ruleForm.folder_no = this.ruleForm.folder_no + (item.segmentChnName === "实体分类号" ? item
              .value.substring(item.value.indexOf("[") + 1, item.value.indexOf("]")) : (item.segmentVal ===
                "值" ? getcode(item,
                  this.form) :
                (
                  item.segmentZero === "取值" ? item.value : (item.segmentName === "year_folder_no" ? repairZeros(
                    item.value) : repairZero(item.value))))) + (key === this.rusult.length - 1 ? "" : item
              .segmentSeparator)
          })
        }
        if (this.ruleForm.hasOwnProperty("archive_no")) {
          this.ruleForm.archive_no = ""
          this.rusult.forEach((item, key) => {
            this.ruleForm.archive_no = this.ruleForm.archive_no + (item.segmentChnName === "实体分类号" ? item
              .value.substring(item.value.indexOf("[") + 1, item.value.indexOf("]")) : (item.segmentVal ===
                "值" ? getcode(item,
                  this.form) :
                (
                  item.segmentZero === "取值" ? item.value :
                  repairZero(item.value)))) + (key === this.rusult.length - 1 ? "" : item.segmentSeparator)
          })
        }
      },
      bluerText(name, value) {
        if (name === "maintitle" && this.ruleForm.fonds_no) {
          let data = {
            fondscode: this.ruleForm.fonds_no,
            maintitle: value
          }
          autoArchiveScope(data).then(res => {
            if (res.body.archiveCtgCode && res.body.retention) {
              this.ruleForm.archive_ctg_no = res.body.archiveCtgCode
              this.ruleForm.retention = res.body.retention
              this.focusdh()
            }
          })
        }
      },
      sumbit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit("sumbit", this.ruleForm);
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      resetFields() {
        this.$refs['ruleForm'].resetFields()
      },
      //返回
      cancel() {
        this.$emit("cancel");
      },
      cancels() {
        this.NumFlage = false
        this.treeRow = {}
      }
    },
  };

</script>
<style lang="scss" scoped>
  .form {
    padding: 15px;
    text-align: right;
    display: flex;
    flex-wrap: wrap;
  }

  .add {
    height: 30px;
    line-height: 30px;
    display: flex;
    margin: 8px 0px;
  }

  .btnClass {
    padding: 20px 40px;
    text-align: right;
  }

  .labelTitle {
    width: 100px;
    text-align: right;
    font-size: 14px;
    font-weight: 600;
  }

  .enClass {
    display: flex;
    justify-content: space-around;

    .treeClass {
      width: 30%
    }

    .tableClass {
      width: 69%
    }
  }

</style>
