<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{
          height: '130px',
          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="itemTitle">
              <a-input v-model="formData.itemTitle" 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>
      <!-- <div :class="[$style.btns]">
        <audit-advanced-export
          ref="export"
          :class-style="[$style.buttonSpacing]"
          :exclebxh="false"
          table-id="evidenceDataTable"
          :config-id="61"
          :v-if="false"
        />
      </div> -->
      <sd-data-table-ex
        ref="evidenceDataTable"
        :filter-expressions="expressions"
        form-id="iamAuditEvidenceSheet"
        :data-url="dataurl"
        :columns="columns"
        :actions="actions"
        show-selection
        :search-fields="['itemTitle', 'itemCode', 'auditedUnitNames', 'creatorName', 'docStatus']"
        :show-advance-query="true"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>

      <div :class="[$style.btns]">
        <audit-advanced-import
          ref="import"
          :config-id="'91'"
          :table-id="'evidenceDataTable'"
          :title="'导入取证单'"
          :message="'注：上传文件为zip格式的压缩包'"
          :class-style="[$style.buttonSpacing]"
          :v-if="false"
          :import-fun="importFun"
        >
          <template v-slot:beforeimport="{ scope }">
            <a-form-item required>
              <div>
                <span class="ant-form-item-required">被审计单位：</span>
                <sd-group-picker v-model="auditedUnitMember" :single="true" style="width: 60%" />
              </div>
            </a-form-item>
          </template>
        </audit-advanced-import>
      </div>
    </a-card>
  </div>
</template>

<script>
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 PageService from '@/common/services/page-service'
import { Modal, message } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import errorUtil from '@/common/services/error-util'
import moment from 'moment'
import auditAdvancedImport from '../../components/audit-advanced-import.vue'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import components from './_import-components/audit-evidence-list-import'

export default {
  name: 'AuditEvidenceList',
  metaInfo: {
    title: '审计取证表',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    auditAdvancedImport,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      projectId: this.$root.$route.query.projectId,
      searchform: 'searchform',
      expressions: [
        {
          dataType: 'str',
          name: 'projectId',
          op: 'eq',
          stringValue: this.$root.$route.query.projectId,
        },
      ],
      formData: {
        itemTitle: '',
        creatorName: '',
      },
      formId: 'iamAuditEvidenceSheet',
      tableId: 'evidenceDataTable',
      dataurl:
        'api/xcoa-mobile/v1/iamauditevidencesheet/all-list?projectId=' +
        this.$root.$route.query.projectId,
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '审计事项',
          dataIndex: 'itemTitle',
          scopedSlots: { customRender: 'islink' },
          width: '35%',
        },
        {
          title: '取证单编号',
          dataIndex: 'itemCode',
          defaultSortOrder: 'descend', // 没有点击任何排序列时，默认的排序列
          sorter: true,
          width: '15%',
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
          width: '15%',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '文档状态',
          dataIndex: 'docStatus',
          sorter: true,
        },
      ],
      actions: [],
      auditedUnitMember: [], // 导入部门选择器
    }
  },
  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.push({
              label: '导出',
              id: 'export',
              permission: null,
              callback: () => {
                this.exportWord()
              },
            })
          } else {
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
              !isProjectUser
            ) {
              this.actions = []
            } else {
              this.actions = [
                {
                  label: '新建',
                  id: 'new',
                  permission: 'create',
                  type: TableActionTypes.primary,
                  callback: () => {
                    const url =
                      '/audit-evidence-from?projectId=' + this.$root.$route.query.projectId // 新页面要打开的路由地址
                    crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                      if (refreshFlag) {
                        // 这里写或者调刷新的方法
                        this.refresh()
                      }
                    })
                  },
                },
                {
                  label: '导出',
                  id: 'export',
                  permission: null,
                  callback: () => {
                    this.exportWord()
                  },
                },
                {
                  label: '导入',
                  permission: null,
                  id: 'import',
                  // type: TableActionTypes.primary,
                  callback: () => {
                    this.$refs.import.showImportPanel()
                    this.flush()
                  },
                },
                {
                  label: '发布',
                  id: 'publish',
                  permission: null, // 纯前端操作，不需要权限控制
                  callback: this.publishRows,
                },
                {
                  label: '删除',
                  id: 'delete',
                  permission: null,
                  type: TableActionTypes.batch,
                  callback: this.deleteRows,
                },
              ]
            }
          }
        }
      })
    },
    // 导出word或zip
    exportWord() {
      // 允许多选
      const selectedRowKeys = this.$refs.evidenceDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择需要导出的审计取证单!',
        })
      } else {
        axios({
          url: 'api/xcoa-mobile/v1/iamauditevidencesheet/exportWord/141/' + selectedRowKeys,
          method: 'get',
          responseType: 'blob',
        }).then((res) => {
          // const blob = new Blob([res.data], { type: 'application/msword' })
          // const blobUrl = window.URL.createObjectURL(blob)
          let blob = null
          let fileName = res.headers['content-disposition']?.split('fileName=')[1]
          if(fileName === null || fileName === undefined){
            fileName = '.zip'
          }
          if (fileName.indexOf('.zip') !== -1) {
            blob = new Blob([res.data], { type: 'application/zip' })
            const time = moment(moment()).format('yyyy-MM-DD')
            fileName = '审计取证单_' + time + '.zip'
          } else {
            blob = new Blob([res.data], { type: 'application/msword' })
            fileName = this.$refs.evidenceDataTable.getSelectedRows()[0].itemTitle + '.docx'
          }

          if ('msSaveOrOpenBlob' in navigator) {
            // 适配ie
            window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
            // 其他浏览器
            const blobUrl = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = blobUrl
            a.setAttribute('download', fileName)
            a.click()
          }
        })
      }
    },
    importFun(val) {
      if (!(this.auditedUnitMember && this.auditedUnitMember.length > 0)) {
        Modal.error({
          content: '请选择被审计单位',
        })
        throw SyntaxError()
      }
      // val是导入方法的入参
      val.auditedUnitIds = this.auditedUnitMember[0].code
      val.auditedUnitNames = this.auditedUnitMember[0].name
      val.projectId = this.$root.$route.query.projectId
      return val
    },
    flush() {
      return this.$refs.evidenceDataTable.refresh(true)
    },
    // 删除数据
    deleteRows(record) {
      const userInfo = getUserInfo()
      const selectedDocStatus = this.$refs.evidenceDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.evidenceDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      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) => {
          // 项目组长05/项目副组长01【删除】所有《取证单》
          let dataxm = res.data.toString()
          if (dataxm.indexOf('0') === -1) {
            dataxm = 0 + dataxm
          }
          if (dataxm.indexOf('01') > -1 || dataxm.indexOf('05') > -1) {
            this.flagdelete()
          } else {
            selectedDocStatus.forEach((item) => {
              if (item.creatorName !== userInfo.name) {
                Modal.error({
                  title: '删除失败，不可删除他人创建的流程！',
                })
              } else {
                this.flagdelete()
              }
            })
          }
        })
      }
    },
    flagdelete() {
      const selectedRowKeys = this.$refs.evidenceDataTable.getSelectedRowKeys()
      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.evidenceDataTable.clearSelection()
                this.$refs.evidenceDataTable.refresh()
                this.loading = false
              })
            }
          })
        },
      })
    },
    publishRows() {
      const selectedDocStatus = this.$refs.evidenceDataTable.getSelectedRows()

      const selectedRowKeys = this.$refs.evidenceDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要发布的文件',
        })
        return
      }
      let flag = true
      selectedDocStatus.forEach((item) => {
        if (item.docStatus === '已结束') {
          flag = false
        }
      })
      
      if(!flag){
          Modal.error({
            title: '发布失败，存在“已结束”数据！',
          })
        } else {
          return new Promise((resolve) => {
            Modal.confirm({
              title: '您确定发布这项内容吗？',
              content: '发布这条数据后，就无法恢复初始的状态。',
              okText: '发布',
              okType: 'danger',
              onOk: () => {
                axios({
                  url: 'api/xcoa-mobile/v1/iamauditevidencesheet/evidencePublish',
                  method: 'get',
                  params: {
                    ids: selectedRowKeys.join(','),
                  },
                })
                  .then(() => {
                    message.success('发布成功')
                    this.$refs.evidenceDataTable.clearSelection()
                    this.$refs.evidenceDataTable.refresh()
                  })
                  .catch((err) => {
                    const msg = errorUtil.getMessage(err) || '发布失败'
                    message.error(msg)
                  })
                  .finally(resolve())
              },
              onCancel: () => {
                resolve()
              },
            })
          })
        }
      // })
    },

    refresh() {
      return this.$refs.evidenceDataTable.refresh(true)
    },
    rowClick(record) {
      const url = '/audit-evidence-from?record=' + record.id // 新页面要打开的路由地址
      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.itemTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'itemTitle',
          op: 'like',
          stringValue: `%${this.formData.itemTitle}%`,
        })
      }
      // 编制人员
      if (this.formData.creatorName) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.creatorName}%`,
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.btns {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 100;
}

.buttonSpacing {
  margin-left: 5px;
}
</style>
