<template>
  <app-drawer v-model="visible" :loading="loading" :title="title" @cancel="onCancel" @confirm="onConfirm" append-to-body class="tree-drawer" hideFooter>
    <div class="dict-body">
      <app-sync-tree
        ref="appAsyncTree"
        :hideTopbar="true"
        highlightFirst
        :actions="treeActions"
        :default-data="defaultData"
        :default-expanded-keys="defaultExpandedKeys"
        :expand-all="expandAll"
        :props="treeProps"
        :request-method="getTreeNodes"
        title="多维字典目录"
        formWidth="100%"
        :formRules="formRules"
        dialogWidth="50%"
        @select="onTreeNodeClick"
      >
        <template #form="{ form: treeForm }">
          <template v-if="!treeForm.id">
            <!-- <el-row :gutter="20" style="width: 96%; margin: 0 2%">
              <app-filter-item :span="10" label="父级字典值">
                <el-input v-model="curNode.name" placeholder="父级字典值" disabled />
              </app-filter-item>
            </el-row> -->
            <el-row :gutter="20" style="width: 96%; margin: 0 2%">
              <app-filter-item :span="20" label="解析Excle">
                <el-input type="textarea" v-model="treeForm.text" placeholder="请输入需要解析的Excle解析文本" />
              </app-filter-item>
              <app-filter-item :span="4" label="">
                <el-button @click="analysisText(treeForm)" type="primary" icon="el-icon-magic-stick">解析</el-button>
                <el-tooltip class="item" content="请复制excel数据到文本框中解析为字典值列表！" placement="bottom">
                  <i class="el-icon-info ml-10 fs-20" style="color: #e6a23c"></i>
                </el-tooltip>
              </app-filter-item>
            </el-row>
            <el-row :gutter="20" style="width: 96%; margin: 0 2%">
              <el-table ref="nodeTable" :data="treeForm.nodeData" border height="40vh" style="width: 100%">
                <el-table-column align="center" label="序号" width="50" type="index" />
                <el-table-column align="center" label="名称" min-width="160" resizable>
                  <template slot="header">
                    <span>
                      <span class="fs-14" style="color: #f56c6c">*</span>
                      名称
                    </span>
                  </template>
                  <template slot-scope="scope">
                    <app-filter-item :prop="`nodeData.${scope.$index}.name`" :rules="formRules.name" :span="24">
                      <el-input v-model="scope.row.name" placeholder="请输入字典值名称" />
                    </app-filter-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" min-width="160" resizable>
                  <template slot="header">
                    <span>
                      <span class="fs-14" style="color: #f56c6c">*</span>
                      编码
                      <el-tooltip class="item" content="编码不能重复" placement="bottom">
                        <i class="el-icon-info fs-14" style="color: #e6a23c"></i>
                      </el-tooltip>
                    </span>
                  </template>
                  <template slot-scope="scope">
                    <app-filter-item :prop="`nodeData.${scope.$index}.key`" :rules="formRules.key" :span="24">
                      <el-input v-model="scope.row.key" placeholder="请输入字典值编码" />
                    </app-filter-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="排序号" width="120" resizable>
                  <template v-slot="{ row }">
                    <app-filter-item :span="24">
                      <el-input type="number" v-model="row.sn" placeholder="请输入字典值序号" />
                    </app-filter-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="120" resizable>
                  <template v-slot="{ row, $index }">
                    <el-button circle type="primary" icon="el-icon-plus" @click="addSubNode"></el-button>
                    <el-button circle type="danger" icon="el-icon-delete" @click="deleteSubNode($index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </template>
          <template v-else>
            <el-row :gutter="20" style="width: 90%; margin: 0 5%">
              <!-- <app-filter-item :span="12" label="父级字典值">
                <el-input v-model="curNode.name" placeholder="父级字典值" disabled />
              </app-filter-item> -->
              <app-filter-item :span="18" label="字典值编码">
                <el-input v-model="treeForm.key" placeholder="字典值编码" disabled />
              </app-filter-item>
            </el-row>
            <el-row :gutter="20" style="width: 90%; margin: 0 5%">
              <app-filter-item :rules="[{ required: true, message: '字典值名称不能为空' }]" :span="18" label="字典值名称">
                <el-input v-model="treeForm.name" placeholder="请输入字典值名称" />
              </app-filter-item>
              <app-filter-item :rules="[{ required: true, message: '字典值序号不能为空' }]" :span="18" label="字典值序号">
                <el-input type="number" v-model="treeForm.sn" placeholder="请输入字典值序号" />
              </app-filter-item>
            </el-row>
          </template>
        </template>
      </app-sync-tree>
    </div>
  </app-drawer>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js';
import API from '@/api/business/dict.js';
export default {
  name: 'SubTreeDrawer',
  mixins: [dialogMixin],
  data() {
    var checkey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('字典值编码不能为空'));
      } else {
        if (this.defaultData.nodeData.filter((item) => item.key === value).length > 1) {
          callback(new Error('字典值编码不能重复!'));
        } else {
          callback();
        }
      }
    };
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
        label: 'name',
      },
      expandAll: false,
      defaultExpandedKeys: [''],
      curNode: {}, // 当前选择字典值
      formRules: {
        name: [
          {
            required: true,
            message: '字典值名称不能为空',
            trigger: 'blur',
          },
        ],
        key: [
          {
            required: true,
            message: '字典值编码不能为空',
            trigger: 'blur',
          },
          { validator: checkey, trigger: 'blur' },
        ],
      },
      defaultData: {
        text: '',
        nodeData: [
          {
            name: '',
            key: '',
            sn: 1,
          },
        ],
      },
    };
    return {
      treeData: [],
      parentRow: {},
      ...TREE_CONFIG,
      curNode: {},
      rootNode: {},
    };
  },
  watch: {},
  created() {},
  methods: {
    initData(data) {
      this.parentRow = { ...data };
      this.defaultData = {
        text: '',
        nodeData: [
          {
            name: '',
            key: '',
            sn: 1,
          },
        ],
      };
      this.reloadTree();
    },
    async getTreeNodes() {
      if (!this.parentRow.id) {
        return [];
      } else {
        const value = await API.queryDictTree(this.parentRow);
        let firstId = value.length > 0 ? value[0].id : '';
        this.rootNode = value.length > 0 ? value[0] : {};
        this.defaultExpandedKeys = [firstId];
        return { data: value || [] };
      }
    },
    reloadTree() {
      this?.$refs?.appAsyncTree?.getTreeData();
    },

    /**
     * @description: treeActions支持函数也支持数组，由于实际场景当中 可能会动态设置按钮，故以函数示例来展示
     * @param {*} data 当前点击节点数据
     * @return {*} 当前节点展示的操作项数组
     */
    treeActions(data) {
      // 根节点判断方式以业务为准，此处仅为示例
      return [
        {
          label: '添加',
          type: 'add',
          icon: 'el-icon-plus',
          method: this.addNode,
        },
        {
          label: '编辑',
          type: 'edit',
          icon: 'el-icon-edit',
          method: this.editNode,
          showHide: (row) => {
            return row.id !== this.rootNode.id;
          },
        },
        {
          label: '删除',
          type: 'delete',
          icon: 'el-icon-delete',
          tips: '及其子节点',
          method: this.delNode,
          showHide: (row) => {
            return row.id !== this.rootNode.id;
          },
        },
      ];
    },

    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return;
      this.curNode = { ...node };
    },
    async addNode(params, node) {
      console.log(params, node);
      const { id = '', typeId = '' } = node;
      let newNodes = params.nodeData || [];
      newNodes = newNodes.map((item) => {
        item.typeId = typeId;
        item.parentId = id;
        item.type = 'val';
        item.dicId = this.parentRow?.id || '';
        return item;
      });
      try {
        const { state, message } = await API.saveMultiDictItemBatch(newNodes);
        if (state) {
          this.reloadTree();
          this.$message.warning('添加字典值成功！');
        }
      } catch (err) {
        this.$message.warning(err || '添加字典值失败！');
      }
    },
    async editNode(params) {
      try {
        const { state, message } = await API.saveMultiDictItem(params);
        if (state) {
          this.reloadTree();
          this.$message.warning('编辑字典值成功！');
        }
      } catch (err) {
        this.$message.warning(err || '编辑字典值失败！');
      }
    },
    async delNode(params, node) {
      try {
        const { state, message } = await API.removeDictNode(params[0]);
        if (state) {
          this.reloadTree();
          this.$message.warning('删除字典值成功！');
        }
      } catch (err) {
        this.$message.warning(err || '删除字典值失败！');
      }
    },

    onConfirm() {
      this.$emit('confirm');
    },
    onCancel() {
      this.visible = false;
      this.$emit('cancel');
    },
    analysisText(val) {
      console.log(val, val.text);
      if (!val.text) {
        this.$message.warning('暂无可解析的数据，请将数据复制到文本框中，再重试！');
      } else {
        this.analysis(val.text);
      }
    },
    analysis(data) {
      let str = data.toString();
      let tempArr = str.split('\n');
      let addData = tempArr.map((item) => {
        let line = item.split('\t');
        return {
          name: line[0],
          key: line[1],
          sn: line[2],
        };
      });

      addData = addData.filter((item) => {
        if (item.name || item.key || item.sn) {
          return true;
        } else {
          return false;
        }
      });
      this.defaultData.nodeData.splice(0, addData.length, ...addData);
      console.log(addData, 'tempArr');
    },
    addSubNode() {
      this.defaultData.nodeData.push({
        name: '',
        key: '',
        sn: this.defaultData.nodeData.length + 1,
      });
    },
    deleteSubNode(index) {
      if (this.defaultData.nodeData.length > 1) {
        this.defaultData.nodeData.splice(index, 1);
      } else {
        this.$message.warning('请至少提交一条子字典值数据！');
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.dict-body {
  ::v-deep {
    .app-tree {
      width: 100%;
    }
  }
}
::v-deep {
  .el-table td.el-table__cell {
    padding: 0;
  }

  .el-form-item {
    margin: 18px 0;
  }
}
</style>
