<template>
  <div :class="[$style.wrapHeight, $style.dataclass]">
    <div :class="$style.rowHeight">
      <MasterDataTree ref="masterTree" @treeSelect="treeSelect"></MasterDataTree>
      <div :class="$style.rightcard">
        <div v-if="groupId !== ''" :class="$style.row">
          <div>
            <a-button type="primary" @click="createMatters">
              新建
            </a-button>
            <a-button
              :disabled="!nodeInfo.id || nodeInfo.id === '-1'"
              :class="$style.rowRight"
              @click="deleteRows"
            >
              删除
            </a-button>
          </div>
        </div>
        <a-descriptions
          v-if="groupId !== '-1' && groupId !== ''"
          bordered
          :title="className"
          :column="2"
        >
          <a-descriptions-item v-for="(item, index) in orgList" :key="index" :label="item.org_name">
            <div :class="$style.labelItem">
              <div v-if="item.checkList.length > 0" style="display: inline-block;">
                <a-tag
                  v-for="(sysItem, sysIndex) in item.checkList"
                  :key="sysIndex"
                  color="#108ee9"
                  :closable="sysItem.isShow"
                  @close="closeTag(sysItem.id)"
                >
                  {{ sysItem.org_name }}
                </a-tag></div
              >
              <a-button
                :class="$style.button"
                size="small"
                icon="plus"
                @click="systemTree(item.org_code, item.org_name)"
              ></a-button>
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </div>
    <a-modal v-model="visible" :title="type === 'add' ? '新增' : '编辑'" width="800px" @ok="save">
      <a-form-model
        ref="ruleForm"
        :model="detailInfo"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 15 }"
      >
        <a-form-model-item label="代码" prop="code">
          <a-input v-model="detailInfo.code"></a-input>
        </a-form-model-item>
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="detailInfo.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="排序号">
          <a-input v-model="detailInfo.weight"></a-input>
        </a-form-model-item>
        <a-form-model-item label="级别">
          <a-input value="公司" disabled></a-input>
        </a-form-model-item>
        <a-form-model-item label="所属分类">
          <a-input v-model="className" disabled></a-input>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea v-model="detailInfo.description" :rows="2"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!--加载状态 -->
    <a-modal v-model="orgShow" :title="sysName" @ok="saveSys">
      <div v-if="confirmLoading" :class="$style.loading">
        <sd-loading></sd-loading>
      </div>
      <div v-else-if="systemData.length > 0">
        <a-tree
          checkable
          check-strictly
          :tree-data="systemData"
          :replace-fields="{
            children: 'children',
            title: 'org_name',
          }"
          @check="onCheck"
        />
      </div>

      <a-empty v-else />
    </a-modal>
  </div>
</template>

<script>
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import MasterDataTree from './master-data-tree.vue'
import TableActionTypes from '@/common/services/table-action-types'
import { message, Modal, Descriptions } from 'ant-design-vue'
import MasterDataService from './master-data-service'
import Vue from 'vue'
import { getUserInfo } from '@/common/store-mixin'
import sdLoading from '@/common/pages/sd-loading.vue'
Vue.use(Descriptions)

export default {
  name: 'MasterDataList',
  metaInfo: {
    title: '组织管理',
  },
  components: {
    MasterDataTree,
    sdLoading,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      confirmLoading: false,
      orgList: [
        { org_name: '法律事务管理系统', org_code: 'dsjsj00001', checkList: [] },
        { org_name: '三重一大系统', org_code: 'dsjsj00002', checkList: [] },
        { org_name: 'JYKJ', org_code: 'dsjsj00003', checkList: [] },
        { org_name: '科技项目', org_code: 'dsjsj00004', checkList: [] },
        { org_name: '技改项目', org_code: 'dsjsj00005', checkList: [] },
        { org_name: '数字化项目', org_code: 'dsjsj00006', checkList: [] },
        { org_name: '电力营销', org_code: 'dsjsj00007', checkList: [] },
        { org_name: '境外项目', org_code: 'dsjsj00008', checkList: [] },
        { org_name: '燃料管理系统', org_code: 'dsjsj00009', checkList: [] },
        { org_name: '投资管理系统', org_code: 'dsjsj00010', checkList: [] },
        { org_name: 'SAP(ERP)', org_code: 'dsjsj00011', checkList: [] },
        { org_name: '财报系统', org_code: 'dsjsj00012', checkList: [] },
        { org_name: '财务共享', org_code: 'dsjsj00013', checkList: [] },
        { org_name: '采购系统', org_code: 'dsjsj00014', checkList: [] },
        { org_name: '产业数据中台', org_code: 'dsjsj00015', checkList: [] },
        { org_name: '对标管理系统', org_code: 'dsjsj00016', checkList: [] },
        { org_name: '司库系统', org_code: 'dsjsj00017', checkList: [] },
        { org_name: '综合办公', org_code: 'dsjsj00018', checkList: [] },
      ],
      values: [
        {
          name: 'code',
          caption: '代码',
          dataType: 'string',
          required: true,
          value: '',
        },
        {
          name: 'name',
          caption: '名称',
          dataType: 'string',
          required: true,
          value: '',
        },
        {
          name: 'weight',
          caption: '排序号',
          dataType: 'string',
          value: '',
        },
        {
          name: 'lev',
          caption: '级别',
          dataType: 'string',
          required: true,
          value: 'COMPANY',
        },
        {
          name: 'parentId',
          caption: '分类',
          dataType: 'int',
          required: true,
          value: null,
        },
        {
          name: 'description',
          caption: '详情',
          dataType: 'string',
          value: '',
        },
      ],

      visible: false,
      orgShow: false,
      systemData: [],
      type: 'add',
      modalForm: {
        name: '',
        code: '',
        description: '',
        weight: '',
        level: '',
      },
      editnode: true,
      searchform: 'searchform',
      formData: {
        name: '',
        code: '',
      },
      parentId: null,

      actions: [
        // 新增
        {
          label: '新建',
          id: 'create',
          permission: null,
          type: TableActionTypes.primary,
          callback: this.createMatters,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          callback: this.deleteRows,
        },
      ],
      columns: [
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          title: '代码',
          dataIndex: 'code',
        },
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '排序',
          dataIndex: 'weight',
        },
        {
          title: '级别',
          dataIndex: 'level',
        },
        {
          title: '备注',
          dataIndex: 'description',
        },
        {
          title: '操作',
          dataIndex: 'opt',
          aligen: 'center',
          width: '150px',
          customRender: (text, record, index) => {
            return (
              <span>
                <a
                  vOn:click={(evt) => {
                    this.association(record.id)
                  }}
                >
                  关联
                </a>{' '}
                <a
                  vOn:click={(evt) => {
                    this.detail(record.id)
                  }}
                >
                  明细
                </a>
              </span>
            )
          },
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: '-1',
        },
      ],
      classListData: [],
      className: '',
      ifZb: '',
      detailInfo: {
        code: '',
        name: '',
        parentId: '',
        description: '',
        weight: 0,
        ifZb: '',
        lev: 'COMPANY',
      },
      treeData: [],
      groupId: '',
      rules: {
        code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
      },
      nodeInfo: {},
      sysName: '',
      sysCode: '',
      checkSysList: [],
    }
  },
  created() {
    this.getOrgTypeListData()
  },
  methods: {
    // 选择需要关联的数据
    onCheck(checkedKeys, info) {
      this.checkSysList = info.checkedNodes
    },
    // 获取需要关联的数据
    systemTree(code, name) {
      this.systemData = []
      this.sysName = name
      this.sysCode = code
      this.orgShow = true
      this.confirmLoading = true
      const params = {
        columns: 'sys_name,org_code,org_name,porg_code',
        maxResults: 9999,
        startPosition: 0,
        expressions: [
          {
            dataType: 'string',
            name: 'sys_code',
            op: 'eq',
            stringValue: code,
          },
        ],
        buttonExpressions: [],
        formId: 'iamoperationrecord',
      }
      // const data = [
      //   {
      //     correlation: 0,
      //     id: 1,
      //     org_code: 'admin',
      //     org_name: '系统组织',
      //     porg_code: 'null',
      //     sys_code: 'dsjsj00001',
      //     sys_name: '法律事务管理系统',
      //   },
      // ]
      // this.systemData = this.toTree(data)

      MasterDataService.getSystemTree(params).then((res) => {
        if (res.data.data.length > 0) {
          res.data.data.map((item) => {
            if (item.correlation === 1) {
              item.disableCheckbox = true
              item.disable = true
            }
          })
          this.systemData = this.toTree(res.data.data)
        }
        this.confirmLoading = false
      })
    },
    // 保存关联数据
    saveSys() {
      const params = []
      this.checkSysList.forEach((val) => {
        const obj = {
          groupId: this.groupId,
          sysName: this.sysName,
          sysCode: this.sysCode,
          code: val.data.props.org_code,
          level: '公司',
          name: val.data.props.org_name,
          operation: getUserInfo().name,
          operationTime: new Date().getTime(),
        }
        params.push(obj)
      })
      MasterDataService.saveMasterData(params).then((res) => {
        // 保存成功后的回调
        message.success('保存成功', 1).then((res) => {
          this.orgShow = false
          this.getSystemData(this.groupId)
        })
      })
    },
    // 删除关联数据
    closeTag(id) {
      MasterDataService.revokeOrgData(id).then((res) => {
        // 保存成功后的回调
        message.success('删除成功', 1).then((res) => {
          this.getSystemData(this.groupId)
        })
      })
    },
    toTree(data) {
      const result = []
      const map = {}
      data.forEach((item) => {
        map[item.org_code] = item
      })
      data.forEach((item) => {
        const parent = map[item.porg_code]
        if (parent) {
          ;(parent.children || (parent.children = [])).push(item)
        } else {
          result.push(item)
        }
      })
      return result
    },
    exitSubmit() {
      const { id, code, name, parentId, description, weight, props } = this.detailInfo
      const params = {
        id: id,
        code: code,
        name: name,
        parentId: parentId,
        description: description,
        weight: weight,
        ifZb: props.ifzb,
        lev: props.lev,
      }
      MasterDataService.exitOrgData(params).then((res) => {
        message.success('修改成功')
        this.visible = false
        this.$refs.dataTable.refresh()
        this.$refs.masterTree.refreshKey()
      })
    },
    // 删除
    deleteRows() {
      if (!this.nodeInfo.id) return message.warning('请选择分类')
      if (this.nodeInfo.props.isEdit === 'false') return message.warning('不能删除系统数据')
      if (this.nodeInfo.children !== null && this.nodeInfo.children.length > 0)
        return message.warning('请先删除子节点')
      MasterDataService.deleteOrgData(this.nodeInfo.id).then(() => {
        message.success('删除成功')
        this.parentId = ''
        this.className = ''
        this.groupId = ''
        this.nodeInfo = {}
        for (const key in this.detailInfo) {
          this.detailInfo[key] = ''
          if (key === 'weight') {
            this.detailInfo[key] = 0
          } else if (key === 'lev') {
            this.detailInfo[key] = 'COMPANY'
          }
        }
        this.$refs.masterTree.refreshKey()
      })
    },
    save() {
      if (this.type === 'add') {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.detailInfo.parentId = this.parentId
            MasterDataService.saveOrgData(this.detailInfo).then((res) => {
              // 保存成功
              message.success('保存成功')
              this.visible = false
              for (const key in this.detailInfo) {
                this.detailInfo[key] = ''
                if (key === 'weight') {
                  this.detailInfo[key] = 0
                } else if (key === 'lev') {
                  this.detailInfo[key] = 'COMPANY'
                }
              }
              this.$refs.masterTree.refreshKey()
            })
          }
        })
      } else {
        this.exitSubmit()
      }
    },

    handleOk() {
      this.visible = false
    },
    // 获取分类
    getOrgTypeListData() {
      MasterDataService.getOrgTypeList().then((res) => {
        this.classListData = res.data
      })
    },
    createMatters() {
      // 请选择分类
      if (this.parentId === '') return message.warning('请选择分类')
      this.visible = true
      this.type = 'add'
    },
    onShowEdit(record) {
      this.visible = true
      this.type = 'edit'
      this.detailInfo = record
    },
    // 关联
    association(id) {
      const url = '#/masterdata-field-binding?id=' + id // 新页面要打开的路由地址
      // 新页面要打开的路由地址
      window.open(url, '_blank')
    },
    // 明细
    detail(id) {
      const url = '#/master-data-operate?id=' + id // 新页面要打开的路由地址
      // 新页面要打开的路由地址
      window.open(url, '_blank')
    },
    // 点击树
    treeSelect(id, node) {
      this.parentId = node.id
      if (id.length === 0 || id[0] === '-1') {
        this.groupId = '-1'
        this.nodeInfo = {}
        this.className = '组织机构'
      } else {
        this.groupId = id[0]
        this.nodeInfo = node
        this.getSystemData(id[0])
        this.className = node.text
      }
    },
    // 获取系统绑定数据
    getSystemData(id) {
      const params = {
        columns: 'id,code,groupId,sysName,name,sysCode',
        maxResults: 9999,
        startPosition: 0,
        expressions: [
          {
            dataType: 'str',
            name: 'sysCode',
            op: 'in',
            stringValues: [
              'dsjsj00001',
              'dsjsj00002',
              'dsjsj00003',
              'dsjsj00004',
              'dsjsj00005',
              'dsjsj00006',
              'dsjsj00007',
              'dsjsj00008',
              'dsjsj00009',
              'dsjsj00010',
              'dsjsj00011',
              'dsjsj00012',
              'dsjsj00013',
              'dsjsj00014',
              'dsjsj00015',
              'dsjsj00016',
              'dsjsj00017',
              'dsjsj00018',
            ],
          },
          {
            dataType: 'long',
            name: 'groupId',
            op: 'eq',
            longValue: id,
          },
        ],
        buttonExpressions: [],
        formId: 'iamOperationAssociationRecord',
      }
      MasterDataService.getSystemInfo(params).then((res) => {
        this.orgList.map((item) => {
          item.checkList = []
          res.data.data.forEach((val) => {
            if (item.org_code === val.sysCode) {
              val.isShow = true
              val.org_name = val.name
              item.checkList.push(val)
            }
          })
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.loading {
  height: 300px;
}
.wrap-height {
  height: 100%;

  .row-height {
    display: flex;
    flex: auto;
    height: 100%;

    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
      padding: 10px;
      overflow-y: auto;
      background: #fff;
      .label-item {
        display: flex;
        // align-items: center;
        justify-content: space-between;
        width: 300px;
        .button {
          margin-left: 15px;
        }
      }
      .card {
        height: 100%;
      }
      .row {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 10px;
        .row-right {
          margin-left: 20px;
        }
      }
    }
  }
}

.dataclass {
  :global(.projectlist .ant-table-empty .ant-table-body) {
    overflow-x: hidden !important;
  }

  :global(span > .ant-btn:nth-child(2)) {
    color: #fff;
    background-color: #1890ff;
    border-color: #1890ff;
  }

  // :global(.ant-table-placeholder) {
  //   width: auto;
  // }
}
</style>
