<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{
          height: '140px',
          left: '20px',
          top: '45px !important',
          width: 'calc(100% - 5px) !important',
          margin: 'auto',
        }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'文件标题'" prop="fileTitle">
              <a-input v-model="formData.fileTitle" allow-clear />
            </a-form-model-item>
          </a-col>
          <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>
        </template>
      </audit-advanced-query>

      <sd-data-table-ex
        ref="noticeDataTable"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="iamAuditNotice"
        :data-url="dataurl"
        :search-fields="['fileTitle', 'auditedUnitNames', 'creatorName', 'flowState']"
        show-selection
        :show-advance-query="true"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { Modal, Message } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import PageService from '@/common/services/page-service'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import components from './_import-components/audit-notice-list-import'

export default {
  name: 'AuditNoticeList',
  metaInfo: {
    title: '审计通知书',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      userType: '',
      projectId: this.$root.$route.query.projectId,
      searchform: 'searchform',
      expressions: [
        {
          dataType: 'str',
          name: 'projectId',
          op: 'eq',
          stringValue: this.$root.$route.query.projectId,
        },
      ],
      formData: {},
      formId: 'iamAuditNotice',
      dataurl:
        'api/xcoa-mobile/v1/iamauditnotice/all-list?projectId=' + this.$root.$route.query.projectId,

      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '文件标题',
          dataIndex: 'fileTitle',
          scopedSlots: { customRender: 'islink' },
          width: '35%',
        },
        {
          title: 'instId',
          dataIndex: 'instId',
          sdHidden: true,
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          sorter: true,
          width: '120px',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          defaultSortOrder: 'descend', // 没有点击任何排序列时，默认的排序列
          sorter: true,
          sdRender: TableColumnTypes.date,
          width: '120px',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      actions: [],
    }
  },
  mounted() {
    this.setUserProject()
    // this.isShowBtn()
  },
  created() {},
  methods: {
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },
    // 是否显示按钮 禅道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
          const readAuthorityCodes = res.data.readAuthorityCodes
          const userList = res.data.iamProjectUserList
          var isProjectUser = this.inProjectUser(userList)
          if (['05', '06', '07'].includes(itemStatus)) {
            this.actions = []
          } else {
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
              !isProjectUser
            ) {
              this.actions = []
            } else {
              this.setUserProject()
            }
          }
        }
      })
    },
    // 删除数据
    deleteRows(record) {
      const selecteFlowState = this.$refs.noticeDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.noticeDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selecteFlowState.forEach((item) => {
        if (item.flowState === '结束') {
          flag = true
        }
      })
      if (flag) {
        // 有过错误
        Modal.error({
          title: '删除失败，存在“流程已结束”数据！',
        })
      } else {
        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) {
                Message.success({ content: '删除成功！' }, 1).then(() => {
                  this.$refs.noticeDataTable.clearSelection()
                  this.$refs.noticeDataTable.refresh()
                  this.loading = false
                })
              }
            })
          },
        })
      }
    },

    setUserProject() {
      var projectId = this.$root.$route.query.projectId
      const params = {
        projectId: projectId,
      }
      if (projectId) {
        axios({
          url: 'api/xcoa-mobile/v1/iamprojectuser/findUserProject',
          method: 'get',
          params,
        }).then((res) => {
          //  项目负责人04 【查看】所有《审计通知书》
          let dataxm = res.data.toString()
          if (dataxm.indexOf('0') === -1) {
            dataxm = 0 + dataxm
          }

          axios({
            url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + projectId,
            method: 'get',
          }).then((res) => {
            if (res.data) {
              const itemStatus = res.data.itemStatus

              if (
                (dataxm.indexOf('01') > -1 ||
                  dataxm.indexOf('02') > -1 ||
                  dataxm.indexOf('03') > -1 ||
                  dataxm.indexOf('05') > -1) &&
                !['05', '06', '07'].includes(itemStatus)
              ) {
                this.actions = [
                  {
                    label: '删除',
                    id: 'delete',
                    type: TableActionTypes.batch,
                    permission: null,
                    callback: this.deleteRows,
                  },
                  {
                    label: '新建',
                    id: 'new',
                    type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
                    permission: 'create', // 纯前端操作，不需要权限控制
                    callback: () => {
                      // var url = '/audit-notice-form?record=' + record.id
                      // crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                      //   if (refreshFlag) {
                      //     // 这里写或者调刷新的方法
                      //     this.refresh()
                      //   }
                      // })
                      // // 查询
                      const url =
                        '/sd-flow-guide?code=PRODUCT_IAM_SJTZS&projectId=' + this.projectId // 新页面要打开的路由地址
                      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                        if (refreshFlag) {
                          // 这里写或者调刷新的方法
                          this.refresh()
                        }
                      })
                      //  // window.open(
                      // //   '#/sd-flow-guide?code=PRODUCT_IAM_SJTZS&projectId=' + this.projectId
                      // // )
                    },
                  },
                ]
                this.userType = res.data
              }
            }
          })
        })
      }
    },

    refresh() {
      return this.$refs.noticeDataTable.refresh(true)
    },
    rowClick(record) {
      const userInfo = getUserInfo()
      if (this.userType === '04' || userInfo.name !== record.currentUser) {
        window.open('#/sd-webflow/done-pages/' + record.instId)
      } else {
        if (record.endType === 0 || record.flowState === '开始' || record.flowState === '起草') {
          window.open('#/sd-webflow/pages/draft/' + record.instId)
        } else {
          window.open('#/sd-webflow/done-pages/' + record.instId)
        }
      }
      // const url = '/audit-notice-form?record=' + record.id + '&projectId=' + this.projectId // 新页面要打开的路由地址
      // crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
      //   if (refreshFlag) {
      //     this.refresh()
      //   }
      // })
    },
    // 查询
    handleSearch() {
      // 默认查询条件
      this.expressions = [
        {
          dataType: 'str',
          name: 'projectId',
          op: 'eq',
          stringValue: this.$root.$route.query.projectId,
        },
      ]

      // 文件标题
      if (this.formData.fileTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'fileTitle',
          op: 'like',
          stringValue: `%${this.formData.fileTitle}%`,
        })
      }
      // 被审计单位
      if (this.formData.auditedUnitNames) {
        this.expressions.push({
          dataType: 'str',
          name: 'auditedUnitNames',
          op: 'like',
          stringValue: `%${this.formData.auditedUnitNames}%`,
        })
      }
    },
  },
}
</script>

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