<template>
  <div class="box">
    <el-card class="tree-box" shadow="always" :body-style="{ padding: '5px' }" ref='cardTree'>
      <div slot="header" class="clearfix">
        <div>
          <span v-show="!status" style="margin-left:4px">实体树</span>
          <el-button style="float: right; padding:  0" type="text" @click='btns'>
            <el-tooltip class="item" effect="dark" v-if="!status" content="折叠" placement="right">
              <svg-icon icon-class="leftzd" v-if="!status" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" v-if="status" content="展开" placement="left">
              <svg-icon icon-class="rightzd" v-if="status" />
            </el-tooltip>
          </el-button>
        </div>
        <div style="padding:5px 0">
          <el-button @click="copyEntity" style="padding: 5px 10px" size="mini" type="success" v-show="!status">
            复制实体
          </el-button>
          <el-button style="padding: 5px 10px" type="danger" size="mini" v-show="!status" :disabled="
            dictionariesFormVal.hasOwnProperty('classType')|| JSON.stringify(dictionariesFormVal) ==='{}' 
          " @click="deleteClick"><i class="iconfont icon-delete"></i>删除实体</el-button>
        </div>
      </div>
      <div class="tree">
          <el-scrollbar wrap-style="overflow-x:hidden;" style="height: calc(100vh - 250px)">
            <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-scrollbar>
      </div>
    </el-card>
    <div class="resize" title="收缩侧边栏">
      ⋮
    </div>
    <el-card class="form-box" ref='cardForm'>
      <div slot="header" class="clearfix">
        <span>实体模板设置</span>
      </div>
      <el-form ref="entityForm" size="small" :model="entityForm" :rules="rules" label-width="120px">
        <el-form-item label="档案模版：" prop="entityName">
          <el-input v-model="entityForm.entityName" :disabled="!isActive"></el-input>
        </el-form-item>
        <el-form-item label="下属编目表：">
          <el-button size="mini" v-if="isActive" @click="addRow" type="success">添加</el-button>
          <el-button size="mini" v-if="isActive" @click="deleteRow" type="danger">删除</el-button>
        </el-form-item>
        <template v-if="isActive || dictionariesFormVal.classType !== 'I'">
          <el-form-item class="jiegou" :label="item.label" v-for="(item, index) in entityForm.list" :key="index"
            :prop="'list.' + index + '.entityName'" :rules="{
            required: true,
            message: item.label + '档案模版不能为空',
            trigger: 'blur',
          }">
            <el-input v-model="entityForm.list[index].entityName" placeholder="请输入层档案模版" :disabled="!isActive">
            </el-input>
            <el-button type="primary" size="mini" @click="openStructureClick(item, index)">结构</el-button>
          </el-form-item>
        </template>
        <el-form-item v-if="!isActive">
          <el-button type="success" size="mini" v-if="dictionariesFormVal.hasOwnProperty('classType')"
            @click="addClick(1)"><i class="iconfont icon-add"></i>添加</el-button>
          <!--<el-button type="primary" size="mini" :disabled=" JSON.stringify(dictionariesFormVal)==='{}'"
            @click=" addClick(2)"><i class="iconfont icon-update"></i>修改</el-button>
          -->
          <el-button type="primary" size="mini"
            v-if="!(dictionariesFormVal.hasOwnProperty('classType')|| JSON.stringify(dictionariesFormVal) ==='{}' )"
            @click=" addClick(2)"><i class="iconfont icon-update"></i>修改</el-button>
        </el-form-item>
        <el-form-item v-if="isActive">
          <el-button :loading="btnloading" type="primary" size="mini" @click="subAddClick"><i
              class="iconfont icon-baocun"></i>保存</el-button>
          <el-button type="info" size="mini" @click="offClick"><i class="iconfont icon-error"></i>取消</el-button>
        </el-form-item>

      </el-form>
    </el-card>
    <el-dialog v-dialogDrag ref="diaFrom" title="结构" :close-on-click-modal="false" :visible.sync="isStructure"
      width="60%" top="10px" :before-close="cancel">
      <structure-box ref="structureForm" :structureForm="structureForm" :structureType="structureType"
        :leftList="leftList" :downTypeList="downTypeList" @offStructureClick="offStructureClick"
        @resetStructureClick="resetStructureClick" @changeLeftVal="changeLeftVal">
      </structure-box>
    </el-dialog>
    <el-dialog v-dialogDrag ref="copyEntity" title="复制实体" :close-on-click-modal="false" :visible.sync="entityStatus"
      width="50%" top="10px" :before-close="cancelEntity">
      <div style="padding:20px">
        <el-form ref="entityCopyForm" size="small" :model="entityCopyForm" :rules="rules" label-width="120px">
          <el-form-item label="档案模版：" prop="entityName">
            <el-input v-model="entityCopyForm.entityName"></el-input>
          </el-form-item>
          <el-form-item label="下属编目表：">
          </el-form-item>
          <template>
            <el-form-item class="jiegou" :label="item.label" v-for="(item, index) in entityCopyForm.list" :key="index"
              :prop="'list.' + index + '.entityName'" :rules="{
            required: true,
            message: item.label + '档案模版不能为空',
            trigger: 'blur',
          }">
              <el-input v-model="entityCopyForm.list[index].entityName" placeholder="请输入层档案模版">
              </el-input>
            </el-form-item>
          </template>
          <el-form-item label=" ">
            <el-button :loading="btnloading" type="primary" size="mini" @click="saveEntity('entityCopyForm')"><i
                class="iconfont icon-baocun"></i>保存</el-button>
            <el-button  type="primary" size="mini" @click="cancelEntity"><i class="iconfont icon-baocun"></i>取消
            </el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>
  </div>
</template>
<script>
  import {
    mapState
  } from "vuex";
  import {
    saveTentityType
  } from "@/api/system-management/templateSetting"
  import structureBox from "./components/structure";
  import {
    message,
    dragControllerDiv
  } from '@/utils/common';
  export default {
    props: {
      clickObj: {
        type: Object,
        default: () => {},
      },
      treeData: {
        type: Array,
        default: () => [],
      },
      downTypeList: {
        type: Array,
        default: () => [],
      },
      defaultProps: {
        type: Object,
        default: () => {},
      },
      title: {
        type: String,
        default: () => "",
      },
      treeLoading: {
        type: Boolean,
        default: () => {},
      },
      dictionariesFormVal: {
        type: Object,
        default: () => {},
      },
    },
    components: {
      structureBox
    },
    data() {
      return {
        entityCopyForm: {},
        entityStatus: false,
        btnloading: false,
        treeId: "",
        structureForm: {
          columnName: "",
          columnChnName: "",
          columnClass: "",
          columnWidth: undefined,
          columnPoint: undefined,
          columnInputType: "",
          note: "",
          columnCanNull: false,
        },
        firstList: [],
        isStructure: false, //结构弹窗
        //结构状态(新增/修改)
        structureType: false,
        status: false,
        isActive: false,
        entityForm: {},
        rules: {
          entityName: [{
            required: true,
            message: "请输入档案模版名",
            trigger: "blur"
          }, ],
        },
      }
    },
    watch: {
      dictionariesFormVal(newVal, oldVal) {
        this.isActive = false;

        if (newVal.hasOwnProperty("childTentityType")) {

          if (this.dictionariesFormVal.childTentityType) {
            let arr = this.dictionariesFormVal.childTentityType.splice(0, 1);
            this.dictionariesFormVal.childTentityType.map((item, index) => {
              if (index === 0) {
                item.label = "第1层";
              } else if (index === 1) {
                item.label = "第2层";
              } else if (index === 2) {
                item.label = "第3层";
              }
            });
            this.entityForm = {
              classId: arr[0].classId,
              entityName: arr[0].entityName,
              list: this.dictionariesFormVal.childTentityType,
              id: newVal.id,
            };
          }
        } else {
          this.entityForm = {
            classId: newVal.id,
            entityName: newVal.className,
            list: [{
              label: "第1层",
              entityName: "",
              classId: newVal.id,
            }],
          };
        }
      },
      'status': {
        handler(val, oldVal) {
          const cardTree = this.$refs.cardTree.$el.style
          const cardForm = this.$refs.cardForm.$el.style
          if (val) {
            cardTree.width = '5%'
            cardForm.width = '94%'
          } else {
            cardTree.width = '22%';
            cardForm.width = '77%';
          }
        }
      }
    },
    computed: {
      ...mapState({
        // thirdTree: (state) => state.templateSetting.thirdTree,
        // downTypeList: (state) => state.templateSetting.downTypeList,
      }),
      leftList: {
        get() {
          return this.$store.state.templateSetting.leftList;
        },
        set(val) {
          this.$store.state.templateSetting.leftList = val;
        },
      },
    },
    methods: {
      copyEntity() {
        if (JSON.stringify(this.clickObj) === "{}") {
          message("warning", "请选择需要复制的实体", 3000)
          return
        }
        if (this.clickObj["pId"] === -1) {
          message("warning", "请勿选择文件夹", 3000)
          return
        }
        this.entityCopyForm = JSON.parse(JSON.stringify(this.entityForm))
        this.entityCopyForm.entityName = this.entityCopyForm.entityName + "--(COPY)"
        this.entityStatus = true
      },
      openStructureClick(item, index) {
        if (!item.label) {
          message('warning', '请输入对应得表名', 3000)
          return
        }
        this.JGLabel = item.label
        this.leftList = [];
        Object.keys(this.structureForm).forEach((key) => {
          if (key === "columnCanNull") {
            this.structureForm[key] = false;
          } else if (key === "columnWidth" || key === "columnPoint") {
            this.structureForm[key] = undefined;
          } else {
            this.structureForm[key] = "";
          }
        });
        if (item.id) {
          this.leftList = this.entityForm.list[index].childTentityTypeStructDescription ? this.entityForm.list[
            index].childTentityTypeStructDescription : this.getInitStructure(item)
        } else {
          this.leftList =
            this.entityForm.list[index].childTentityTypeStructDescription || [];
        }
        this.structureType = false;
        this.activeIndex = index;
        this.isStructure = true;
      },
      // 点击树节点
      handleNodeClick(data, node) {
        // if (!this.treeId) {
        //   this.treeId = data.id

        // } else {
        //   if (this.treeId != data.id) {
        //     this.firstList = []
        //   }
        // }
        this.$emit("handleNodeClick", data, node);
      },
      btns() {
        this.status = !this.status
      },
      deleteClick() {
        this.$alert("是否确认删除该数据？", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: async (action) => {
            if (action === "cancel") {
              return false;
            }
            this.$store.dispatch('templateSetting/deleteTentityType', {
              id: this.entityForm.id
            }).then(res => {
              this.$message.success("删除成功");
              this.$emit("handleClick", {
                name: "third"
              });
            })
          },
        });
      },
      addClick(index) {
        if (index === 1) {
          this.entityForm = {
            isAddOrUpdate: 1,
            classId: this.entityForm.classId,
            list: [{
              label: "第1层",
              entityName: "",
              classId: this.entityForm.classId,
            }],
          };
        }
        this.isActive = true;
      },
      addRow() {
        if (this.entityForm.list.length === 1) {
          this.entityForm.list.push({
            classId: this.entityForm.classId,
            label: "第2层",
            entityName: ""
          });
        } else if (this.entityForm.list.length === 2) {
          this.entityForm.list.push({
            classId: this.entityForm.classId,
            label: "第3层",
            entityName: ""
          });
        } else {
          this.$alert("实体最多为三层", "提示", {
            confirmButtonText: "确定",
            type: "warning",
            callback: async (action) => {
              return false;
            },
          });
        }
      },
      deleteRow() {
        if (this.entityForm.list.length === 1) {
          this.$alert("实体最少为一层", "提示", {
            confirmButtonText: "确定",
            type: "warning",
            callback: async (action) => {
              return false;
            },
          });
          return false;
        } else {
          this.entityForm.list.pop();
        }
      },
      subAddClick() {
        // return
        this.$refs.entityForm.validate(async (valid) => {
          if (valid) {
            this.btnloading = true;
            if (this.entityForm.isAddOrUpdate === 1) {
              let data = {
                childTentityType: [{
                  entityName: this.entityForm.entityName,
                  classId: this.entityForm.classId,
                }, ],
              };
              this.entityForm.list.map((item, index) => {
                data.childTentityType.push({
                  classId: item.classId,
                  entityLevel: index + 1,
                  entityName: item.entityName,
                  childTentityStructDescription: item.childTentityTypeStructDescription,
                });
              });
              saveTentityType(data).then(res => {
                this.btnloading = false;
                this.isActive = false;
                this.$message.success(
                  this.entityForm.isAddOrUpdate === 1 ? "保存成功" : "修改成功"
                );
                this.$emit("handleClick", {
                  name: "third"
                });
              }).catch(err => {
                this.btnloading = false;
              })
            } else {
              let data = {
                childTentityType: [{
                  entityName: this.entityForm.entityName,
                  classId: this.entityForm.classId,
                  id: this.entityForm.id,
                }, ],
              };
              this.entityForm.list.map((item, index) => {
                data.childTentityType.push({
                  classId: item.classId,
                  entityLevel: index + 1,
                  entityName: item.entityName,
                  childTentityStructDescription: item.childTentityTypeStructDescription ? item
                    .childTentityTypeStructDescription : item.childTentityStructDescription,
                  id: item.id,
                });
              });
              this.$store.dispatch("templateSetting/updateTentityType", data).then(res => {
                this.btnloading = false;
                this.isActive = false;
                this.$message.success(
                  this.entityForm.isAddOrUpdate === 1 ? "保存成功" : "修改成功"
                );
                this.$emit("handleClick", {
                  name: "third"
                });
              }).catch(err => {
                this.btnloading = false;
              })

            }
          } else {
            return false;
          }
        });
      },
      offClick() {
        this.$emit("handleNodeClick", this.clickObj);
      },
      changeLeftVal(val) {
        this.structureType = true;
        this.$refs.structureForm.$refs.structureForm.clearValidate();
        this.structureForm = {
          ...val,
        };
      },
      resetStructureClick() {
        this.structureType = false;

        for (let key in this.structureForm) {
          if (key === "columnWidth" || key === "columnPoint") {
            this.structureForm[key] = undefined;
          } else if (key === "columnCanNull") {
            this.structureForm[key] = false;
          } else {
            this.structureForm[key] = "";
          }
        }
        this.$refs.structureForm.OptionType = false;
        this.$refs.structureForm.OptionValue = "";
      },
      offStructureClick(list) {
        this.entityForm.list[
          this.activeIndex
        ].childTentityTypeStructDescription = [...list];
        this.activeIndex = null;
        this.isStructure = false;
      },
      getInitStructure(item) {
        // if (JSON.stringify(this.firstList) === '[]') {
        this.$store.dispatch('templateSetting/getTentityStructByEntityId', {
          entityId: item.id
        }).then(res => {
          //临时储存
          // this.firstList = this.leftList
        })
        // }

      },
      cancel() {
        this.$refs.structureForm.offStructureClick();
        this.$refs.structureForm.OptionType = false;
      },
      cancelEntity() {
        this.entityStatus = false
      },
      saveEntity(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnloading = true;
            let data = {
              childTentityType: [{
                id: this.entityCopyForm.id,
                entityName: this.entityCopyForm.entityName,
              }, ],
            };
            this.entityCopyForm.list.map((item, index) => {
              data.childTentityType.push({
                id: item.id,
                entityName: item.entityName,
              });
            });
            this.$store.dispatch("templateSetting/copyEntity", data).then(res => {
              this.btnloading = false
              this.$store.dispatch("templateSetting/getEntityTree").then(res => {})
              this.cancelEntity()
            }).catch(err => {
              this.btnloading = false;
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    },
    mounted() {
      dragControllerDiv()
    },
  }

</script>
<style lang='scss' scoped>
  .box {
    display: flex;
    justify-content: space-around;
    height: 100%;

    .tree-box {
      width: 22%;
      // height: 770px;
      // overflow-y: auto;

      .el-tree {
        width: 100%;
        margin-top: 10px;
      }

      .clearfix {
        font-weight: 600;
        font-size: 17px;
        letter-spacing: 3px;
      }
    }

    .form-box {
      width: 77%;

      .clearfix {
        font-weight: 600;
        font-size: 17px;
        letter-spacing: 3px;
      }

      .el-form {
        width: 100%;
        padding: 5px 0;

        .el-form-item {
          width: 80%;

          &:last-of-type {
            text-align: left;
          }

          &:nth-of-type(2) {
            ::v-deep .el-form-item__content {
              text-align: left;
            }
          }

          &.jiegou {
            ::v-deep .el-form-item__content {
              display: flex;

              .el-button {
                margin-left: 5px;
              }
            }
          }
        }
      }
    }
  }

</style>
