<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <ele-split-layout
        width="230px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
      >
        <div>
          <div class="ele-border-lighter sys-organization-list">
            <div
              class="add"
              style="
                display: flex;
                justify-content: flex-end;
                margin-bottom: 10px;
              "
            >
              <el-button type="primary" @click="openEditType('add')"
                >添 加</el-button
              >
            </div>
            <el-tree
              :data="typeTree"
              default-expand-all
              @node-click="handleNodeClick"
              highlight-current
              ref="treeRef"
              node-key="id"
              :expand-on-click-node="false"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <div>
                  <span>{{ data.type == 'templateStyle' ? '模板-' : '' }}</span>
                  {{ node.label }}</div
                >
                <span>
                  <div class="edit-box">
                    <!-- <i
                      v-if="node.type == 'templateStyle'"
                      @click.stop="openEditType('edit', node)"
                      class="el-icon-edit"
                    ></i> -->

                    <el-popconfirm
                      title="确定删除吗？"
                      @confirm="deleteTypeNode(node)"
                    >
                      <i
                        slot="reference"
                        @click.stop
                        class="el-icon-delete"
                        style="color: #f56c6c"
                      ></i>
                    </el-popconfirm>
                  </div>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
        <template v-slot:content>
          <search @search="reload" />
          <ele-pro-table
            ref="table"
            :columns="columns"
            :datasource="datasource"
            :cache-key="cacheKeyUrl"
            row-key="id"
          >
            <template v-slot:toolbar>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                class="ele-btn-icon"
                @click="addPermit(null, 'add', '新增记录规则')"
              >
                新建
              </el-button>
            </template>
            <!-- <template v-slot:status="{ row }"> </template> -->
            <template v-slot:action="{ row }">
              <el-link
                type="primary"
                :underline="false"
                icon="el-icon-document-copy"
                @click="addPermit(row, 'clone', '克隆记录规则')"
              >
                克隆
              </el-link>

              <el-link
                v-if="row.publishStatus === 1 && !row.isUpdatedVersion"
                type="success"
                :underline="false"
                icon="el-icon-finished"
                @click="addPermit(row, 'change', '变更记录规则')"
              >
                变更
              </el-link>

              <!-- <el-popconfirm
            v-if="row.publishStatus == 1"
            class="ele-action"
            title="确定要撤销此条数据吗？"
            @confirm="recordrulesRevokePublish(row)"
          >
            <template v-slot:reference>
              <el-link type="warning" :underline="false" icon="el-icon-delete">
                撤销
              </el-link>
            </template>
          </el-popconfirm> -->

              <el-link
                v-if="row.publishStatus != 1"
                type="primary"
                :underline="false"
                icon="el-icon-edit"
                @click="addPermit(row, 'edit', '修改记录规则')"
              >
                修改
              </el-link>

              <el-popconfirm
                v-if="row.publishStatus != 1"
                class="ele-action"
                title="确定要发布此条数据吗？"
                @confirm="publish(row)"
              >
                <template v-slot:reference>
                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-position"
                  >
                    发布
                  </el-link>
                </template>
              </el-popconfirm>

              <el-link
                v-if="row.publishStatus == 1"
                type="primary"
                :underline="false"
                icon="el-icon-tickets"
                @click="openHistory(row)"
              >
                历史版本
              </el-link>

              <el-popconfirm
                v-if="row.publishStatus != 1"
                class="ele-action"
                title="确定要删除此条数据吗？"
                @confirm="remove(row)"
              >
                <template v-slot:reference>
                  <el-link
                    type="danger"
                    :underline="false"
                    icon="el-icon-delete"
                  >
                    删除
                  </el-link>
                </template>
              </el-popconfirm>
            </template>

            <template v-slot:code="{ row }">
              <el-link
                type="primary"
                :underline="false"
                @click="addPermit(row, 'detail', '记录规则详情')"
                >{{ row.code }}</el-link
              >
            </template>
          </ele-pro-table>
        </template>
      </ele-split-layout>
    </el-card>
    <permitAdd
      ref="permitAddRef"
      @reload="reload"
      :typeInfo="treeNode"
      @reloadTypeList="getTypeList"
    />
    <historyModal ref="historyModalRef" />
    <editTypeModal ref="editTypeModalRef" @reload="getTypeList"></editTypeModal>
  </div>
</template>

<script>
  import search from './components/search.vue';
  import permitAdd from './components/permitAdd.vue';
  import {
    recordrulesPage,
    recordrulesDeletes,
    recordrulesPublish,
    recordrulesRevokePublish,
    recordrulesTypePage,
    recordrulesTypeDeletes,
  } from '@/api/recordrules/index';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import dictMixins from '@/mixins/dictMixins';
  import historyModal from './components/historyModal.vue';
  import editTypeModal from './components/editTypeModal.vue';

  export default {
    components: { search, permitAdd, historyModal, editTypeModal },
    mixins: [tabMixins, dictMixins],
    computed: {
      columns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            label: '记录规则编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'code'
          },
          {
            prop: 'name',
            label: '记录规则名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'industryType',
            label: '行业类别',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.getDictValue('行业类别', row.industryType);
            }
          },
          {
            prop: 'businessType',
            label: '业务分类',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.getDictValue('业务类型', row.businessType);
            }
          },
          {
            prop: 'reportWorkType',
            label: '模块划分',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.getDictValue('记录规则报工类型', row.reportWorkType);
            }
          },
          {
            prop: 'classify',
            label: '应用场景',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.getDictValue('记录规则类型', row.classify);
            }
          },
          {
            prop: 'recordTemplateStyle',
            label: '模板样式',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.getDictValue(
                '记录表模板样式',
                row.recordTemplateStyle
              );
            }
          },
          {
            prop: 'executeMethodName',
            label: '执行方式',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'produceTaskName',
            label: '工序名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'version',
            label: '版本号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return `${row.versionSymbol}${row.bigVersion}${row.versionMark}${row.smallVersion}`;
            }
          },
          {
            prop: 'fromName',
            label: '来源版本',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'startDate',
            label: '启用日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.$util.toDateString(row.startDate, 'yyyy-MM-dd');
            }
          },
          {
            prop: 'stopDate',
            label: '停用日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return this.$util.toDateString(row.stopDate, 'yyyy-MM-dd');
            }
          },
          {
            prop: '',
            label: '周期',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              return (
                row.frequencyValue +
                this.getDictValue('规则周期', row.frequencyUnit)
              );
            }
          },
          {
            prop: 'createUserName',
            label: '创建人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'enable',
            label: '是否启用',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return row.enable ? '启用' : '停用';
            }
          },
          {
            prop: 'publishStatus',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              switch (row.publishStatus) {
                case 0:
                  return '草稿';
                case 1:
                  return '已发布';
                case 2:
                  return '已撤销';
                default:
                  return '';
              }
            }
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 260,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ];
      }
    },
    data() {
      return {
        loading: false,
        cacheKeyUrl: 'maindata-25922-recordrules-index',
        typeTree: [],
        treeNode: null
      };
    },
    created() {
      this.getTypeList();
    },
    methods: {
      addPermit(row, type, title) {
     
        if (type == 'add') {
          if (!this.treeNode) {
            return this.$message.warning('请先选择类型节点！');
          }
          if (this.treeNode.type != 'templateStyle') {
            return this.$message.warning('请先选择左侧模板样式节点！');
          }
        }
        this.$refs.permitAddRef.open(row, type, title);
      },
      async remove(row) {
        try {
          console.log('row', row);
          await recordrulesDeletes([row.id]);
          this.$message.success('删除成功');
          this.reload();
        } catch (error) {
          this.$message.error('删除失败');
        }
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        const typeWhere = {};
        console.log('this.treeNode~~~~~~~~~~~~~~~', this.treeNode);
        if (this.treeNode && this.treeNode.item) {
          if (this.treeNode.type === 'industry') {
            typeWhere.industryType = this.treeNode.item.industryType;
          } else if (this.treeNode.type === 'business') {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
          } else if (this.treeNode.type === 'reportWork') {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
            typeWhere.reportWorkType = this.treeNode.item.reportWorkType;
          } else if (this.treeNode.type === 'scene') {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
            typeWhere.reportWorkType = this.treeNode.item.reportWorkType;
            typeWhere.classify = this.treeNode.item.sceneType;
          } else {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
            typeWhere.reportWorkType = this.treeNode.item.reportWorkType;
            typeWhere.classify = this.treeNode.item.sceneType;
            typeWhere.recordTemplateStyle =
              this.treeNode.item.templateStyleType;
          }
        }

        return recordrulesPage({
          pageNum: page,
          size: limit,
          ...where,
          ...typeWhere
        });
      },
      /* 刷新表格 */
      reload(where) {
        const typeWhere = {};
        if (this.treeNode && this.treeNode.item) {
          if (this.treeNode.type === 'industry') {
            typeWhere.industryType = this.treeNode.item.industryType;
          } else if (this.treeNode.type === 'business') {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
          } else if (this.treeNode.type === 'reportWork') {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
            typeWhere.reportWorkType = this.treeNode.item.reportWorkType;
          } else if (this.treeNode.type === 'scene') {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
            typeWhere.reportWorkType = this.treeNode.item.reportWorkType;
            typeWhere.classify = this.treeNode.item.sceneType;
          } else {
            typeWhere.industryType = this.treeNode.item.industryType;
            typeWhere.businessType = this.treeNode.item.businessType;
            typeWhere.reportWorkType = this.treeNode.item.reportWorkType;
            typeWhere.classify = this.treeNode.item.sceneType;
            typeWhere.recordTemplateStyle =
              this.treeNode.item.templateStyleType;
          }
        }
        this.$refs.table.reload({ page: 1, where, ...typeWhere });
      },
      // 发布
      async publish(row) {
        // 判断时间
        const startDate = new Date(row.startDate);
        const stopDate = new Date(row.stopDate);

        if (startDate >= stopDate) {
          return this.$message.warning('请先修改规则停用时间！');
        }

        try {
          await recordrulesPublish(row.id);
          this.$message.success('发布成功');
          this.reload();
        } catch (error) {
          this.$message.error('发布失败');
        }
      },
      // 撤销
      async recordrulesRevokePublish(row) {
        try {
          await recordrulesRevokePublish(row.id);
          this.$message.success('撤销成功');
          this.reload();
        } catch (error) {
          this.$message.error('撤销失败');
        }
      },
      // 历史版本
      openHistory(row) {
        this.$refs.historyModalRef.open(row.id);
      },
      // 类型列表
      async getTypeList() {
        const { list = [] } = await recordrulesTypePage({
          pageNum: 1,
          size: 99999
        });

        console.log('type list', list);

        const industryMap = new Map();

        list.forEach((item) => {
          // industry
          let industryNode = industryMap.get(item.industryType);
          if (!industryNode) {
            industryNode = {
              id: 'industry-' + item.industryType,
              type: 'industry',
              value: item.industryType,
              label: item.industryName,
              children: [],
              item,
              _businessMap: new Map()
            };
            industryMap.set(item.industryType, industryNode);
          }

          // business
          let businessNode = industryNode._businessMap.get(item.businessType);
          if (!businessNode) {
            businessNode = {
              id: `business-${item.industryType}-${item.businessType}`,
              type: 'business',
              value: item.businessType,
              label: item.businessName,
              children: [],
              item,
              _reportMap: new Map()
            };
            industryNode._businessMap.set(item.businessType, businessNode);
            industryNode.children.push(businessNode);
          }

          // reportWork
          let reportNode = businessNode._reportMap.get(item.reportWorkType);
          if (!reportNode) {
            reportNode = {
              id: `report-${item.industryType}-${item.businessType}-${item.reportWorkType}`,
              type: 'reportWork',
              value: item.reportWorkType,
              label: item.reportWorkName,
              children: [],
              item,
              _sceneMap: new Map()
            };
            businessNode._reportMap.set(item.reportWorkType, reportNode);
            businessNode.children.push(reportNode);
          }

          // scene
          let sceneNode = reportNode._sceneMap.get(item.sceneType);
          if (!sceneNode) {
            sceneNode = {
              id: `scene-${item.industryType}-${item.businessType}-${item.reportWorkType}-${item.sceneType}`,
              type: 'scene',
              value: item.sceneType,
              label: item.sceneName,
              children: [],
              item,
              _templateMap: new Map()
            };
            reportNode._sceneMap.set(item.sceneType, sceneNode);
            reportNode.children.push(sceneNode);
          }

          // template style
          let templateNode = sceneNode._templateMap.get(item.templateStyleType);
          if (!templateNode) {
            templateNode = {
              id: `template-${item.industryType}-${item.businessType}-${item.reportWorkType}-${item.sceneType}-${item.templateStyleType}`,
              type: 'templateStyle',
              value: item.templateStyleType,
              label: item.templateStyleName,
              item,
              children: []
            };
            sceneNode._templateMap.set(item.templateStyleType, templateNode);
            sceneNode.children.push(templateNode);
          }

          // 原始数据
          templateNode.item = item;
        });

        const clean = (node) => {
          delete node._businessMap;
          delete node._reportMap;
          delete node._sceneMap;
          delete node._templateMap;
          node.children && node.children.forEach(clean);
        };

        const tree = Array.from(industryMap.values());
        tree.forEach(clean);

        this.typeTree = tree; // 结果树
        
        if (!this.treeNode) {
          // 默认选中第一个节点
          this.treeNode = this.typeTree.length > 0 ? this.typeTree[0] : null;
          // console.log('this.treeNode`1111111111111111111111`', this.treeNode);
          if (this.treeNode) {
            // 默认选中节点
            this.$nextTick(() => {
              this.$refs.treeRef.setCurrentKey(this.treeNode.id);
              this.reload();
            });
          }
        }

        console.log('typeTree', this.typeTree);
      },
      // 打开新增类型
      openEditType(type = 'add', data = null) {
        this.$refs.editTypeModalRef.open(type, type == 'add' ? this.treeNode : data);
      },
      async deleteTypeNode(node) {
        console.log('delete node', node);
        // 删除类型节点
        await recordrulesTypeDeletes([node.data.item.id]);
        this.$message.success('删除成功');
        this.getTypeList();
      },
      handleNodeClick(data) {
        console.log('data', data);
        this.treeNode = data;
        this.reload();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .sys-organization-list {
    height: calc(100vh - 264px);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    overflow: auto;
    padding: 10px 5px;
  }

  .sys-organization-list :deep(.el-tree-node__content) {
    height: 30px;

    & > .el-tree-node__expand-icon {
      // margin-left: 10px;
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    .edit-box {
      display: none;
      gap: 2px;
      cursor: pointer;
    }

    &:hover .edit-box {
      display: flex;
    }
  }
</style>
