<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '170px', left: '20px', top: '57px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'模板名称'" prop="templateName">
              <a-input v-model="formData.templateName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'模板类型'" prop="templateType">
              <a-select v-model="formData.templateType" :allow-clear="true">
                <a-select-option :value="1">
                  资料清单
                </a-select-option>
                <a-select-option :value="2">
                  审计方案
                </a-select-option>
                <a-select-option :value="3">
                  审计通知书
                </a-select-option>
                <a-select-option :value="6">
                  审计报告
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'是否默认'" prop="isDefault">
              <a-select v-model="formData.isDefault" :allow-clear="true">
                <a-select-option :value="0">
                  否
                </a-select-option>
                <a-select-option :value="1">
                  是
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>

      <sd-data-table-ex
        ref="SJMBKDataTable"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="iamTemplate"
        data-url="api/xcoa-mobile/v1/iamtemplate/all-list"
        :search-fields="['templateName', 'templateType', 'isDefault']"
        show-selection
        :show-advance-query="true"
        @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 moment from 'moment'
import axios from '@/common/services/axios-instance'
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 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-template-list-import'

export default {
  name: 'AuditTemplateList',
  metaInfo: {
    title: '审计模板库',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      searchform: 'searchform',
      expressions: [],
      formData: {
        templateName: '',
        templateType: null,
        isDefault: null,
      },
      formId: 'iamTemplate',
      // nodePerms: {},
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '模板名称',
          dataIndex: 'templateName',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '模板类型',
          dataIndex: 'templateType',
        },
        {
          title: '是否默认',
          dataIndex: 'isDefault',
        },
        {
          title: '适用机构范围',
          dataIndex: 'orgNameScope',
        },
        {
          title: '编制日期',
          dataIndex: 'authTime',
          sdRender: TableColumnTypes.date,
          sdHidden: true,
          sorter: true,
          defaultSortOrder: 'desc',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: 'create',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          callback: () => {
            const url = '/audit-template-form' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
        },
        {
          label: '批量导出附件',
          id: 'exportdataFiles',
          permission: null, // 纯前端操作，不需要权限控制
          callback: this.exportTemplateFiles,
        },
      ],
    }
  },
  computed: {},
  created() {},
  methods: {
    refresh() {
      return this.$refs.SJMBKDataTable.refresh(true)
    },
    rowClick(record) {
      const url = '/audit-template-form?record=' + record.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 导出审计模板附件
    exportTemplateFiles() {
      const selectedRowKeys = this.$refs.SJMBKDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择要一键导出附件的模板（最多可选择10条）',
        })
      } else {
        const timestamp = new Date().getTime()
        console.log(timestamp)
        axios({
          method: 'get',
          url: 'api/xcoa-mobile/v1/spic-common/exportTemplateFiles/' + selectedRowKeys,
          responseType: 'blob',
        }).then((res) => {
          if (res.data) {
            let blob = null
            let fileName = res.headers['content-disposition']?.split('fileName=')[1]
            if (fileName === null || fileName === undefined) {
              fileName = '.zip'
            }
            blob = new Blob([res.data], { type: 'application/zip' })
            const time = moment(moment()).format('yyyyMMDD')
            fileName = '审计模板-' + time + '.zip'
            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()
            }
            message.success('导出成功')
          } else {
            message.error('导出失败，请联系系统管理员')
          }
        })
      }
    },
    // 查询
    handleSearch() {
      this.expressions = []
      // 模板名称
      if (this.formData.templateName) {
        this.expressions.push({
          dataType: 'str',
          name: 'templateName',
          op: 'like',
          stringValue: `%${this.formData.templateName}%`,
        })
      }

      // 模板类型
      if (this.formData.templateType) {
        this.expressions.push({
          dataType: 'str',
          name: 'templateType',
          op: 'like',
          stringValue: `%${this.formData.templateType}%`,
        })
      }

      // 是否默认
      if (this.formData.isDefault != null) {
        this.expressions.push({
          dataType: 'str',
          name: 'isDefault',
          op: 'like',
          stringValue: `%${this.formData.isDefault}%`,
        })
      }
    },
  },
}
</script>

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