<template>
  <div>
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" tab="本应用字典">
        <a-row :gutter="24" :class="$style.fullHeight">
          <a-col :md="5" :sm="24" :class="$style.fullHeight">
            <a-card :class="[$style.fullHeight, $style.treecard]">
              <div :class="$style.header">
                <a-input-search
                  v-model="searchStr"
                  placeholder=""
                  allow-clear
                  @change="onSearchChange"
                />
                <a-button
                  v-if="!appNodeId"
                  type="link"
                  icon="plus"
                  size="large"
                  title="新建"
                  @click="handleNode({ dataRef: selectedNode }, 'add')"
                />
              </div>
              <a-tree
                :key="key"
                :class="$style.tree"
                :load-data="onLoadData"
                :tree-data="treeData"
                :selected-keys="selectedKeys"
                :auto-expand-parent="autoExpandParent"
                :expanded-keys.sync="expandedKeys"
                @select="onSelect"
                @expand="onExpand"
              >
                <template v-slot:title="node">
                  <div :class="$style.node">
                    <span v-if="node.title.indexOf(searchStr) > -1">
                      {{ node.title.substr(0, node.title.indexOf(searchStr)) }}
                      <span :class="$style.searchColor">{{ searchStr }}</span>
                      {{ node.title.substr(node.title.indexOf(searchStr) + searchStr.length) }}
                    </span>
                    <span v-else>{{ node.title }}</span>
                    <span v-if="node.props.isRoot === 'false' && !appNodeId" :class="$style.action">
                      <a-icon type="edit" title="编辑" @click.stop="handleNode(node, 'editor')" />
                      <a-icon type="delete" title="删除" @click.stop="delNode(node)" />
                    </span>
                  </div>
                </template>
              </a-tree>
            </a-card>
          </a-col>
          <a-col :class="$style.fullHeight" :md="19" :sm="24">
            <a-card :class="$style.fullHeight">
              <sd-data-table-ex
                form-id="weAppDictValue"
                :page-id="computedPageId"
                :columns="columns"
                :actions="actions"
                :filter-expressions="expressions"
                :show-selection="!appNodeId"
                :search-fields="['name']"
                :modal-props="appNodeId ? { footer: null } : undefined"
              >
                <template v-slot:form="{ model }">
                  <sd-form-item name="id" hidden />
                  <sd-form-item
                    name="keyId"
                    hidden
                    :input-props="{
                      defaultValue: model.keyName || selectedNode.id,
                    }"
                  ></sd-form-item>
                  <sd-form-item
                    name="keyName"
                    :input-props="{
                      defaultValue: model.keyName || selectedNode.title,
                      disabled: true,
                    }"
                  />

                  <sd-form-item name="code" />
                  <sd-form-item name="name" />
                  <sd-form-item name="sortNum" />
                  <sd-form-item name="status" />
                  <sd-form-item name="valueDesc" />
                  <sd-form-item name="appId" hidden :input-props="{ defaultValue: appId }" />
                </template>
              </sd-data-table-ex>
            </a-card>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="2" tab="系统数据字典">
        <div :class="$style.sys">
          <SdSysparamsMaintain module :class="$style.sysdata" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="3" tab="树形字典">
        <div :class="$style.sys">
          <SdTreedataDictionary :app-id="appId" :app-node-id="appNodeId" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="系统树形字典">
        <div :class="$style.sys">
          <SdTreedataDictionary module :app-node-id="appNodeId" />
        </div>
      </a-tab-pane>
    </a-tabs>
    <a-modal
      title="字典项管理"
      :visible="visible"
      :width="700"
      destroy-on-close
      @ok="saved"
      @cancel="visible = false"
    >
      <sd-detail-form
        ref="detail"
        :record-id="recordId"
        page-id="app/dict/weAppDictKey"
        :class="$style.detailForm"
        @saved="saved"
      >
        <template v-slot="{ model }">
          <sd-form-item
            name="parentId"
            hidden
            :input-props="{ defaultValue: model.parentId || parentId, disabled: true }"
          />
          <sd-form-item
            name="parentName"
            :input-props="{ defaultValue: model.parentName || parentName, disabled: true }"
          />
          <sd-form-item name="appId" hidden :input-props="{ defaultValue: appId }" />
          <sd-form-item name="name" />
          <sd-form-item name="sortNum" />
          <sd-form-item name="keyDesc" />
        </template>
      </sd-detail-form>
    </a-modal>
  </div>
</template>

<script>
import TableActionTypes from '@/common/services/table-action-types'
import axios from '@/common/services/axios-instance'
import { Modal } from 'ant-design-vue'
import SdSysparamsMaintain from '@/sys-params-manage/sd-sysparams-maintain.vue'
import SdTreedataDictionary from '@/workbench/sd-treedata-dictionary.vue'
import components from './_import-components/sd-data-dictionary-import'
const formatTree = (arr) => {
  arr.forEach((a) => {
    if (a.children) formatTree(a.children)
    a.key = a.id
    a.title = a.text
    a.scopedSlots = { title: 'title' }
  })
}
const columns = [
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  {
    dataIndex: 'name',
    title: '名称',
    sdClickable: true,
  },
  {
    dataIndex: 'code',
    title: '编码',
  },
  {
    dataIndex: 'sortNum',
    title: '排序号',
  },
  {
    dataIndex: 'status',
    title: '状态',
  },
  {
    dataIndex: 'valueDesc',
    title: '描述',
  },
]
export default {
  name: 'SdDataDictionary',
  metaInfo: {
    title: '数据字典',
  },
  components: { SdSysparamsMaintain, SdTreedataDictionary, ...components },
  data() {
    return {
      key: 0,
      expandedKeys: [],
      appId: '',
      treeData: [],
      recordId: '',
      searchStr: '',
      columns,
      selectedNode: {},
      selectedKeys: [],
      visible: false,
      parentName: '',
      parentId: '',
      autoExpandParent: true,
      searchDataList: [],
      appNodeId: undefined,
    }
  },
  computed: {
    expressions() {
      return [
        {
          dataType: 'str',
          name: 'keyId',
          op: 'eq',
          stringValue: this.selectedKeys[0] || '-1',
        },
      ]
    },
    actions() {
      if (this.appNodeId) {
        return []
      }
      const tActions = [
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete,
        },
      ]
      if (!this.selectedKeys.includes('-1')) {
        tActions.push({
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        })
      }
      return tActions
    },
    computedPageId() {
      if (this.appNodeId) {
        return 'app/dict/weAppDictValue?mode=VIEW'
      }
      return 'app/dict/weAppDictValue'
    },
  },
  created() {
    this.appId = this.$route.query.appId
    this.appNodeId = this.$route.query.appNodeId
    this.getRootNode()
  },
  methods: {
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSearchChange(e) {
      this.searchStr = e.target.value
      const expandedKeys = this.searchDataList
        .filter((s) => s.title.indexOf(e.target.value) > -1)
        .map((m) => m.parentKey)
      Object.assign(this, {
        expandedKeys,
        searchStr: e.target.value,
        autoExpandParent: true,
      })
    },
    getRootNode() {
      return axios.get(`api/framework/v1/app-dict/tree-root/${this.appId}`).then((res) => {
        this.treeData = [res.data]
        this.selectedKeys = [res.data.id]
        this.expandedKeys = ['-1']
        formatTree(this.treeData)
        this.selectedNode = this.treeData[0]
      })
    },
    flatter(dataSource, parentKey) {
      const flatArr = []
      dataSource.forEach((item) => {
        const { children, ...items } = item
        flatArr.push({ ...items, parentKey })
        if (item.children) flatArr.push(...this.flatter(item.children, item.key))
      })
      return flatArr
    },
    onLoadData(treeNode) {
      return axios
        .get(`api/framework/v1/app-dict/all/tree-sub/${this.appId}?parentId=${treeNode.dataRef.id}`)
        .then((res) => {
          if (res.data) {
            res.data.forEach((r) => {
              r.parentId = treeNode.dataRef.id
              r.parentName = treeNode.dataRef.title
            })
            treeNode.dataRef.children = res.data
            formatTree(this.treeData)
            this.searchDataList = this.flatter(this.treeData)
          }
        })
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.selectedNode = info.node.dataRef
    },
    handleNode(node, type) {
      if (type === 'add') {
        this.parentName = node.dataRef.title
        this.parentId = node.dataRef.id
        this.recordId = ''
      } else {
        this.parentName = node.dataRef.parentName
        this.parentId = node.dataRef.parentId
        this.recordId = node.dataRef.id
      }
      this.visible = true
    },
    saved() {
      this.$refs.detail.save().then(() => {
        this.visible = false
        this.refreshTree()
      })
    },
    refreshTree() {
      this.treeData = []
      this.getRootNode().then(() => {
        this.key++
      })
      this.key++
    },
    delNode(node) {
      Modal.confirm({
        title: '确认删除这个项和其所有子项吗？',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          axios.delete(`api/framework/v1/page/weAppDictKey?ids=${node.dataRef.id}`).then(() => {
            this.refreshTree()
          })
        },
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$line: 24px;
.full-height {
  height: 100%;
  :global .ant-card-body {
    height: 100%;
    overflow: auto;
  }
  &.treecard {
    height: 100%;
  }
}
.detail-form {
  :global .ant-btn {
    display: none;
  }
}
.header {
  display: flex;
  align-items: center;
}
.search-color {
  color: $orange-6;
}
.tree {
  :global .ant-tree-node-content-wrapper {
    width: calc(100% - 24px);
    :global .anticon {
      display: none;
      float: right;
      line-height: $line;
    }
    &:hover {
      :global .anticon {
        display: inline-block;
        margin-left: 5px;
      }
    }
  }
}
.sys {
  :global .ant-col:nth-child(1) {
    max-height: 700px;
    overflow: auto;
  }
}
</style>
