<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <div :class="$style.rightcard">
        <a-card>
          <div :class="$style.wrapper">
            <audit-advanced-query
              :expand="expand"
              :search-data="formData"
              :ref-name="'searchform'"
              :search-style="{ height: '130px', left: '20px', top: '64px', width: '100%' }"
              :search-fun="handleSearch"
              @searchedClick="searchedClick"
            >
              <template>
                <a-col :span="12">
                  <a-form-model-item :label="'审计单位'" prop="auditOrgName">
                    <a-input v-model="formData.auditOrgName" allow-clear />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item :label="'被审计对象'" prop="orgName">
                    <a-input v-model="formData.orgName" allow-clear />
                  </a-form-model-item>
                </a-col>
              </template>
            </audit-advanced-query>
            <div :class="[$style.btns]">
              <audit-advanced-export
                v-if="true"
                ref="exportBtn"
                :class-style="[$style.buttonSpacing]"
                :exclebxh="false"
                :expressions="expressions"
                :config-id="51"
                :v-show="false"
              />
            </div>
            <SdDataTableEx
              ref="oaTable"
              :form-id="formId"
              :columns="columns"
              :actions="actions"
              :filter-expressions="expressions"
              :data-url="dataurl"
              :show-selection="true"
              :show-advance-query="true"
              :search-fields="['auditOrgName', 'orgName']"
              :row-selection="{ type: 'radio' }"
              @recordsDeleted="onRecordsDeleted"
              @searchbtnClick="searchbtnClick"
            >
              <a
                slot="fldSubject"
                slot-scope="text, record"
                :title="text"
                @click="fnReadDoc(record)"
                >{{ text }}</a
              >

              <a slot="opt" slot-scope="text, record" @click="fnEditDoc(record)">编辑</a>
            </SdDataTableEx>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import PageService from '@/common/services/page-service'
import { getUserInfo, getUserPerms } from '@/common/store-mixin'

import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import auditAdvancedQuery from '../../../components/audit-advanced-query.vue'
import auditAdvancedExport from '../../../components/audit-advanced-export.vue'
import components from './_import-components/iam-source-target-list-import'

export default {
  name: 'IamSourceTargetList',
  metaInfo: {
    title: '审计对象',
  },
  components: {
    auditAdvancedQuery,
    SdDataTableEx,
    ...components,
    auditAdvancedExport,
  },
  mixins: [auditAdvancedQueryMixins],

  props: {
    // 是不是用于选择知识
    isSelectd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formData: {
        auditOrgName: '',
        orgName: '',
        cUser: '',
      },
      expand: false,
      categorys: [],
      activeKey: 'textlist',
      isKmAdmin: false,
      expressions: [],
      dataurl: 'api/xcoa-mobile/v1/iamtarget/all-list',

      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '审计单位名称',
          dataIndex: 'auditOrgName',
          width: '25%',
        },
        {
          title: '被审计对象名称',
          dataIndex: 'orgName',
          scopedSlots: { customRender: 'fldSubject' },
          width: '25%',
        },
        // {
        //   title: '机构编号',
        //   dataIndex: 'orgId',
        //   width: '10%',
        // },
        {
          title: '国家',
          dataIndex: 'country',
        },
        {
          title: '地区',
          dataIndex: 'region',
        },
        {
          title: '主要负责人',
          dataIndex: 'directorName',
          sdHidden: true,
        },
        // {
        //   title: '被审计单位联系人',
        //   dataIndex: 'contractName',
        // },
        {
          title: '维护人员',
          dataIndex: 'creatorName',
        },
        {
          title: '维护日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          // sorter: true,
          // defaultSortOrder: 'desc',
        },
      ],
      actions: [
        {
          label: '导出',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.$refs.exportBtn.exportdata()
          },
        },
        {
          label: '删除',
          permission: 'delete', // 纯前端操作，不需要权限控制
          id: 'delete',
          type: TableActionTypes.oa.delete,
          // callback: this.deleteRows,
        },
        {
          label: '新建',
          permission: 'create', // 纯前端操作，不需要权限控制
          id: 'create', // 没写type，一般按钮
          callback: () => {
            this.fnCreatDoc()
          },
          type: TableActionTypes.primary,
        },
      ],
      businessTypeId: null,
      typeId: null,
      typeName: '',

      formId: 'iamTarget',
      // 图文列表参数
      showCreateBtn: false,
      showDeleteBtn: false,
      pictureData: [],
      pagination: {
        onChange: (page) => {
          this.paginationChange(page)
        },
        current: 1,
        pageSize: 8,
        showTotal(total) {
          return `共${total}条`
        },
      },
      loading: false, // 图文列表数据的loading
      orderType: 'creationTime',
      creationTimeDesc: true,
      pictureRowSelection: [],
      searchText: '',
      picList: '',
    }
  },
  // 图文列表参数变化更新数据
  watch: {
    orderType() {
      this.pictureListRefresh()
    },
    creationTimeDesc() {
      this.pictureListRefresh()
    },
  },
  created() {},
  methods: {
    searchedClick() {
      this.expand = false
    },
    // 查询
    handleSearch() {
      this.expressions = []

      // 审计单位名称
      if (this.formData.auditOrgName) {
        this.expressions.push({
          dataType: 'str',
          name: 'auditOrgName',
          op: 'like',
          stringValue: `%${this.formData.auditOrgName}%`,
        })
      }
      // 被审计对象名称
      if (this.formData.orgName) {
        this.expressions.push({
          dataType: 'str',
          name: 'orgName',
          op: 'like',
          stringValue: `%${this.formData.orgName}%`,
        })
      }
    },

    // 获取businessTypeId，选中的节点要是没有businessTypeId就向上找，直至找到根节点，如果没有就返回null
    fnGetBusinessTypeId(item) {
      let businessTypeId
      if (item === null) {
        // 如果找到根节点都没找到flowId就返回null
        businessTypeId = null
      } else {
        if (item.selectedNodes && item.selectedNodes[0].data.props.props.businessTypeId) {
          businessTypeId = item.selectedNodes[0].data.props.props.businessTypeId
        } else if (item.props && item.props.businessTypeId) {
          businessTypeId = item.props.businessTypeId
        } else {
          const key = item.id ? item.id : item.selectedNodes[0].data.key
          const parentNode = this.getParentNode(key, this.$refs.tree.treeData)
          businessTypeId = this.fnGetBusinessTypeId(parentNode)
        }
      }
      return businessTypeId
    },

    // 查找父节点
    getParentNode(key, tree) {
      let parentNode = null
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentNode = node
          } else if (this.getParentNode(key, node.children)) {
            parentNode = this.getParentNode(key, node.children)
          }
        }
      }
      return parentNode
    },

    // 知识投稿
    fnCreatDoc() {
      var url = '/iam-source-target-form?'
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          return this.$refs.oaTable.refresh(true)
        }
      })
    },
    fnEditDoc(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
        this.loadData()
      }, 5000)

      var url = `/km-knowledage-form?&typeId=${this.typeId}&typeName=${this.typeName}&record=${record.id}`

      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          return this.$refs.oaTable.refresh(true)
        }
      })
    },
    // 查看知识
    fnReadDoc(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
        this.loadData()
      }, 5000)
      window.open(`#/iam-source-target-form?id=${record.id}&title=${record.orgName}`, '_blank')
    },

    // 图片列表页面翻页
    paginationChange(page) {
      this.pagination.current = page
      this.loadData()
    },

    pictureListRefresh(toFirstPage) {
      if (toFirstPage) this.pagination.current = 1
      if (!this.isSelectd) {
        return this.loadData()
      }
    },
    // 列表删除数据时刷新一下
    onRecordsDeleted() {
      this.$refs.tree.refresh() // 刷新树
    },
    // 列表删除数据
    deleteRows() {
      const selectedRowKeys = this.$refs.oaTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      Modal.confirm({
        title: '你确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          this.loading = true
          const params = {
            ids: selectedRowKeys.join(','),
          }

          PageService.delete(params, this.formId).then((res) => {
            if (res.status === 200) {
              this.$refs.oaTable.clearSelection()
              this.$refs.oaTable.refresh()
              this.loading = false
              message.success('删除成功')
            }
          })
        },
      })
    },

    onSearchChange(text) {
      if (this.searchText === text) return
      this.searchText = text.trim()
      const pagination = this.pagination
      pagination.current = 1
      this.localPagination = { ...pagination }
      this.loadData()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.btns {
  position: absolute;
  top: 24px;
  right: 142px;
  z-index: 100;
}
.buttonSpacing {
  margin-left: 5px;
}
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: 100%;
      height: 100%;
    }
  }
}

.sider-content {
  padding: 0 0;
  .sider-title {
    position: relative;
    margin-left: 23px;
    i {
      position: absolute;
      top: 3px;
      left: -27px;
      font-size: 18px;
      color: #1890ff;
    }

    font-weight: bold;
  }
  .sider-li {
    :global(.ant-timeline-item-content) {
      margin: 0 0 0 23px;
    }
    :global(.ant-timeline-item-head-blue) {
      color: #9f9f9f;
      border-color: #9f9f9f;
    }
    :global(.ant-timeline-item-tail) {
      height: calc(100% - -18px);
      border-left: 2px solid #f5f5f5;
    }
  }
  .sider-title-div-first {
    padding: 0 0 10px 20px;
    margin-bottom: 10px;
    border-bottom: 3px solid #e8e8e8;
  }
  .sider-title-div {
    padding: 10px 0 10px 20px;
    margin-bottom: 20px;
    border-top: 3px solid #e8e8e8;
    border-bottom: 3px solid #e8e8e8;
  }
  ul {
    margin-bottom: 30px;
    margin-left: 0;
  }
  .sider-ul-div {
    width: 90%;
    padding: 13px 0 0 5px;
    margin: 10px auto;
    cursor: pointer;
    border-radius: 5px;
    :global(.ant-timeline-item) {
      padding: 0;
      margin-left: 3px;
    }
  }
  :global(.checked) {
    color: #fff;
    background: linear-gradient(to right, #13c2c2, #2db7f5);
    :global(.ant-timeline-item-head-blue) {
      background-color: #13c2c2;
      border-color: #fff !important;
    }
  }
  :global(.ant-timeline-item-last .ant-timeline-item-tail) {
    display: none;
  }
}
</style>
