<template>
  <div :class="[$style.wrapHeight, $style.maintainlist]">
    <div :class="$style.rowHeight">
      <!-- <audit-maintain-classify-tree
        ref="auditMattersCatalogTree"
        :key="key"
        show-line
        top-node-text="审计模型"
        :is-select-dep="true"
        @treeSelect="treeSelect"
        @de,
    AduitAreaTreepChanged="depChanged"
      ></audit-maintain-classify-tree> -->
      <AduitAreaTree ref="auditAreaTree" @treeSelect="treeSelect"></AduitAreaTree>
      <div :class="$style.rightcard">
        <a-card>
          <!-- 高级搜索组件 -->
          <audit-advanced-query
            :expand="expand"
            :search-data="formData"
            :ref-name="searchform"
            :search-style="{ height: '150px', left: '20px', top: '57px' }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-col :span="12">
                <a-form-model-item :label="'模型编号'" prop="modelCode">
                  <a-input v-model="formData.modelCode" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="'模型名称'" prop="modelName">
                  <a-input v-model="formData.modelName" allow-clear />
                </a-form-model-item>
              </a-col>
            </template>
          </audit-advanced-query>

          <sd-data-table-ex
            ref="SJMXDataTable"
            :projectlist="true"
            :filter-expressions="expressions"
            :columns="columns"
            :actions="actions"
            form-id="iamModelMaintain"
            page-id="audit/maintain/iamModelMaintain"
            :search-fields="['modelCode', 'modelName']"
            show-selection
            :show-advance-query="true"
            :fnonloadsum="fnonloadsum"
            @searchbtnClick="searchbtnClick"
          >
            <div slot="islink" slot-scope="text, record">
              <a v-if="isCreateUser(record)" :title="text" @click="rowClick(record)">{{ text }}</a>
              <span v-else :title="text">{{ text }}</span>
            </div>
            <div slot="shareType" slot-scope="text, record">
              <a-switch
                v-if="isCreateUser(record)"
                :checked="shareStatus(record.sharedSetting)"
                checked-children="开"
                un-checked-children="关"
                @change="shareTypeChange(record)"
              ></a-switch>
            </div>
            <div slot="edit" slot-scope="text, record">
              <a-button
                :disabled="!isCreateUser(record)"
                type="link"
                :title="text"
                @click="setStatus(record)"
                >{{ record.lineStatus === '下线' ? '上线' : '下线' }}</a-button
              >
            </div>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableActionTypes from '@/common/services/table-action-types'
import { getUserInfo } from '@/common/store-mixin'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import components from './_import-components/audit-maintain-list-import'
import auditMaintainService from './audit-maintain-service'
import AduitAreaTree from './aduit-area-tree.vue'

export default {
  name: 'AuditMaintainList',
  metaInfo: {
    title: '审计模型',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    AduitAreaTree,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],

  data() {
    return {
      key: 0,
      treeData: [],
      searchform: 'searchform',

      formData: {
        modelCode: '',
        modelName: '',
      },
      formId: 'iamModelMaintain',
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '模型名称',
          dataIndex: 'modelName',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '模型编号',
          // dataIndex: 'id',
          dataIndex: 'modelCode',
        },
        {
          title: '风险描述',
          dataIndex: 'risk',
        },
        // 上下线状态
        {
          title: '操作',
          dataIndex: 'lineStatus',
          scopedSlots: { customRender: 'edit' },
        },
        //
        // {
        //   title: '共享设置',
        //   dataIndex: 'sharedSetting',
        //   // 插槽
        //   scopedSlots: { customRender: 'shareType' },
        // },
        // 创建人
        {
          title: '创建人',
          dataIndex: 'creatorId',
          sdHidden: true,
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'source',
          op: 'eq',
          stringValue: 0,
        },
      ],
      catalogId: null,
      catalogName: '',
      actions: [
        {
          label: '新建',
          permission: 'create',
          id: 'new',
          type: TableActionTypes.primary,
          callback: this.createMatters,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
      ],
      actionscsh: [
        // todo暂时注释 11-30
        // {
        //   label: '模型授权',
        //   id: 'auditWarrant',
        //   permission: null,
        //   callback: this.Matterssq,
        // },
        // {
        //   label: '分类配置',
        //   id: 'auditMattersCatalog',
        //   permission: null,
        //   callback: () => {
        //     const url = '#/sd-frame/audit-maintain-catalog' // 新页面要打开的路由地址
        //     window.open(url)
        //     // openAsTrustId(url, null)
        //   },
        // },
      ],
      parentorgId: '',
      isroot: true,
      modelDomain: '',
    }
  },
  created() {},
  methods: {
    setStatus(record) {
      const status = record.lineStatus === '下线' ? 1 : 0
      auditMaintainService
        .updateModelStatus({ id: parseInt(record.id), status: status })
        .then((res) => {
          if (res) {
            this.refresh()
          }
        })
    },
    // <!-- 判断自己是否是创建人 -->
    isCreateUser(record) {
      const userInfo = getUserInfo()
      const allUserAdmin = ['00942922', '00332032', '00372263', '00350134']
      return userInfo.id === record.creatorId || allUserAdmin.includes(userInfo.account)
    },
    shareStatus(record) {
      return record === 0
    },
    depChanged(oldId, value) {
      this.parentorgId = oldId
      // 获取当前节点权限 判断按钮是否显示
      if (typeof this.parentorgId !== 'number' && this.parentorgId.indexOf('o_') > -1) {
        this.showeditbutton(this.parentorgId.replaceAll('o_', ''))
      } else {
        this.showeditbutton(this.parentorgId)
      }
    },
    // 调整共享开关
    shareTypeChange(record) {
      const type = record.sharedSetting === 0 ? 1 : 0
      auditMaintainService
        .setShareStatus({ id: parseInt(record.id), sharedSetting: type })
        .then((res) => {
          if (res) {
            this.refresh()
          }
        })
    },
    fnonloadsum() {
      if (
        document
          .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
          .getElementsByClassName('ant-btn').length > 4 &&
        document
          .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
          .getElementsByClassName('ant-btn')[5]
          .innerHTML.indexOf('模型授权') > -1
      ) {
        if (
          document
            .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
            .getElementsByClassName('ant-btn').length > 4 &&
          document
            .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
            .getElementsByClassName('ant-btn')[5]
            .classList.value.indexOf('ant-btn-primary') === -1
        ) {
          document
            .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
            .getElementsByClassName('ant-btn')[5]
            .classList.add('ant-btn-primary')
        }
      }
      if (
        document
          .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
          .getElementsByClassName('ant-btn').length > 4 &&
        document
          .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
          .getElementsByClassName('ant-btn')[4]
          .innerHTML.indexOf('删') > -1
      ) {
        document
          .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
          .getElementsByClassName('ant-btn')[4]
          .parentElement.appendChild(
            document
              .getElementsByClassName('maintainlist_audit-maintain-list_product')[0]
              .getElementsByClassName('ant-btn')[4]
          )
      }
    },
    treeSelect(selectedKeys, info) {
      this.modelDomain = selectedKeys[0] || ''
      this.handleSearch()
    },
    // 判断按钮显示
    showeditbutton(deptId) {
      // axios({
      //   url: 'api/xcoa-mobile/v1/iammodelmaintain/getRole?selectOrgId=' + deptId,
      //   method: 'get',
      // }).then((res) => {
      //   if (res.data === true) {
      //     if (this.actions.length === 0) {
      // todo暂时放开权限11-30
      // this.actionscsh.forEach((a) => {
      //   this.actions.push(a)
      // })
      //     }
      //   } else {
      //     this.actions = []
      //   }
      // })
    },
    createMatters() {
      if (this.modelDomain !== '') {
        const url = '/audit-maintain-from?modelDomain=' + this.modelDomain
        // 新页面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.refresh()
          }
        })
      } else {
        Modal.confirm({
          title: '请先选择审计模型领域',
          content: '请先选择审计模型领域。',
          okText: '确定',
          okType: 'danger',
        })
      }
    },
    Matterssq() {
      const arrid = this.$refs.SJMXDataTable.getSelectedRowKeys()
      if (arrid.length > 0) {
        const url = '#/audit-warrant-from?selectid=' + arrid.join(',') // 新页面要打开的路由地址
        // 新页面要打开的路由地址
        window.open(url, '_blank')
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择审计模型!',
        })
      }
    },
    refresh() {
      return this.$refs.SJMXDataTable.refresh(true)
    },
    rowClick(record) {
      const url = '/audit-maintain-from?record=' + record.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 查询
    handleSearch() {
      this.expressions = []
      this.expressions.push({
        dataType: 'str',
        name: 'source',
        op: 'eq',
        stringValue: 0,
      })
      // 模型编号
      if (this.formData.modelCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'modelCode',
          op: 'like',
          stringValue: `%${this.formData.modelCode}%`,
        })
      }
      // 模型名称
      if (this.formData.modelName) {
        this.expressions.push({
          dataType: 'str',
          name: 'modelName',
          op: 'like',
          stringValue: `%${this.formData.modelName}%`,
        })
      }
      // 模型领域
      if (this.modelDomain) {
        this.expressions.push({
          dataType: 'str',
          name: 'modelDomain',
          op: 'eq',
          stringValue: this.modelDomain,
        })
      }
    },
  },
}
</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%;
    }
  }
}
.maintainlist {
  :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>
