<template>
  <div>
    <audit-advanced-query
      :expand="expand"
      :search-data="formData"
      :ref-name="searchform"
      :search-style="{ height: '135px', left: '0px', top: '40px' }"
      :search-fun="handleSearch"
      @searchedClick="searchedClick"
    >
      <template>
        <a-col :span="12">
          <a-form-model-item label="资料清单名称" prop="title">
            <a-input v-model="formData.title" allow-clear />
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item label="被审计单位" prop="auditedUnit">
            <a-input v-model="formData.auditedUnit" allow-clear />
          </a-form-model-item>
        </a-col>
      </template>
    </audit-advanced-query>
    <a-card>
      <sd-data-table-ex
        ref="sjzlTable"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="iamAuditMaterialList"
        :data-url="dataUrl"
        :search-fields="['title']"
        :show-advance-query="true"
        show-selection
        :modal-props="{ class: 'noBottom' }"
        :custom-delete-fun="deleteFun"
        @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 { message, Modal } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import components from './_import-components/iam-audit-material-list-list-import'

export default {
  name: 'IamAuditMaterialListList',
  metaInfo: {
    title: '审前资料清单',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      projectId: this.$root.$route.query.projectId,
      searchform: 'searchform',
      expressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ],
      dataUrl: 'api/xcoa-mobile/v1/iam-material-list/all-list/' + this.$route.query.projectId,
      formData: {
        title: '',
        auditedUnit: '',
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          defaultSortOrder: 'descend',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          sdHidden: true,
        },
        {
          title: '资料清单名称',
          dataIndex: 'title',
          scopedSlots: { customRender: 'islink' },
          width: '30%',
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
        },
        {
          title: '被审计单位联系人',
          dataIndex: 'linkManName',
          width: '200px',
        },
        {
          title: '在线反馈截止时间',
          dataIndex: 'feedbackTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          width: '200px',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
          sorter: true,
          customRender: (text, record, index) => {
            if ((record.flowState === null) | (record.flowState === '')) {
              return '起草中'
            } else {
              return record.flowState
            }
          },
          sortDirections: ['ascend', 'descend'],
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
        {
          title: 'instId',
          dataIndex: 'instId',
          sdHidden: true,
        },
        { title: '文档状态', dataIndex: 'endType', width: '120px', sdHidden: true },
      ],
      actions: [],
      // actions: [
      //   {
      //     label: '删除',
      //     id: 'delete',
      //     permission: null,
      //     type: 'delete',
      //   },
      //   {
      //     label: '新建',
      //     id: 'new',
      //     type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
      //     permission: null, // 权限控制
      //     callback: () => {
      //       const url = '/sd-flow-guide?code=AUDIT_MATERIAL&projectId=' + this.projectId // 新页面要打开的路由地址
      //       crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
      //         if (refreshFlag) {
      //           // 这里写或者调刷新的方法
      //           this.refresh()
      //         }
      //       })
      //     },
      //   },
      // ],
    }
  },
  mounted() {
    this.isShowBtn()
  },
  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 = []
              this.hasOperatePermissions = false
            } else {
              this.actions = [
                {
                  label: '删除',
                  id: 'delete',
                  permission: null,
                  type: 'delete',
                },
                {
                  label: '新建',
                  id: 'new',
                  type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
                  permission: null, // 权限控制
                  callback: () => {
                    const url = '/sd-flow-guide?code=PRODUCT_IAM_SJZL&projectId=' + this.projectId // 新页面要打开的路由地址
                    crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                      if (refreshFlag) {
                        // 这里写或者调刷新的方法
                        this.refresh()
                      }
                    })
                  },
                },
              ]
            }
          }
        }
      })
    },
    deleteFun() {
      const selectedRowKeys = this.$refs.sjzlTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      const selectedRows = this.$refs.sjzlTable.getSelectedRows()
      const currentAccount = getUserInfo().account
      const instIds = []
      let flag = false
      selectedRows.forEach((item) => {
        if (item.endType !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
        return
      }
      var flages = true
      selectedRows.forEach((item) => {
        var instId = item.instId - 0
        if (item.creatorAccount !== currentAccount) {
          Modal.info({
            content: '请选择自己创建的文件',
          })
          flages = false
        } else {
          instIds.push(instId)
        }
      })
      if (!flages) {
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/flow-mobile/v1/process-manager/process-instance/remove',
              method: 'POST',
              data: {
                flowCallbackBeanName: 'formBeanCleanerCallBack',
                processInstanceIds: instIds.join(','),
              },
            })
              .then(() => {
                this.clearSelection()
                this.refresh()
                message.success('删除成功')
                /**
                 * 数据删除成功后触发
                 * @property {Array} rowKeys 已删除的记录ids
                 */
                this.$emit('recordsDeleted', selectedRowKeys)
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    clearSelection() {
      this.$refs.sjzlTable.clearSelection()
    },
    // 刷新列表
    refresh() {
      // this.$refs.sjzlTable.refresh()
      this.$emit('refreshTable')
    },
    // 新建、详情打开新页面
    rowClick(record) {
      let openurl = ''
      const loginUser = getUserInfo()
      if (
        (record.flowState === '起草') |
        (record.flowState === '开始') |
        (record.flowState === null)
      ) {
        if (loginUser.name === record.currentUser) {
          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.refresh()
        }
      })
    },
    // 查询
    handleSearch() {
      this.expressions = [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ]

      // 资料名称
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'title',
          op: 'like',
          stringValue: `%${this.formData.title}%`,
        })
      }

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

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