<template>
  <div class="rightBox">
    <div class="rightTitle">门类定制设置</div>
    <el-form ref="formData" :model="formData" label-width="130px" :rules="rules" class="rightForm">
      <el-form-item label="类目名称：" prop="className">
        <el-input v-model="formData.className" size="mini" style="width: 60%">
        </el-input>
      </el-form-item>
      <el-form-item label="类目类型：" prop="classType">
        <el-radio-group v-model="formData.classType" :disabled="formDataFlage.classType" style="width: 60%"
          @change="changeClassType(formData.classType)">
          <el-radio label="L">中间门类</el-radio>
          <el-radio label="C">底层门类</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="类目排序：" prop="classOrder">
        <el-input v-model="formData.classOrder" size="mini" style="width: 60%"></el-input>
      </el-form-item>
      <el-form-item label="元数据方案：">
        <el-select v-model="formData.ClassProgramme" size="mini" style="width: 60%" placeholder="请输入"
          :disabled="formDataFlage.ClassProgramme">
          <el-option v-for="(item, key) in retentionList" :key="key" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实体类型">
        <el-select style="width: 60%" :disabled="formDataFlage.EntityType" v-model="formData.EntityType" size="mini"
          placeholder="请输入" @change="ChangeEntity">
          <el-option v-for="(item, key) in EntityList" :key="key" :label="item.entityName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="预归档：" prop="filing">
        <el-radio-group style="width: 60%" v-model="formData.filing" :disabled="formDataFlage.filing">
          <el-radio :label="1">显示</el-radio>
          <el-radio :label="2">不显示</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="下属编目表：" v-if="formData.EntityList.length">
      </el-form-item>
      <div v-for="(item, key) in formData.EntityList" :key="key" class="cateList">
        <span>第{{ key + 1 }}层：</span>
        <el-input style="width: 50%; margin: 0 5px" size="mini" disabled v-model="item.entityName"></el-input>
        <el-button type="primary" size="mini" @click="look(item)">结构</el-button>
        <el-button type="primary" size="mini" @click="rename(item)">重命名</el-button>
        <!-- <span v-if="item.newNameCN" class="noteSuecss"> 已填写中文名</span> -->
        <!-- <span v-else class="note"> 未填写中文名</span> -->
      </div>
      <div class="sub-btn">
        <el-button :disabled="btnFlage.add" v-if="!btnFlage.sumbit" type="success" size="mini" @click="btnClick(1)"><i
            class="iconfont icon-add"></i>添加</el-button>
        <!-- <el-button
       
          :disabled="btnFlage.edit"
          v-if="!btnFlage.sumbit"
          type="primary"
          size="mini"
          @click="btnClick(2)"
          ><i class="iconfont el-icon-edit"></i>修改</el-button
        > -->
        <el-button @click="handleEdit" type="primary" size="mini">修改</el-button>
        <el-button v-loading="delLoading" :disabled="btnFlage.del" v-if="!btnFlage.sumbit" type="danger" size="mini"
          @click="btnClick(3)"><i class="iconfont icon-delete"></i>删除</el-button>
        <!-- <el-button
       
           type="primary"
          size="mini"
          :disabled="btnFlage.move"
          v-if="!btnFlage.sumbit"
          @click="btnClick(4)"
          ><i class="iconfont el-icon-rank"></i>移动至</el-button
        > -->
        <el-button :loading="btnloading" type="primary" size="mini" @click="btnClick(5)" v-if="btnFlage.sumbit"><i
            class="iconfont icon-baocun"></i>保存</el-button>
        <el-button v-if="btnFlage.cancel" size="mini" @click="btnClick(6)"><i class="iconfont el-icon-close"></i>返回
        </el-button>
      </div>
    </el-form>
    <el-dialog v-dialogDrag width="35%" title="重命名" :close-on-click-modal="false" :before-close="cancel"
      :visible.sync="catalogueDia">
      <el-form size="mini" label-width="120px" class="diaForm" ref="diaForm" :rules="diaRules" :model="diaForm">
        <el-form-item label="原中文名：">
          <el-input disabled size="mini" v-model="diaForm.oriName"></el-input>
        </el-form-item>
        <el-form-item label="新表英文名：" prop="newNameEN">
          <el-input size="mini" clearable v-model="diaForm.newNameEN" :disabled="renameFlage"></el-input>
        </el-form-item>
        <el-form-item label="新表中文名：" prop="newNameCN">
          <el-input size="mini" clearable v-model="diaForm.newNameCN" :disabled="renameFlage"></el-input>
        </el-form-item>
        <el-form-item label="表备注：">
          <el-input :disabled="renameFlage" size="mini" clearable v-model="diaForm.table_note"></el-input>
        </el-form-item>
        <div class="footer">
          <el-button size="mini" type="primary" @click="sumbitDia('diaForm')">确认</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog title="结构" :visible.sync="isStructure" v-dialogDrag width="60%" :close-on-click-modal="false">
      <structure-box ref="structureForm" :structureForm="structureForm" :leftList="leftList" :btnType="btnType"
        :downTypeList="downTypeList" @changeLeftVal="changeLeftVal">
      </structure-box>
    </el-dialog>
  </div>
</template>
<script>
  import structureBox from "../../../../templateSetting/components/third/components/structure.vue";
  import {
    falseObjValue,
    clearObjValue,
    message
  } from "@/utils/common.js";
  import {
    getEntityChild,
    addCate,
    getTableInfo,
    deleteById,
    classTreeUpdate
  } from "@/api/system-management/categoryManagement.js";
  import {
    getFindList,
    getEntity,
    getEntityTable,
    selectAllMetadataChineseName
  } from "@/api/system-management/templateSetting"
  export default {
    props: {
      nowSort: Number,
      treeNodeData: {
        type: Object,
        default: () => {}
      },
      EntityList: {
        type: Array,
        default: () => [],
      },
      downTypeList: {
        type: Array,
        default: () => [],
      },
      btnFlage: {
        type: Object,
        default: () => {},
      },
      formDataFlage: {
        type: Object,
        default: () => {},
      },
      formData: {
        type: Object,
        default: () => {},
      },
    },
    components: {
      structureBox,
    },

    data() {
      return {
        ids: null,
        //删除门类按钮权限
        delLoading: false,

        btnloading: false,
        //重命名权限
        renameFlage: true,
        //结构弹窗
        btnType: false,
        isStructure: false,
        structureForm: {
          columnName: "",
          columnChnName: "",
          columnClass: "",
          columnWidth: null,
          columnPoint: null,
          columnInputType: "",
        },
        leftList: [],
        /****/
        retentionList: [],
        /*table弹窗*/
        diaForm: {
          oriName: "",
          newNameEN: "",
          newNameCN: "",
          table_note: "",
        },
        beforeForm: {}, //缓存表单
        beforeBtn: {}, //缓存按钮权限
        beforeformDataFlage: {}, //表单权限
        catalogueDia: false, //重命名弹窗
        // 表单验证
        rules: {
          className: [{
            required: true,
            message: "请填写类目名称",
            trigger: "blur"
          }, ],
          classOrder: [{
            required: true,
            message: "请填写类目排序",
            trigger: "blur"
          }, ],
          filing: [{
            required: true,
            message: "请选择预归档",
            trigger: "change"
          }, ],
          classType: [{
            required: true,
            message: "请选择类目类型",
            trigger: "change"
          }, ],
        },
        diaRules: {
          newNameEN: [{
            required: true,
            message: "请填写英文名称",
            trigger: "blur"
          }, ],
          newNameCN: [{
            required: true,
            message: "请填写中文名称",
            trigger: "blur"
          }, ],
        },
      };
    },
    methods: {
      getIds(id) {
        this.ids = id;
      },
      // 修改
      handleEdit() {
        let ClassData = this.formData;
        let data = {
          className: ClassData.className,
          classOrder: ClassData.classOrder,
          id: this.ids.id,
        };
        classTreeUpdate(data).then((res) => {
          if (res.code == 100) {
            message("success", res.msg, 2000);
            this.$emit("initGetTree", 2);
          }
        });
      },
      btnClick(num) {
        switch (num) {
          case 1:
            //重命名弹窗权限
            this.renameFlage = false;
            //保存缓存
            this.beforeForm = JSON.stringify(this.formData);
            this.beforeBtn = JSON.stringify(this.btnFlage);
            this.beforeformDataFlage = JSON.stringify(this.formDataFlage);
            falseObjValue(this.btnFlage, true);
            falseObjValue(this.formDataFlage, false);
            this.formDataFlage["ClassProgramme"] = true;
            this.formDataFlage["EntityType"] = true;
            this.formData["classOrder"] = this.nowSort;
            this.formData["filing"] = 1;
            this.formData.classType = "";
            this.formData.className = "";
            break;
          case 2:
            this.beforeForm = JSON.stringify(this.formData);
            this.beforeBtn = JSON.stringify(this.btnFlage);
            falseObjValue(this.btnFlage, true);
            break;
          case 3:
            this.$confirm("请确认要删除的数据，点击确认删除！", "删除提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
              .then(async () => {
                this.delLoading = true
                deleteById({
                  id: this.formData.pId
                }).then(res => {
                  if (res.success) {
                    message("success", res.msg, 2000);
                    this.$emit("initGetTree", 2);
                  } else {
                    this.$message.error(res.msg);
                  }
                }).finally(res => {
                  this.delLoading = false
                })
              })
              .catch(() => {
                return false;
              });

            break;
          case 4:
            break;
          case 5:
            this.$refs["formData"].validate(async (valid) => {
              if (valid) {
                if (
                  this.formData.classType === "C" &&
                  !this.formData.ClassProgramme
                ) {
                  message("warning", "请填写元数据方案", 2000);
                  return;
                }
                if (
                  this.formData.classType === "C" &&
                  !this.formData.EntityType
                ) {
                  message("warning", "请填写实体类型", 2000);
                  return;
                }
                if (
                  this.formData.EntityList.filter((ele) => !ele.newNameCN).length
                ) {
                  message("warning", "请先重命名表格中文名", 3000);
                  return;
                }

                let classTree = {
                  className: this.formData.className, //名字
                  classType: this.formData.classType, //类型
                  classOrder: this.formData.classOrder, //排序
                  metadataType: this.formData.ClassProgramme, //元素方案
                  pId: this.formData.pId, //父级id
                  flage: this.formData.filing, //预归档
                };
                let data = {
                  classTree,
                  parentEntityId: this.formData.EntityType,
                  ttableDescriptions: [],
                };
                this.formData.EntityList.forEach((item) => {
                  let info = {
                    entityId: item.id,
                    note: item.note,
                    tableChnName: item.newNameCN,
                    tableName: item.newNameEN,
                  };
                  data.ttableDescriptions.push(info);
                });
                this.btnloading = true;
                addCate(data).then((res) => {
                  this.btnloading = false;
                  message("success", "保存成功", 2000);
                  this.$emit("initGetTree", 1);
                }).catch(err => {
                  this.btnloading = false;
                })
              } else {
                return false;
              }
            });
            break;
          case 6:
            this.$emit("reduction");
            break;
        }
      },
      //得到下级实体
      ChangeEntity(val) {
        if (!val) {
          return;
        }
        let data = {
          id: val,
        };
        this.ids = val;
        getEntityChild(data).then((res) => {
          this.formData.EntityList = res.body.list;
          this.formData.EntityList.forEach((item) => {
            this.$set(item, "newNameCN", "");
            this.$set(item, "newNameEN", "one_table");
            this.$set(item, "note", "");
          });
        });
      },
      //重命名
      rename(val) {
        let data = {
          entityId: val.id,
          classId: this.formData.pId
        };
        getTableInfo(data).then((res) => {
          if (res.body.ttableDescription) {
            let info = res.body.ttableDescription;
            this.diaForm.oriName = info.tableChnName;
            this.diaForm.newNameEN = info.tableName;
            this.diaForm.note = info.note;
            this.diaForm.newNameCN = info.tableChnName;
          } else {
            this.diaForm.oriName = val.entityName;
            this.diaForm.newNameEN = val.newNameEN;
            this.diaForm.table_note = val.note;
            this.diaForm.newNameCN = val.newNameCN;
          }
          this.catalogueDia = true;
        });
      },
      //弹框表格保存
      sumbitDia(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.formData.EntityList.forEach((item) => {
              if (this.diaForm.oriName === item.entityName) {
                item.newNameEN = this.diaForm.newNameEN;
                item.newNameCN = this.diaForm.newNameCN;
                item.note = this.diaForm.table_note;
              }
            });
            this.catalogueDia = false;
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      //查看结构
      look(item) {
        this.structureForm = {};
        // this.$nextTick(() => {
        //   this.$refs.structureForm.$refs.structureForm.clearValidate();
        // });
        if (this.treeNodeData.classType === "L") {
          this.getInitStructure(item);
        } else if (this.treeNodeData.classType === "C") {
          this.getInitStructureTable(item);
        } else {
          this.leftList = [];
          this.isStructure = true;
        }
      },
      async getInitStructure(item) {
        getEntity({
          entityId: item.id
        }).then(res => {
          if (res.success) {
            this.isStructure = true;
            this.leftList = res.body.tentityStructList;
          } else {
            this.$message.error(res.msg);
          }
        })
      },
      async getInitStructureTable(item) {
        getEntityTable({
          entityId: item.id
        }).then(res => {
          this.isStructure = true;
          this.leftList = res.body.tableStructDescriptionList;
          this.leftList.forEach(item => {
            if (item.columnCanNull === "true") {
              item.columnCanNull = true;
            } else {
              item.columnCanNull = false;
            }
          })
        }).catch(err => {
          this.$message.error(err.msg);
        })
      },
      changeLeftVal(val) {
        this.$refs.structureForm.$refs.structureForm.clearValidate();
        this.structureForm = {
          ...val,
        };
      },
      cancel() {
        this.catalogueDia = false;
      },
      //改变类目类型
      changeClassType(val) {
        if (val === "L") {
          this.formDataFlage["ClassProgramme"] = true;
          this.formDataFlage["EntityType"] = true;
        } else {
          falseObjValue(this.formDataFlage, false);
          this.formData.EntityType = "";
          this.formData.ClassProgramme = "";
        }
      },
    },
    async created() {
      selectAllMetadataChineseName().then(res => {
        if (res.success) {
          this.retentionList = res.body.list;
        }
      })

    },
  };

</script>
<style lang="scss" scoped>
  .rightBox {
    width: 100%;

    .rightTitle {
      letter-spacing: 3px;
      font-size: 17px;
      font-weight: 600;
      height: 37px;
      line-height: 15px;
      text-align: left;
      border-bottom: 1px solid #ccc;
    }

    .rightForm {
      text-align: left;
      padding: 20px;
      width: 80%;

      .note {
        font-size: 12px;
        color: red;
      }

      .noteSuecss {
        font-size: 12px;
        color: #67c23a;
      }
    }

    .diaForm {
      text-align: left;
      padding: 20px;
      // width: 60%;
    }

    .sub-btn {
      text-align: left;
      padding: 20px 80px;
    }

    .cateList {
      padding: 0 0 8px 70px;
    }
  }

  .footer {
    text-align: right;
    height: 36px;
    padding: 18px;
  }

</style>
