<template>
  <div :class="$style.mainDiv">
    <a-card>
      <a-tabs v-model="activeKey" type="line">
        <a-tab-pane key="1" tab="借阅申请">
          <div style="margin-top: 80px">
            <!-- 高级搜索组件 -->
            <audit-advanced-query
              :expand="expand"
              :search-data="formData"
              :ref-name="searchform"
              :search-style="{ height: '150px', left: '20px', top: '125px !important' }"
              :search-fun="handleSearch"
              @searchedClick="searchedClick"
            >
              <template>
                <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>
                <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>
              </template>
            </audit-advanced-query>
            <a-radio-group
              v-model="radioValue"
              allow-clear
              style="position: absolute"
              @change="radioOnChange"
            >
              <a-radio :value="1"> 全部 </a-radio>
              <a-radio :value="2"> 待处理 </a-radio>
            </a-radio-group>
            <sd-data-table-ex
              ref="borrowDataTable"
              :filter-expressions="expressions1"
              :columns="columns1"
              :actions="actions1"
              form-id="iamArchivesBorrow"
              :data-url="dataurl1"
              show-selection
              :search-fields="['creatorName', 'projectCode', 'projectName', 'flowState']"
              :show-advance-query="true"
              @searchbtnClick="searchbtnClick"
            >
              <div slot="islink" slot-scope="text, record">
                <a :title="text" @click="rowClick1(record)">{{ text }}</a>
              </div>
              <div
                slot="borrowTerm"
                slot-scope="text, record"
                :title="format(record.creationTime) + '至' + format(text)"
              >
                {{ format(record.creationTime) }}至{{ format(text) }}
              </div>
            </sd-data-table-ex>
          </div>
        </a-tab-pane>
        <a-tab-pane v-if="datashow" key="2" tab="档案列表">
          <div style="margin-top: 80px">
            <!-- 高级搜索组件 -->
            <audit-advanced-query
              :expand="expand"
              :search-data="formData"
              :ref-name="searchform"
              :search-style="{ height: '170px', left: '20px', top: '125px !important' }"
              :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>
              </template>
            </audit-advanced-query>
            <sd-data-table-ex
              ref="archivesDataTable"
              :filter-expressions="expressions2"
              :columns="columns2"
              :actions="actions2"
              form-id="iamArchivesMaintain"
              :data-url="dataurl2"
              show-selection
              :search-fields="['projectCode', 'projectName']"
              :show-advance-query="true"
              @searchbtnClick="searchbtnClick"
            >
              <div slot="islink" slot-scope="text, record">
                <a :title="text" @click="rowClick2(record)">{{ text }}</a>
              </div>
            </sd-data-table-ex>
          </div>
        </a-tab-pane>
      </a-tabs>
    </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 components from './_import-components/audit-borrow-list-import'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import PageService from '@/common/services/page-service'

export default {
  name: 'AuditBorrowList',
  metaInfo: {
    title: '档案借阅表',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      datashow: true,
      activeKey: '1',
      radioValue: 1,
      year: '',
      searchYear: '',
      yearShow: false,
      searchform: 'searchform',
      dataurl1: 'api/xcoa-mobile/v1/iamarchivesborrow/all-list',
      dataurl2: 'api/xcoa-mobile/v1/iamarchivesmaintain/record_list',
      expressions1: [],
      expressions2: [],
      formData: {},
      columns1: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: 'instId',
          dataIndex: 'instId',
          sdHidden: true,
        },
        {
          title: 'dossierId',
          dataIndex: 'dossierId',
          sdHidden: true,
        },
        {
          title: '申请人',
          dataIndex: 'creatorName',
        },
        {
          title: '申请日期',
          dataIndex: 'creationTime',
          defaultSortOrder: 'descend', // 没有点击任何排序列时，默认的排序列
          sorter: true,
          sdRender: TableColumnTypes.dateTime,
        },
        {
          title: '所属项目编号',
          dataIndex: 'projectCode',
          width: '200px',
        },
        {
          title: '所属项目名称',
          dataIndex: 'projectName',
          scopedSlots: { customRender: 'islink' },
          width: '25%',
        },
        {
          title: '借阅期限',
          dataIndex: 'borrowTerm',
          scopedSlots: { customRender: 'borrowTerm' },
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      columns2: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },

        {
          title: '项目名称',
          dataIndex: 'projectName',
          scopedSlots: { customRender: 'islink' },
          width: '25%',
        },
        {
          title: '项目编号',
          dataIndex: 'archivesCode',
        },
        {
          title: '案件状态',
          dataIndex: 'fileState',
          width: '120px',
        },
        {
          title: '归档时间',
          dataIndex: 'filingDate',
          sorter: true,
          sdRender: TableColumnTypes.dateTime,
        },
      ],
      actions1: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: this.deleteRows,
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: 'create', // 纯前端操作，不需要权限控制
          callback: () => {
            const url = '/sd-flow-guide?code=PRODUCT_IAM_DAJY' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          },
        },
      ],
      actions2: [
        {
          label: '导出',
          id: 'export',
          permission: null,
          callback: () => this.$refs.archivesDataTable.exportExcel(),
        },
      ],
      formId: 'iamArchivesBorrow',
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 删除数据
    deleteRows(record) {
      const selecteFlowState = this.$refs.borrowDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.borrowDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selecteFlowState.forEach((item) => {
        if (item.endType !== 0) {
          flag = true
        }
      })
      if (flag) {
        // 有过错误
        Modal.error({
          title: '删除失败：存在不是起草状态的数据',
        })
      } else {
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const params = {
              ids: selectedRowKeys.join(','),
            }
            this.formId = this.activeKey === '1' ? 'iamArchivesBorrow' : 'iamArchivesMaintain'
            PageService.delete(params, this.formId).then((res) => {
              if (res.status === 200) {
                message.success({ content: '删除成功！' }, 1).then(() => {
                  this.$refs.borrowDataTable.clearSelection()
                  this.$refs.borrowDataTable.refresh()
                  this.loading = false
                })
              }
            })
          },
        })
      }
    },

    moment,
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    format(shijianchuo) {
      // shijianchuo是整数，否则要parseInt转换
      var time = new Date(shijianchuo)
      var y = time.getFullYear()
      var m = time.getMonth() + 1
      var d = time.getDate()
      return y + '-' + this.add0(m) + '-' + this.add0(d)
    },
    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
      }
    },

    // 重置年份
    resetForm() {
      this.formData.year = null
      this.searchYear = null
    },
    radioOnChange(e) {
      if (this.selectedType !== e.target.value) {
        this.selectedType = e.target.value
        if (e.target.value === 1) {
          this.dataurl1 = 'api/xcoa-mobile/v1/iamarchivesborrow/all-list'
        } else if (e.target.value === 2) {
          this.dataurl1 = 'api/xcoa-mobile/v1/iamarchivesborrow/todo-list'
        }
      }
    },

    refresh() {
      return this.$refs.borrowDataTable.refresh(true)
    },
    rowClick1(record) {
      if (record.flowState === '起草') {
        window.open('#/sd-webflow/pages/draft/' + record.instId)
      } else {
        window.open('#/sd-webflow/done-pages/' + record.instId)
      }
    },
    rowClick2(record) {
      const url = '/audit-archives-view?record=' + record.id + '&dossierId=' + record.dossierId // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 查询
    handleSearch() {
      this.expressions1 = []
      // 申请人
      if (this.formData.creatorName) {
        this.expressions1.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.creatorName}%`,
        })
      }
      // 项目名称
      if (this.formData.projectName) {
        this.expressions1.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `%${this.formData.projectName}%`,
        })
      }

      this.expressions2 = []
      // 年度
      if (this.searchYear) {
        this.expressions2.push({
          dataType: 'str',
          name: 'searchYear',
          op: 'like',
          stringValue: `${this.searchYear}`,
        })
      }
      // 项目名称
      if (this.formData.projectName) {
        this.expressions2.push({
          dataType: 'str',
          name: 'projectName',
          op: 'like',
          stringValue: `${this.formData.projectName}`,
        })
      }
      // 档案编号
      if (this.formData.archivesCode) {
        this.expressions2.push({
          dataType: 'str',
          name: 'archivesCode',
          op: 'like',
          stringValue: `${this.formData.archivesCode}`,
        })
      }
    },
  },
}
</script>

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