<template>
  <div :class="[$style.wrapHeight, $style.dataclass]">
    <div :class="$style.rowHeight">
      <audit-class-tree
        ref="auditMaintainCatalogTree"
        show-line
        top-node-text="数据分类"
        :is-select-dep="true"
        :draggable="true"
        :cate="true"
        :tree-data="categoryTreeSearched"
        :replace-fields="{ title: 'categoryName', key: 'id' }"
        v-bind="{ checkable: true, checkStrictly: true }"
        style="width: 20%"
        @treeSelect="treeSelect"
        @onChangeSearch="onCategorySearch"
        @onCheck="onCategoryCheck"
      >
        <div style="display: flex;justify-content: space-between">
          <a-button type="primary" @click="onCategoryAdd">新建分类</a-button>
          <a-button type="primary" :disabled="!nowCategory" @click="onCategoryEdit">编辑</a-button>
          <a-popconfirm
            title="确定删除此分类吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onCategoryDel"
            @cancel="showCategory = false"
          >
            <a-button :disabled="!nowCategory">删除</a-button>
          </a-popconfirm>
          <!--          <a-button @click="some">测试</a-button>-->
        </div>
      </audit-class-tree>
      <div :class="$style.rightcard">
        <a-card>
          <!-- page-id="audit/datacube/iamServerInfo" -->
          <SdDataTableEx
            ref="dataTable"
            :projectlist="true"
            form-id="iamServerInfo"
            :columns="columns"
            :actions="actions"
            data-url="api/xcoa-mobile/v1/server-info/serverList"
            :filter-expressions="expressions"
            :search-fields="['tableNameCN', 'tableNameEN']"
          >
            <template slot="operation" slot-scope="text, record">
              <a-button type="link" @click="tableEdit(record)">编辑</a-button>
              <a-button type="link" @click="tableDel(record)">删除</a-button>
            </template>
          </SdDataTableEx>
        </a-card>
      </div>
    </div>
    <a-modal v-model="showCategory" @ok="onCategorySave">
      <a-form-model
        ref="categoryForm"
        :model="categoryForm"
        :rules="categoryRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-form-model-item label="父级分类">
          <a-cascader
            v-model="parentId"
            :disabled="isType === 'exit'"
            :options="categoryOptions"
            :change-on-select="true"
            placeholder="请选择"
            :field-names="{ label: 'categoryName', value: 'id', children: 'children' }"
          />
        </a-form-model-item>
        <a-form-model-item label="分类名称" prop="categoryName">
          <a-input v-model="categoryForm.categoryName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="分类类型">
          <a-select v-model="categoryForm.classifyType">
            <a-select-option value="1">宽表类型</a-select-option>
            <a-select-option value="2">财务报表非结构化</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="分类描述">
          <a-input v-model="categoryForm.categoryDesc"></a-input>
        </a-form-model-item>
        <a-form-model-item label="分类排序" prop="sortNum">
          <a-input-number v-model="categoryForm.sortNum"></a-input-number>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal v-model="showTable" @ok="tableEditConfirm">
      <a-form-model
        ref="tableForm"
        :model="tableForm"
        :rules="tableRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="服务器ip" prop="ip">
          <a-input v-model="tableForm.ip"></a-input>
        </a-form-model-item>
        <a-form-model-item label="账号" prop="account">
          <a-input v-model="tableForm.account" autocomplete="new-user"></a-input>
        </a-form-model-item>
        <a-form-model-item label="密码" prop="pass">
          <a-input-password v-model="tableForm.pass" autocomplete="new-password"></a-input-password>
        </a-form-model-item>
        <a-form-model-item label="表中文名" prop="tableNameCN">
          <a-input v-model="tableForm.tableNameCN"></a-input>
        </a-form-model-item>
        <a-form-model-item label="表英文名" prop="tableNameEN">
          <a-input v-model="tableForm.tableNameEN"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据库名称" prop="databaseName">
          <a-input v-model="tableForm.databaseName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="端口号" prop="port">
          <a-input v-model="tableForm.port"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据库schema" prop="schemaName">
          <a-input v-model="tableForm.schemaName"></a-input>
        </a-form-model-item>
        <!-- 序号 -->
        <a-form-model-item label="序号">
          <a-input-number v-model="tableForm.sortNum" :min="0"></a-input-number>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import auditClassTree from './audit-class-tree.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import TableActionTypes from '@/common/services/table-action-types'
import apis from './data-market'
import { generateTree, getTreeIds } from '@product/iam/audit/dataMarket/util'
import axios from '@/common/services/axios-instance'

export default {
  name: 'DataRuleManage',
  metaInfo: {
    title: '数据权限管理',
  },
  components: {
    SdDataTableEx,
    auditClassTree,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      columns: [
        { dataIndex: 'classifyId', sdHidden: true },
        { dataIndex: 'classifyName', sdHidden: true },
        { dataIndex: 'ip', sdHidden: true },
        { dataIndex: 'account', sdHidden: true },
        { dataIndex: 'pass', sdHidden: true },
        { title: '表中文名', dataIndex: 'tableNameCN' },
        { title: '表英文名', dataIndex: 'tableNameEN' },
        // 序号
        { title: '序号', dataIndex: 'sortNum' },
        { dataIndex: 'databaseName', sdHidden: true },
        { dataIndex: 'port', sdHidden: true },
        { dataIndex: 'schemaName', sdHidden: true },
        {
          title: '操作',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      actions: [
        {
          label: '新建数据表',
          permission: null,
          type: TableActionTypes.primary,
          callback: this.tableAdd,
        },
        {
          label: '数据授权',
          permission: null,
          callback: this.categoryAuth,
        },
        {
          label: '删除',
          permission: null,
          type: TableActionTypes.ex.delete,
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'classifyId',
          op: 'eq',
          longValue: 0,
        },
      ],
      isroot: true,
      className: '',
      categoryTree: [],
      categoryTreeSearched: [],
      categoryForm: {},
      nowCategory: null,
      showCategory: false,
      categoryRules: {
        categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        sortNum: [{ required: true, message: '请输入分类排序', trigger: 'blur' }],
      },
      tableRules: {
        ip: [{ required: true, message: '请输入ip地址', trigger: 'blur' }],
        account: [{ required: true, message: '请输入数据表账号', trigger: 'blur' }],
        pass: [{ required: true, message: '请输入数据表密码', trigger: 'blur' }],
        tableNameCN: [{ required: true, message: '请输入表中文名', trigger: 'blur' }],
        tableNameEN: [{ required: true, message: '请输入表英文名', trigger: 'blur' }],
        databaseName: [{ required: true, message: '请输入数据库名称', trigger: 'blur' }],
        port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
        schemaName: [{ required: true, message: '请输入schema', trigger: 'blur' }],
      },
      categoryChecked: [],
      tableForm: {},
      showTable: false,
      parentId: [],
      isType: '',
    }
  },
  computed: {
    categoryOptions() {
      return [{ categoryName: '顶级分类', id: 0, children: this.categoryTree }]
    },
  },
  created() {
    this.getCategory()
  },
  methods: {
    tableAdd() {
      if (!this.nowCategory) {
        Modal.warning({ title: '提示', content: '请先选择分类' })
        return
      }
      if (this.nowCategory.classifyType === '2') {
        Modal.warning({ title: '提示', content: '此类型的分类不支持添加数据表' })
        return
      }
      this.tableForm = {
        classifyId: this.nowCategory.id,
        classifyName: this.nowCategory.categoryName,
        ip: '',
        account: '',
        pass: '',
        tableNameCN: '',
        tableNameEN: '',
        databaseName: '',
        port: '',
        schemaName: '',
        sortNum: 0,
      }
      this.showTable = true
    },
    tableEdit(table) {
      this.tableForm = { ...table }
      this.showTable = true
    },
    tableEditConfirm() {
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          // const data = {
          //   pageFlowId: '08ecc6f9-ed1d-4559-98ea-76a0e9661d6a',
          //   pagePath: 'audit/datacube/iamServerInfo',
          //   eventId: 'save',
          //   inputs: Object.entries(this.tableForm).map(([k, v]) => ({ name: k, value: v })),
          // }
          // if (this.tableForm.id) data.eventId = 'update'
          apis.saveDataTable(this.tableForm).then((res) => {
            message.success('保存成功')
            this.refresh()
            this.showTable = false
          })
        } else {
          return false
        }
      })
    },
    tableDel(table) {
      const that = this
      Modal.confirm({
        title: '提示',
        content: '是否删除此项？',
        onOk() {
          return new Promise((resolve, reject) => {
            axios
              .delete('api/xcoa-mobile/v1/iam-page/iamServerInfo', { params: { ids: table.id } })
              .then((res) => {
                message.success('已删除')
                that.refresh()
                resolve()
              })
          })
        },
      })
    },
    onCategoryCheck({ checked }) {
      this.categoryChecked = [...checked]
    },
    onCategoryAdd() {
      this.parentId = []
      this.categoryForm = {
        parentId: [],
        classifyType: '1',
        categoryName: '',
        categoryDesc: '',
        sortNum: 0,
      }
      this.showCategory = true
      this.isType = 'add'
    },
    onCategoryEdit() {
      const { id, parentId, categoryName, classifyType, categoryDesc, sortNum } = this.nowCategory
      const ids = [0, ...getTreeIds(this.categoryTree, id)]
      this.parentId = ids
      this.categoryForm = {
        id,
        parentId: ids,
        categoryName,
        classifyType,
        categoryDesc,
        sortNum,
      }
      this.showCategory = true
      this.isType = 'exit'
    },
    onCategoryDel() {
      apis.categoryDel({ ids: this.nowCategory.id }).finally(() => {
        this.nowCategory = null
        this.getCategory()
      })
    },
    onCategorySave() {
      if (this.parentId.length === 0) {
        return message.error('请选择父级分类')
      }
      this.$refs.categoryForm.validate((valid) => {
        if (valid) {
          if (this.isType === 'add') {
            if (this.parentId.length >= 2) {
              this.categoryForm.parentId = this.parentId[this.parentId.length - 1]
            } else {
              this.categoryForm.parentId = 0
            }
          } else {
            if (this.parentId.length >= 2) {
              this.categoryForm.parentId = this.parentId[this.parentId.length - 2]
            } else {
              this.categoryForm.parentId = 0
            }
          }
          const data = {
            pageFlowId: '08ecc6f9-ed1d-4559-98ea-76a0e9661d6a',
            pagePath: 'audit/datacube/iamDataCube',
            eventId: 'save',
            inputs: Object.entries(this.categoryForm).map(([k, v]) => ({ name: k, value: v })),
          }
          // console.log(data)
          apis.setShareStatus(data).then((res) => {
            message.success('保存成功')
            this.getCategory()
            this.showCategory = false
          })
        } else {
          return false
        }
      })
    },
    // 搜索分类
    onCategorySearch(val) {
      this.categoryTreeSearched = this.categoryFilter(this.categoryTree, val)
    },
    categoryFilter(list, val) {
      const res = list.filter((i) => i.categoryName.includes(val))
      res.forEach((item) => {
        if (item.children && item.children.length) {
          item.children = this.categoryFilter(item.children, val)
        }
      })
      return res
    },
    getCategory() {
      apis.categoryListWhole().then((res) => {
        this.categoryTree = generateTree(res.data, 'id', 'parentId', 'children')
        this.onCategorySearch('')
      })
    },
    treeSelect(selectedKeys, info) {
      const nowNode = info.selectedNodes[0]
      if (nowNode) {
        this.nowCategory = nowNode.data.props
        this.expressions = [
          {
            dataType: 'long',
            name: 'classifyId',
            op: 'eq',
            longValue: this.nowCategory.id,
          },
        ]
      } else {
        this.nowCategory = null
      }
    },
    refresh() {
      this.$refs.dataTable.refresh()
    },
    tableAuth() {
      const tableIds = this.$refs.dataTable.getSelectedRowKeys()
      if (tableIds.length) {
        const url = '#/data-rule-apply?selectid=' + tableIds.join(',') // 新页面要打开的路由地址
        // 新页面要打开的路由地址
        window.open(url, '_blank')
      } else {
        Modal.warning({ title: '提示', content: '请选择数据表!' })
      }
    },
    categoryAuth() {
      if (this.categoryChecked.length) {
        const url = '#/data-rule-apply?classid=' + this.categoryChecked.join(',') // 新页面要打开的路由地址
        // 新页面要打开的路由地址
        window.open(url, '_blank')
      } else {
        Modal.warning({ title: '提示', content: '请选择数据分类!' })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
.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>
