<template>
  <div :class="$style.wrapHeight">
    <a-card :bordered="false">
      <a-tabs v-model="activeKey" type="line" @change="toggleTabs">
        <a-tab-pane key="1" tab="年度报告">
          <!-- 高级搜索组件 -->
          <audit-advanced-query
            :class="$style.advancedQuery"
            :expand="expand"
            :search-data="formData"
            :ref-name="searchform"
            :search-style="{ height: '210px', left: '20px', top: '60px' }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-row>
                <a-col :span="12">
                  <a-form-model-item :label="'年\u2002\u2002度'" prop="reportYear">
                    <a-input v-model="formData.reportYear" allow-clear />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item :label="'标\u2002\u2002题'" prop="title">
                    <a-input v-model="formData.title" allow-clear />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <a-form-model-item :label="'当前状态'" prop="flowState">
                    <sd-select
                      v-model="formData.flowState"
                      :allow-clear="true"
                      :options="flowStateOptions"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item :label="'上报单位'" prop="auditedUnitNames">
                    <a-input v-model="formData.auditedUnitNames" allow-clear />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <a-form-model-item :label="'是否逾期未报'" prop="isLate">
                    <sd-select
                      v-model="formData.isLate"
                      :allow-clear="true"
                      :options="isLateOptions"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </template>
          </audit-advanced-query>
          <a-card>
            <sd-data-table-ex
              ref="SJMBKDataTable"
              :filter-expressions="expressions"
              :columns="columns"
              :actions="actions"
              form-id="spicAnnualReport"
              data-url="api/xcoa-mobile/v1/spicannualreport/all-list"
              :search-fields="['fileTitle']"
              show-selection
              :show-advance-query="true"
              :custom-delete-fun="deleteFun"
              @searchbtnClick="searchbtnClick"
            >
              <div slot="islink" slot-scope="text, record">
                <a :title="text" @click="rowClick(record)">{{ text }}</a>
              </div>
            </sd-data-table-ex>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="2" tab="年报资料下发">
          <!-- 高级搜索区域 -->
          <audit-advanced-query
            :expand="expand"
            :search-data="SJJHAdvSearchForm"
            :ref-name="searchform"
            :search-style="{ height: '170px', left: '20px', top: '57px' }"
            :search-fun="handleSearch2"
            @searchedClick="searchedClick"
          >
            <template>
              <a-col :span="8">
                <a-form-model-item :label="'年度'" prop="reportYear">
                  <a-input v-model="SJJHAdvSearchForm.reportYear" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="当前状态" prop="status">
                  <sd-select
                    v-model="SJJHAdvSearchForm.status"
                    :allow-clear="true"
                    :options="flowStateOptions2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="编辑人员" prop="creatorName">
                  <a-input v-model="SJJHAdvSearchForm.creatorName" />
                </a-form-model-item>
              </a-col>
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            ref="SJJHDataTable"
            :filter-expressions="SJJHTableExpressions"
            :columns="columns2"
            show-selection
            form-id="spicAnnualReportPublish"
            data-url="api/xcoa-mobile/v1/spicannualreportpublish/all_list"
            :search-fields="['fileTitle']"
            :actions="this.isApplicationAdmin === true ? actions2 : actions1"
            :custom-delete-fun="deleteRows"
            :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>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import moment from 'moment'
import errorUtil from '@/common/services/error-util'
import CompositeDatabaseService from '../spiccompositedatabase/composite-database-service'
import components from './_import-components/xm-annual-report-list-import'
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 '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
export default {
  name: 'XmAnnualReportList',
  metaInfo: {
    title: '年度报告库',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      year: null,
      endOpen: false,
      expand: false,
      isApplicationAdmin: false, // 是否为年度报告管理员
      searchform: 'searchform',
      SJJHTableExpressions: [],
      activeKey: '1',
      expressions: [],
      formData: {
        reportYear: '',
        title: '',
        flowState: '',
        auditedUnitNames: '',
        isLate: '',
      },
      SJJHAdvSearchForm: {
        reportYear: '',
        status: '',
        creatorName: '',
      },
      formId: 'spicAnnualReport',
      tableId: 'SJMBKDataTable',
      flowStateOptions: [
        {
          id: '开始',
          name: '开始',
        },
        {
          id: '结束',
          name: '结束',
        },
      ],
      flowStateOptions2: [
        {
          id: '起草中',
          name: '起草中',
        },
        {
          id: '已发布',
          name: '已发布',
        },
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '60px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '年度',
          dataIndex: 'reportYear',
          width: '80px',
        },
        {
          title: '标题',
          dataIndex: 'fileTitle',
          scopedSlots: { customRender: 'islink' },
          width: '15%',
        },
        {
          title: '上报单位',
          dataIndex: 'auditedUnitNames',
          width: '200px',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          width: '100px',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
          sortDirections: ['ascend', 'descend'],
          width: '100px',
        },
        // {
        //   title: '编制日期',
        //   dataIndex: 'creationTime',
        //   sdRender: TableColumnTypes.date,
        //   defaultSortOrder: 'descend',
        //   sorter: true,
        //   sortDirections: ['ascend', 'descend'],
        //   width: '30%',
        // },
        {
          title: '当前状态',
          dataIndex: 'flowState',
          width: '100px',
          sorter: true,
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
          width: '100px',
        },
        {
          title: '操作',
          dataIndex: 'opt',
          aligen: 'center',
          customRender: (text, record, index) => {
            if (record.endType === 5 && record.publishAccount === getUserInfo().account) {
              return (
                <span>
                  <a vOn:click={(evt) => this.overruleReport(record)}>驳回上报</a>
                </span>
              )
            }
          },
          width: '100px',
        },
      ],
      columns2: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '60px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '年度',
          dataIndex: 'reportYear',
          width: '80px',
        },
        {
          title: '标题',
          width: '15%',
          dataIndex: 'fileTitle',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '在线反馈截止时间',
          dataIndex: 'lastTime',
          width: '120px',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          width: '120px',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
          sortDirections: ['ascend', 'descend'],
          width: '120px',
        },
        {
          title: '当前状态',
          dataIndex: 'status',
          sortDirections: ['ascend', 'descend'],
          width: '120px',
          sorter: true,
        },
      ],
      isLateOptions: [
        {
          id: '是',
          name: '是',
        },
        {
          id: '否',
          name: '否',
        },
      ],
      actions: [
        // {
        //   label: '新建',
        //   id: 'new',
        //   permission: 'create',
        //   type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
        //   callback: () => {
        //     const url = '/sd-flow-guide?code=SPIC_AUDIT_REPORT' // 新页面要打开的路由地址
        //     crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        //       if (refreshFlag) {
        //         // 这里写或者调刷新的方法
        //         this.refreshDataTable()
        //       }
        //     })
        //   },
        // },
        // {
        //   label: '删除',
        //   id: 'delete',
        //   type: 'delete', // 删除按钮，不需要回调，会自动处理
        //   permission: null,
        // },
        {
          label: '批量导出附件',
          id: 'exportdataFiles',
          permission: null, // 纯前端操作，不需要权限控制
          callback: this.exportAnnualReportFiles,
        },
      ],
      actions1: [],
      actions2: [
        {
          label: '新建',
          id: 'new',
          permission: 'create',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          callback: () => {
            const url = '/xm-annual-report-puiblish' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refreshDataTable()
              }
            })
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: 'delete', // 删除按钮，不需要回调，会自动处理
          permission: null,
        },
      ],
    }
  },
  mounted() {
    // 初始化权限
    this.initJurisdiction()
  },
  methods: {
    // 初始化权限
    initJurisdiction() {
      debugger
      // 校验权限（检查为年度报告管理员）
      CompositeDatabaseService.checkAnnualReportPermission().then((res) => {
        this.isApplicationAdmin = res.data.isHasPermission // 按钮权限（年度报告管理员）
      })
    },

    // 驳回上报
    overruleReport(record) {
      axios({
        url: 'api/xcoa-mobile/v1/spicannualreport/overruleReport?id=' + record.id,
        method: 'get',
      }).then((res) => {
        if (res.data) {
          Modal.info({
            title: '提示',
            content: '驳回成功!',
          })
          this.$refs.SJMBKDataTable.refresh()
        } else {
          Modal.warning({
            title: '提示',
            content: '驳回失败，请联系管理员!',
          })
        }
      })
    },

    // 导出审计模板附件
    exportAnnualReportFiles() {
      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/exportAnnualReportFiles/' + 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('导出失败，请联系系统管理员')
          }
        })
      }
    },

    onChange(value) {
      if (value) {
        this.SJJHAdvSearchForm.reportYear = value.format('yyyy')
      } else {
        this.SJJHAdvSearchForm.reportYear = ''
      }
    },
    deleteRows() {
      const selectedRowKeys = this.$refs.SJJHDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      const selectedRows = this.$refs.SJJHDataTable.getSelectedRows()
      let flag = false
      selectedRows.forEach((item) => {
        if (item.status === '已发布') {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在已发布状态的数据',
        })
        return
      }
      const currentAccount = getUserInfo().account
      const instIds = []
      var flages = true
      selectedRows.forEach((item) => {
        var instId = item.instId - 0
        if (item.creatorAccount !== currentAccount) {
          Modal.info({
            content: '请选择自己创建的文件',
          })
          flages = false
        } else {
          instIds.push(instId)
        }
      })
      if (!flages) {
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/framework/v1/page/' + this.$refs.SJJHDataTable.formId,
              method: 'delete',
              params: { ids: selectedRowKeys.join(',') },
            })
              .then(() => {
                this.$refs.SJJHDataTable.clearSelection()
                this.$refs.SJJHDataTable.refresh()
                message.success('删除成功')
                this.$emit('recordsDeleted', selectedRowKeys)
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },

    yearChange(value) {
      this.year = value
      this.model.reportYear = value.format('YYYY')
      if (document.getElementsByClassName('ant-calendar-picker-container').length > 0) {
        document.getElementsByClassName('ant-calendar-picker-container')[0].style.display = 'none'
      }
    },

    handleEndOpenChange(open) {
      this.endOpen = open
    },
    clearSelection() {
      this.$refs.SJMBKDataTable.clearSelection()
    },
    // 刷新列表
    refresh() {
      this.$emit('refreshTable')
    },
    deleteFun() {
      debugger
      const selectedRowKeys = this.$refs.SJMBKDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      const selectedRows = this.$refs.SJMBKDataTable.getSelectedRows()
      const currentAccount = getUserInfo().account
      const instIds = []
      let flag = false
      selectedRows.forEach((item) => {
        if (item.endType !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
        return
      }
      var flages = true
      selectedRows.forEach((item) => {
        var instId = item.instId - 0
        if (item.creatorAccount !== currentAccount) {
          Modal.info({
            content: '请选择自己创建的文件',
          })
          flages = false
        } else {
          instIds.push(instId)
        }
      })
      if (!flages) {
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/flow-mobile/v1/process-manager/process-instance/remove',
              method: 'POST',
              data: {
                flowCallbackBeanName: 'formBeanCleanerCallBack',
                processInstanceIds: instIds.join(','),
              },
            })
              .then(() => {
                this.clearSelection()
                this.$refs.SJMBKDataTable.refresh()
                message.success('删除成功')
                /**
                 * 数据删除成功后触发
                 * @property {Array} rowKeys 已删除的记录ids
                 */
                this.$emit('recordsDeleted', selectedRowKeys)
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    // 新建、详情打开新页面
    rowClick(record) {
      let openurl = ''
      if (
        (record.flowState === '起草') |
        (record.flowState === '开始') |
        (record.flowState === null)
      ) {
        if (
          (record.flowState === '起草' || record.flowState === '开始') &&
          record.creatorAccount === getUserInfo().account
        ) {
          openurl = '/sd-webflow/pages/draft/' + record.instId
        } else {
          openurl = '/sd-webflow/done-pages/' + record.instId
        }
      } else {
        openurl = '/sd-webflow/done-pages/' + record.instId
      }
      crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refresh()
        }
      })
    },

    rowClick2(record) {
      const url = '/xm-annual-report-puiblish?record=' + record.id
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refreshDataTable()
        }
      })
    },
    refreshDataTable() {
      if (this.activeKey === '1') {
        this.tableId = 'SJMBKDataTable'
      }
      if (this.activeKey === '2') {
        this.tableId = 'SJJHDataTable'
      }
      if (this.$refs[`${this.tableId}`]) {
        this.$refs[`${this.tableId}`].clearSelection()
        this.$refs[`${this.tableId}`].refresh()
      }
    },
    toggleTabs(key) {
      this.activeKey = key
      if (this.activeKey === '1') {
        this.tableId = 'SJMBKDataTable'
        this.expressions = []
      } else {
        this.tableId = 'SJJHDataTable'
        this.SJJHTableExpressions = []
      }
      if (this.$refs[`${this.tableId}`]) {
        this.$refs[`${this.tableId}`].clearSelection()
      }
    },
    searchedClick() {
      this.expand = !this.expand
    },
    // 查询
    handleSearch() {
      debugger
      this.expressions = []
      // 年度
      if (this.formData.reportYear) {
        this.expressions.push({
          dataType: 'str',
          name: 'reportYear',
          op: 'like',
          stringValue: `%${this.formData.reportYear}%`,
        })
      }
      // 当前状态
      if (this.formData.flowState[0]) {
        this.expressions.push({
          dataType: 'str',
          name: 'flowState',
          op: 'like',
          stringValue: `%${this.formData.flowState[0].id}%`,
        })
      }
      // 报送机构名称
      if (this.formData.auditedUnitNames) {
        this.expressions.push({
          dataType: 'str',
          name: 'auditedUnitNames',
          op: 'like',
          stringValue: `%${this.formData.auditedUnitNames}%`,
        })
      }
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'title',
          op: 'like',
          stringValue: `%${this.formData.title}%`,
        })
      }
      if (this.formData.isLate[0]) {
        this.expressions.push({
          dataType: 'str',
          name: 'isLate',
          op: 'like',
          stringValue: `${this.formData.isLate[0].id}`,
        })
      }
      this.$refs[`${this.tableId}`].clearSelection()
    },
    handleSearch2() {
      this.SJJHTableExpressions = []

      // 年度
      if (this.SJJHAdvSearchForm.reportYear) {
        this.SJJHTableExpressions.push({
          dataType: 'str',
          name: 'reportYear',
          op: 'like',
          stringValue: `%${this.SJJHAdvSearchForm.reportYear}%`,
        })
      }
      // 当前状态
      if (this.SJJHAdvSearchForm.status[0]) {
        this.SJJHTableExpressions.push({
          dataType: 'str',
          name: 'status',
          op: 'like',
          stringValue: `%${this.SJJHAdvSearchForm.status[0].id}%`,
        })
      }
      // 编辑人员
      if (this.SJJHAdvSearchForm.creatorName) {
        this.SJJHTableExpressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.SJJHAdvSearchForm.creatorName}%`,
        })
      }
      this.$refs[`${this.tableId}`].clearSelection()
    },
  },
}
</script>

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

.advancedQuery {
  :global(.ant-col .ant-form-item-label) {
    width: 30% !important;
  }

  :global(.ant-col .ant-form-item-control-wrapper) {
    width: 60% !important;
  }
}
</style>
