<template>
  <div>
    <a-card>
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="'searchform'"
        :search-fun="handleSearch"
        :search-style="{ height: '130px', left: '0px !important', top: '40px !important' }"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'被审计单位'" prop="auditedUnitNames">
              <a-input v-model="formData.auditedUnitNames" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'编制人员'" prop="creatorName">
              <a-input v-model="formData.creatorName" allow-clear />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table-ex
        ref="dataTable"
        :key="dataTableKey"
        :v-if="showData"
        :form-id="formId"
        page-id="audit/auditsource/work/scheme/iamAuditScheme"
        :columns="columns"
        :actions="actions"
        :custom-delete-fun="linkToDelete"
        show-selection
        :show-advance-query="true"
        :search-fields="['fileTitle']"
        :filter-expressions="expressions"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a :title="text" @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import { Modal, message } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'
import AuditProjectuserService from '@product/iam/audit/work/projectuser/audit-projectuser-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import auditAdvancedQuery from '../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import auditService from './iam-audit-scheme-service'
import components from './_import-components/iam-audit-scheme-list-import'
const columns = [
  {
    title: '序号',
    width: '70px',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  {
    dataIndex: 'instId',
    sdHidden: true,
  },
  {
    dataIndex: 'projectId',
    sdHidden: true,
  },
  {
    dataIndex: 'endType',
    sdHidden: true,
  },
  {
    title: '文件标题',
    dataIndex: 'fileTitle',
    // sdClickable: true, // 列内容是否可点击
    scopedSlots: { customRender: 'islink' },
  },
  {
    title: '被审计单位',
    dataIndex: 'auditedUnitNames',
    sorter: true,
    width: '150px',
  },
  {
    title: '编制人员',
    dataIndex: 'creatorName',
    width: '120px',
    sorter: true,
  },
  {
    title: '编制日期',
    dataIndex: 'creationTime',
    sdRender: TableColumnTypes.date,
    sorter: true,
    defaultSortOrder: 'desc',
    width: '120px',
  },
  {
    title: '当前状态',
    dataIndex: 'flowState',
    width: '150px',
  },
  {
    title: '当前处理人',
    dataIndex: 'nowUser',
    width: '150px',
  },
]
export default {
  name: 'IamAuditSchemeList',
  metaInfo: {
    title: '审计方案',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      expand: false,
      showData: false,
      dataTableKey: 0,
      formId: 'iamAuditScheme',
      tableId: 'dataTable',
      columns,
      projectId: this.$root.$route.query.projectId,
      formData: {},
      basicExpression: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ],
      actions: [],
    }
  },
  created() {
    this.addExpression()
  },
  mounted() {
    const projectId = this.$route.query.projectId
    if (projectId) {
      this.projectId = projectId
    }
    let flag = true
    let actions = []
    auditService.getUserRoles(this.projectId).then((res) => {
      res.data.forEach((item) => {
        if (item === '01' || item === '05') {
          if (flag) {
            // 增加删除
            actions.push({
              label: '删除',
              id: 'delete',
              type: 'delete',
              permission: null,
              // callback: this.delete,
            })
            actions.push({
              label: '新建',
              id: 'create',
              permission: null,
              type: TableActionTypes.primary,
              callback: () => {
                const url = '/sd-flow-guide?code=PRODUCT_IAM_SJFA&projectId=' + this.projectId // 新页面要打开的路由地址
                // window.open(url)
                crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                  if (refreshFlag) {
                    this.refreshDataTable()
                  }
                })
              },
            })
            flag = false
          }
        }
      })
      let justFinish = false
      if (res.data.length !== 0) {
        justFinish = res.data.every((item) => {
          return item === '02' || item === '03'
        })
      }
      if (justFinish) {
        this.basicExpression.push({
          dataType: 'long',
          name: 'endType',
          op: 'eq',
          longValue: 5,
        })
      }
      const projectId = this.$root.$route.query.projectId
      axios({
        url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + projectId,
        method: 'get',
      }).then((res) => {
        if (res.data) {
          const itemStatus = res.data.itemStatus
          if (['05', '06', '07'].includes(itemStatus)) {
            actions = []
          }
          this.actions = actions
        }
      })
      this.expressions = this.basicExpression

      this.showData = true
      this.dataTableKey++
    })
    // this.isShowBtn()
  },
  methods: {
    // 是否显示按钮 禅道bug21826需要，关闭项目后各阶段都不能再新建（包括其他操作按钮）
    isShowBtn() {
      const projectId = this.$root.$route.query.projectId
      axios({
        url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + projectId,
        method: 'get',
      }).then((res) => {
        if (res.data) {
          const itemStatus = res.data.itemStatus
          if (['05', '06', '07'].includes(itemStatus)) {
            this.actions = []
          }
        }
      })
    },
    // 重置年份
    resetForm() {
      // this.formData = {}
    },
    handleSearch() {
      // 默认查询条件
      this.expressions = []

      this.addExpression()

      this.basicExpression.forEach((item) => {
        this.expressions.push(item)
      })
      // this.expressions = this.basicExpression

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

      // 编制人
      if (this.formData.creatorName) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.creatorName}%`,
        })
      }
    },
    // 项目负责人,项目组长/项目副组长【查看】所有《离场会》;项目主审/项目组员【查看】所有“已结束”《离场会》
    addExpression() {
      this.basicExpression.push({
        dataType: 'long',
        name: 'projectId',
        op: 'eq',
        longValue: parseInt(this.projectId),
      })
      AuditProjectuserService.isProjectLeader(parseInt(this.projectId), 'all').then((res) => {
        if (res && res.data === false) {
          this.basicExpression.push({
            dataType: 'str',
            name: 'flowState',
            op: 'like',
            stringValue: `%结束%`,
          })
        }
      })
    },
    searchedClick() {
      this.expand = !this.expand
    },
    refreshDataTable() {
      this.$refs.dataTable.clearSelection()
      this.$refs.dataTable.refresh()
    },
    rowClick(record) {
      let openurl = ''
      const loginUser = getUserInfo()
      if (
        (record.flowState === '起草') |
        (record.flowState === '开始') |
        (record.flowState === null)
      ) {
        if (loginUser.name === record.creatorName) {
          openurl = '/sd-webflow/pages/draft/' + record.instId
        } else {
          openurl = '/sd-webflow/done-pages/' + record.instId
        }
      } else {
        openurl = '/sd-webflow/done-pages/' + record.instId
      }
      crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
        // if (refreshFlag) {
        // 这里写或者调刷新的方法
        this.refreshDataTable()
        // }
      })
    },
    linkToDelete() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          axios({
            url: 'api/xcoa-mobile/v1/page/' + this.formId,
            method: 'delete',
            params: {
              ids: selectedRowKeys.join(','),
            },
          })
            .then(() => {
              const msg = '删除成功'
              message.success(msg)
              this.$refs[`${this.tableId}`].clearSelection()
              this.$refs[`${this.tableId}`].refresh()
            })
            .catch((err) => {
              const msg = errorUtil.getMessage(err) || '删除失败'
              message.error(msg)
            })
        },
        onCancel: () => {},
      })
    },
  },
}
</script>

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