<template>
  <div :class="$style.mainDiv">
    <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"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'年\u2002\u2002\u2002\u2002度:'">
              <a-date-picker
                v-model="formData.year"
                mode="year"
                format="YYYY"
                :allow-clear="false"
                placeholder="选择年份"
                :input-read-only="true"
                :open="yearShow"
                style-echartclass-open-change="openChange"
                @openChange="openChange"
                @panelChange="panelYearChange"
              ></a-date-picker>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'项目名称'" prop="projectName">
              <a-input v-model="formData.projectName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'档案编号'" prop="archivesCode">
              <a-input v-model="formData.archivesCode" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'案卷状态'" prop="fileState">
              <a-select v-model="formData.fileState" :allow-clear="true">
                <a-select-option :value="'FILING'"> 立卷 </a-select-option>
                <a-select-option :value="'STAY_FILE'"> 待归档 </a-select-option>
                <a-select-option :value="'ALREADY_FILE'"> 已归档 </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table-ex
        ref="archivesDataTable"
        :filter-expressions="expressions"
        :columns="czflag ? columnscz : columns"
        :actions="actions"
        form-id="iamArchivesMaintain"
        data-url="api/xcoa-mobile/v1/iamarchivesmaintain/all-list"
        :search-fields="['projectName', 'archivesCode', 'fileState']"
        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 moment from 'moment'
import { message, Modal } from 'ant-design-vue'
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 AuditArchivesService from './audit-archives-service'
import components from './_import-components/audit-archives-list-import'
import PageService from '@/common/services/page-service'
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 SdIcon from '@/common/components/sd-icon'
import download from '@/common/services/download'

export default {
  name: 'AuditArchivesList',
  metaInfo: {
    title: '档案管理',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      year: '',
      searchYear: '',
      yearShow: false,
      searchform: 'searchform',
      formData: {
        year: '',
      },
      formId: 'iamArchivesMaintain',
      expressions: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          scopedSlots: { customRender: 'islink' },
          width: '35%',
        },
        {
          title: '档案编号',
          dataIndex: 'archivesCode',
          sorter: true,
          defaultSortOrder: 'descend', // 没有点击任何排序列时，默认的排序列
        },
        {
          title: '案卷状态',
          dataIndex: 'fileState',
        },
        {
          title: '档案类型',
          dataIndex: 'archivesType',
        },
        {
          title: '归档时间',
          dataIndex: 'filingDate',
          sorter: true,
          sdRender: TableColumnTypes.dateTime,
        },
      ],
      columnscz: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          scopedSlots: { customRender: 'islink' },
          width: '35%',
        },
        {
          title: '档案编号',
          dataIndex: 'archivesCode',
          sorter: true,
          defaultSortOrder: 'descend', // 没有点击任何排序列时，默认的排序列
        },
        {
          title: '案卷状态',
          dataIndex: 'fileState',
        },
        {
          title: '档案类型',
          dataIndex: 'archivesType',
        },
        {
          title: '归档时间',
          dataIndex: 'filingDate',
          sorter: true,
          sdRender: TableColumnTypes.dateTime,
        },
        {
          title: '操作',
          dataIndex: 'opt',
          sdHidden: false,
          customRender: (text, record, index) => {
            if (record.fileState !== '立卷') {
              if (record.fileState !== '已归档') {
                return (
                  <span>
                    <a-button
                      type='link'
                      size='small'
                      title='归档'
                      vOn:click={(evt) => this.isNotfileBtn(record.id, 'ALREADY_FILE')}
                    >
                      <SdIcon type='sd-audit-archive' theme='fill' />
                    </a-button>
                  </span>
                )
              } else {
                return (
                  <span>
                    <a-button
                      type='link'
                      size='small'
                      title='重新归档'
                      vOn:click={(evt) => this.isNotfileBtn(record.id, 'FILING')}
                    >
                      <SdIcon type='sd-audit-archives-management' theme='fill' />
                    </a-button>
                  </span>
                )
              }
            }
          },
        },
      ],
      //  项目组长/项目副组长——查看自己相关所有的
      actions: [],
      czflag: true,
    }
  },

  mounted() {
    this.setUserType()
  },

  methods: {
    //  档案管理员——查看所有
    setUserType() {
      axios({
        url: 'api/xcoa-mobile/v1/iamarchivesmaintain/findHasPermission',
        method: 'post',
      }).then((res) => {
        if (res.data === true) {
          this.refresh()
          this.actions = [
            {
              label: '删除',
              id: 'delete',
              permission: null,
              type: TableActionTypes.batch,
              callback: this.deleteRows,
            },
            {
              label: '新建',
              id: 'new',
              permission: 'create',
              type: TableActionTypes.primary,
              callback: () => {
                const url = '/audit-archives-form' // 新页面要打开的路由地址
                crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                  if (refreshFlag) {
                    // 这里写或者调刷新的方法
                    this.refresh()
                  }
                })
              },
            },
            {
              label: '导出',
              id: 'export',
              permission: null,
              callback: () => {
                this.exportdata()
              },
            },
          ]
        } else {
          this.czflag = false
        }
      })
    },

    exportdata() {
      const selectedRowKeys = this.$refs.archivesDataTable.getSelectedRowKeys()

      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择导出的数据!',
        })
        return false
      }
      AuditArchivesService.fileExport(selectedRowKeys.join(',')).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
        }
      })
    },
    // 是否归档
    isNotfileBtn(id, value) {
      axios({
        url: `api/xcoa-mobile/v1/iamarchivesmaintain/isNotfileBtn?id=${id}&isNotfile=${value}`,
        method: 'post',
      }).then((res) => {
        if (res.data === true) {
          if (value === 'FILING') {
            message.success('重新归档')
          } else {
            message.success('归档成功')
          }
          this.$refs.archivesDataTable.refresh()
        } else {
          Modal.error({
            title: '修改失败，请联系管理员！',
          })
        }
      })
    },

    // 删除数据
    deleteRows(record) {
      const selecteArchivesType = this.$refs.archivesDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.archivesDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selecteArchivesType.forEach((item) => {
        if (item.archivesType === '系统档案') {
          flag = true
        }
        if (item.fileState !== '立卷') {
          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.archivesDataTable.clearSelection()
                  this.$refs.archivesDataTable.refresh()
                  this.loading = false
                })
              }
            })
          },
        })
      }
    },

    moment,
    panelYearChange(value) {
      this.year = value
      this.formData.year = value
      this.searchYear = moment(value).format('YYYY')
      this.yearShow = false
    },
    // 弹出日历和关闭日历的回调
    openChange(status) {
      // status是打开或关闭的状态
      if (status) {
        this.yearShow = true
      } else {
        this.yearShow = false
      }
    },
    refresh() {
      return this.$refs.archivesDataTable.refresh(true)
    },
    rowClick(record) {
      const url = '/audit-archives-form?record=' + record.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },

    // 查询
    handleSearch() {
      this.expressions = []
      // 年度
      if (this.searchYear) {
        this.expressions.push({
          dataType: 'str',
          name: 'searchYear',
          op: 'like',
          stringValue: `${this.searchYear}`,
        })
      }
      // 项目名称
      if (this.formData.projectName) {
        this.expressions.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `${this.formData.projectName}`,
        })
      }
      // 档案编号
      if (this.formData.archivesCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'archivesCode',
          op: 'like',
          stringValue: `${this.formData.archivesCode}`,
        })
      }
      // 案卷状态
      if (this.formData.fileState) {
        this.expressions.push({
          dataType: 'str',
          name: 'fileState',
          op: 'like',
          stringValue: `${this.formData.fileState}`,
        })
      }
    },
    // 重置年份
    resetForm() {
      this.formData.year = null
      this.searchYear = null
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.main-div {
  :global(.ant-calendar-picker) {
    width: 100%;
  }
}
</style>
