<template>
  <span>
    <a-card>
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="'searchform'"
        :search-style="{
          height: '250px',
          left: '0px',
          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="findTitle">
              <a-input v-model="formData.findTitle" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'审计发现编号'" prop="findCode">
              <a-input v-model="formData.findCode" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'审计发现描述'" prop="findDesc">
              <a-input v-model="formData.findDesc" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审计建议类型" prop="suggestionType">
              <!-- <sd-select
              v-model="formData.suggestionType"
              :options="dictionary.suggestionTypeOptions"
            /> -->
              <a-select v-model="formData.suggestionType" :allow-clear="true" :default-value="''">
                <a-select-option
                  v-for="item in dictionary.suggestionTypeOptions"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'问题责任部门'" prop="responsibleDept">
              <a-input v-model="formData.responsibleDept" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" class="recitifyrectstatus">
            <a-form-model-item :label="'确认状态'" prop="confirmsStatus">
              <!-- <a-select
              v-model="formData.confirmsStatus"
              :initial-values="[]"
              :default-value="[]"
              :options="dictionary.confirmsStatus"
            /> -->
              <a-select v-model="formData.confirmsStatus" :allow-clear="true" :default-value="''">
                <a-select-option
                  v-for="item in dictionary.confirmsStatus"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" class="recitifyrectstatus">
            <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
        :key="dataTableCount"
        ref="dataTable"
        :filter-expressions="expressions"
        form-id="iamAuditDiscover"
        page-id="audit/work/factConfirm/iamAuditDiscover"
        :data-url="dataUrl"
        :projectlist="true"
        :columns="columns"
        :actions="actions"
        show-selection
        :search-fields="['findTitle']"
        :show-advance-query="true"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="isLink" slot-scope="text, record">
          <a class="part-time">
            <span>
              <a-spin v-if="pending.includes(record.id)">
                <a-icon slot="indicator" type="loading" :class="$style.submitStatus" />
              </a-spin>
              <a-tooltip
                v-if="batchSubmitSucceed.map((item) => parseInt(item.id)).includes(record.id)"
                :title="batchSubmitSucceed.find((item) => item.id === record.id + '').message"
              >
                <a-icon type="check-circle" :class="[$style.submitStatus, $style.success]" />
              </a-tooltip>
              <a-tooltip
                v-if="batchsubmitFailed.map((item) => parseInt(item.id)).includes(record.id)"
                :title="batchsubmitFailed.find((item) => item.id === record.id + '').message"
              >
                <a-icon type="close-circle" :class="[$style.submitStatus, $style.error]" />
              </a-tooltip>
            </span>
          </a>
          <a :title="text" @click="showAccountDetail(record)">{{ text }}</a>
        </div>
        <div slot="opt" slot-scope="text, record">
          <a-button type="link" size="small" @click="openGzdg(record)">查看工作底稿 </a-button>
        </div>
        <template slot="attachment" slot-scope="text, record">
          <template v-if="(text !== '') & (text !== null)">
            <sd-attachment :key="record.id" :group-id="text" read-only />
          </template>
        </template>
        <template slot="findType" slot-scope="text, record">
          {{ JSON.parse(text).text }}
        </template>
      </sd-data-table-ex>
    </a-card>
  </span>
</template>

<script>
import download from '@/common/services/download'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableActionTypes from '@/common/services/table-action-types'
import { Modal } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import auditService from './audit-factconfirm-service'
import components from './_import-components/audit-factconfirm-list-import'

export default {
  name: 'AuditFactconfirmList',
  metaInfo: {
    title: '事实确认',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      projectId: this.$root.$route.query.projectId,
      dataTableCount: 0,
      dataUrl: 'api/xcoa-mobile/v1/audit-fact-confirm/list',
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '审计发现标题',
          dataIndex: 'findTitle',
          scopedSlots: { customRender: 'isLink' },
          width: '150px',
        },
        {
          title: '审计发现编号',
          dataIndex: 'findCode',
          sorter: true,
          width: '120px',
        },
        {
          title: '审计发现类别',
          dataIndex: 'findType',
          scopedSlots: {
            customRender: 'findType',
          },
          width: '150px',
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
          width: '120px',
        },
        {
          title: '审计建议类型',
          dataIndex: 'suggestionType',
          width: '150px',
        },
        {
          title: '确认状态',
          dataIndex: 'confirmsStatus',
          sorter: true,
          width: '120px',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          sorter: true,
          width: '120px',
        },
        {
          title: '问题类型',
          dataIndex: 'problemType',
          width: '120px',
        },
        {
          title: '附件',
          dataIndex: 'attachment',
          dataType: 'attachment',
          scopedSlots: {
            customRender: 'attachment',
          },
          width: '120px',
        },
        {
          title: '操作',
          width: '150px',
          scopedSlots: { customRender: 'opt' },
        },
      ],
      actions: [],
      // actions: [
      //   {
      //     label: '确认',
      //     id: 'confirm',
      //     permission: null,
      //     // type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
      //     type: TableActionTypes.batch,
      //     callback: (keys, records) => {
      //       this.confirmFact(keys, records)
      //     },
      //   },
      //   {
      //     label: '导出',
      //     id: 'export',
      //     permission: null,

      //     callback: () => {
      //       this.exportdata()
      //     },
      //   },
      // ],
      expressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ],
      formData: {},
      dictionary: {
        suggestionTypeOptions: [],
        confirmsStatus: [],
      },
      pending: [], // batch操作中的数据信息
      batchSubmitSucceed: [], // batch操作后成功数据信息
      batchsubmitFailed: [], // batch操作后失败数据信息
    }
  },
  mounted() {
    auditService.getDictionary('ADVICE_TYPE').then((res) => {
      this.dictionary.suggestionTypeOptions = res.data
    })
    auditService.getDictionary('CONFIRMS_STATUS').then((res) => {
      this.dictionary.confirmsStatus = res.data
    })
    this.isShowBtn()
  },
  methods: {
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },

    // 事实确认按钮展示条件梳理：1、确认 导出 所有对所有角色展示
    // 2、项目组长和项目副组长可以确认所有的，其他人只能确定自己的
    // 3、项目结束后按钮不可操作
    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)
          axios({
            url: 'api/xcoa-mobile/v1/iamprojectuser/userProject?projectId=' + projectId,
            method: 'get',
          }).then((res) => {
            const datas = res.data
            if (['05', '06', '07'].includes(itemStatus)) {
              this.actions = []
            } else {
              if (
                readAuthorityCodes != null &&
                readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
                !isProjectUser
              ) {
                this.actions = []
              } else {
                // 控制actions
                // 如果只有一个项目组长的身份，那么啥按钮都没有
                // if (datas.length === 1 && datas.includes('05')) {
                //   this.actions = []
                // } else {
                this.actions = [
                  {
                    label: '确认',
                    id: 'confirm',
                    permission: null,
                    // type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
                    type: TableActionTypes.batch,
                    callback: (keys, records) => {
                      this.confirmFact(keys, records)
                    },
                  },
                  {
                    label: '导出',
                    id: 'export',
                    permission: null,
                    callback: () => {
                      this.exportdata()
                    },
                  },
                ]
                // }
              }
            }
          })
        }
      })
    },
    confirmFact(keys, records) {
      this.pending = keys
      auditService.confirmFact(this.projectId, keys).then((res) => {
        res.data.forEach((item) => {
          if (item.code === '0') {
            this.batchSubmitSucceed.push({ id: parseInt(item.id, 10), ...item })
          } else {
            this.batchsubmitFailed.push({ id: parseInt(item.id, 10), ...item })
          }
        })
        this.pending = []
        this.$refs.dataTable.refresh()
      })
    },
    openGzdg(record) {
      auditService.getGzdgInstId(record.paperId).then((res) => {
        const openurl = '/sd-webflow/done-pages/' + res.data
        crossWindowWatcher.waitForChanged(openurl)
      })
    },
    handleSearch() {
      // 默认查询条件
      this.expressions = [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ]

      // 审计发现标题
      if (this.formData.findTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'findTitle',
          op: 'like',
          stringValue: `%${this.formData.findTitle}%`,
        })
      }

      // 审计发现编号
      if (this.formData.findCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'findCode',
          op: 'like',
          stringValue: `%${this.formData.findCode}%`,
        })
      }

      // 审计发现描述
      if (this.formData.findDesc) {
        this.expressions.push({
          dataType: 'str',
          name: 'findDesc',
          op: 'like',
          stringValue: `%${this.formData.findDesc}%`,
        })
      }

      // 审计建议类型
      if (this.formData.suggestionType && this.formData.suggestionType.length) {
        this.expressions.push({
          dataType: 'str',
          name: 'suggestionType',
          op: 'eq',
          stringValue: `${this.formData.suggestionType}`,
        })
      }

      if (this.formData.responsibleDept) {
        this.expressions.push({
          dataType: 'str',
          name: 'responsibleDept',
          op: 'like',
          stringValue: `%${this.formData.responsibleDept}%`,
        })
      }

      if (this.formData.confirmsStatus && this.formData.confirmsStatus.length) {
        this.expressions.push({
          dataType: 'str',
          name: 'confirmsStatus',
          op: 'eq',
          stringValue: `${this.formData.confirmsStatus}`,
        })
      }

      if (this.formData.creatorName) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.creatorName}%`,
        })
      }
    },
    refreshDataTable(refreshFlag) {
      // this.$refs.dataTable.clearSelection()
      this.dataTableCount++
      setTimeout(() => {
        return this.$refs.dataTable.refresh(refreshFlag)
      }, 500)
    },
    showAccountDetail(record) {
      const url =
        '/iam-operate-factconfirm-form?record=' + record.id + '&projectId=' + this.projectId // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        debugger
        if (refreshFlag) {
          this.refreshDataTable(refreshFlag)
        }
      })
    },
    exportdata() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()
      var exportType = 'single'
      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择导出的数据!',
        })
        return false
      }
      if (selectedRowKeys.length > 1) {
        exportType = 'multi'
      }
      auditService.wordExport(selectedRowKeys.join(','), this.projectId, exportType).then((res) => {
        if (res.status === 200) {
          const url = URL.createObjectURL(res.data)
          const filename = res.headers['content-disposition']
          const fname = filename.substring(filename.indexOf('fileName=') + 9, filename.length)
          download(url, decodeURI(fname))
        } else {
          Modal.warning({
            title: '提示',
            content: '导出报错，请联系管理员!',
          })
          return false
        }
      })
    },
    // 标题格式化
    formatterTitle(val, length) {
      var resultArry = []
      let title = ''
      let result = ''
      if (val === undefined || val === '' || val === '[]') {
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      } else {
        try {
          JSON.parse(val).forEach((e) => {
            result += e.name + ','
          })
        } catch (e) {
          result = val
        }
        if (result.lastIndexOf(',') > 0) {
          result = result.substr(0, result.length - 1)
        }
        title = result
        if (result.length > length) {
          result = result.substr(0, length) + '...'
        }
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      }
    },
  },
}
</script>

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

.success {
  color: $alert-success-icon-color;
}

.error {
  color: $alert-error-icon-color;
}
:global(.recitifyrectstatus) {
  :global(.ant-form-item-label) {
    margin-left: 2em;
  }
}
</style>
