<template>
  <span>
    <audit-advanced-query
      :expand="expand"
      :search-data="formData"
      :ref-name="searchform"
      :search-style="{ height: '165px', left: '0px', top: '40px' }"
      :search-fun="handleSearch"
      @searchedClick="searchedClick"
    >
      <template>
        <a-col :span="12">
          <a-form-model-item :label="'资料名称'" prop="materialTitle">
            <a-input v-model="formData.materialTitle" allow-clear />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'资料编号'" prop="materialCode">
            <a-input v-model="formData.materialCode" allow-clear />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'材料提供部门'" prop="provisionDeptName">
            <a-input v-model="formData.provisionDeptName" allow-clear />
          </a-form-model-item>
        </a-col>

        <!-- <a-col :span="8">
          <div :class="$style.buttonContent">
            <a-button :loading="exportLoading" type="primary" @click="exportMaterialFiles('export')"
              >批量导出附件</a-button
            >
          </div>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-model-item label="文档状态" prop="docStatus">
            <a-select v-model="formData.docStatus" :allow-clear="true">
              <a-select-option value="起草中">
                起草中
              </a-select-option>
              <a-select-option value="审批中">
                审批中
              </a-select-option>
              <a-select-option value="已结束">
                已结束
              </a-select-option>
              <a-select-option value="未反馈">
                未反馈
              </a-select-option>
              <a-select-option value="已反馈">
                已反馈
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item label="编制日期" prop="creationTime">
            <a-range-picker v-model="formData.creationTime" />
          </a-form-model-item>
        </a-col> -->
      </template>
    </audit-advanced-query>

    <sd-data-table-ex
      ref="sjzlTable"
      :filter-expressions="expressions"
      :columns="columns"
      :actions="actions"
      form-id="iamAuditMaterial"
      page-id="audit/preparation/material/iamAuditMaterial"
      data-url="api/xcoa-mobile/v1/iam-material/material-list"
      :search-fields="['materialTitle']"
      :show-advance-query="true"
      show-selection
      :modal-props="{ class: 'noBottom' }"
      @searchbtnClick="searchbtnClick"
    >
      <div slot="islink" slot-scope="text, record">
        <a :title="text" @click="rowClick(record)">{{ text }}</a>
      </div>
      <div slot="attachment" slot-scope="text, record">
        <XmAttachmentCus
          :group-id="JSON.parse(text).value ? JSON.parse(text).value : text"
          read-only
        />
      </div>
    </sd-data-table-ex>
  </span>
</template>

<script>
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 { getUserInfo } from '@/common/store-mixin'
import XmAttachmentCus from '@product/iam/core/attachment/xm-attachment-cus'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import { message, Modal } from 'ant-design-vue'
import components from './_import-components/iam-audit-material-list-import'
export default {
  name: 'IamAuditMaterialList',
  metaInfo: {
    title: '审计资料',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    XmAttachmentCus,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      projectId: this.$root.$route.query.projectId,
      searchform: 'searchform',
      expressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ],
      formData: {
        materialTitle: '',
        materialCode: '',
        provisionDeptName: '',
        docStatus: null,
        creationTime: null,
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '资料名称',
          dataIndex: 'materialTitle',
          scopedSlots: { customRender: 'islink' },
          width: '30%',
        },
        {
          title: '资料编号',
          dataIndex: 'materialCode',
          width: '15%',
        },
        {
          title: '材料提供部门',
          dataIndex: 'provisionDeptName',
          width: '200px',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          width: '160px',
        },
        {
          dataIndex: 'creatorId',
          sdHidden: true,
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          defaultSortOrder: 'descend',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          width: '120px',
        },
        {
          title: '附件',
          dataIndex: 'attachment',
          scopedSlots: { customRender: 'attachment' },
        },
        {
          title: '文档状态',
          dataIndex: 'docStatus',
          defaultSortOrder: 'ascend',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          width: '120px',
        },
      ],
      actions: [
        {
          label: '批量导出附件',
          id: 'exportdataFiles',
          permission: null, // 纯前端操作，不需要权限控制
          callback: this.exportMaterialFiles,
        },
      ],
      hasOperatePermissions: true,
      userList: null,
      // actions: [
      //   {
      //     label: '删除',
      //     id: 'delete',
      //     permission: 'delete',
      //     type: TableActionTypes.ex.delete,
      //   },
      //   {
      //     label: '新建',
      //     id: 'new',
      //     type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
      //     permission: 'iamAuditMaterial-create', // 权限控制
      //     callback: () => {
      //       const url = '/iam-audit-material-from?projectId=' + this.projectId // 新页面要打开的路由地址
      //       crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
      //         if (refreshFlag) {
      //           // 这里写或者调刷新的方法
      //           this.refresh()
      //         }
      //       })
      //       // window.open('#/sd-flow-guide?code=AUDIT_MATERIAL&projectId=' + this.projectId)
      //     },
      //   },
      // ],
    }
  },
  mounted() {
    this.isShowBtn()
  },
  methods: {
    // 导出审计资料附件
    exportMaterialFiles() {
      const selectedRowKeys = this.$refs.sjzlTable.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/exportMaterialFiles/' + 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('导出失败，请联系系统管理员')
          }
        })
      }
    },
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    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
          this.userList = userList
          var isProjectUser = this.inProjectUser(userList)
          if (['05', '06', '07'].includes(itemStatus)) {
            this.actions = [
              {
                label: '批量导出附件',
                id: 'exportdataFiles',
                permission: null, // 纯前端操作，不需要权限控制
                callback: this.exportMaterialFiles,
              },
            ]
            this.hasOperatePermissions = false
          } else {
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
              !isProjectUser
            ) {
              this.actions = []
              this.hasOperatePermissions = false
            } else {
              this.actions = [
                {
                  label: '删除',
                  id: 'delete',
                  permission: 'delete',
                  type: TableActionTypes.batch,
                  callback: this.linkDelete,
                },
                {
                  label: '新建',
                  id: 'new',
                  type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
                  permission: 'iamAuditMaterial-create', // 权限控制
                  callback: () => {
                    const url = '/iam-audit-material-from?projectId=' + this.projectId // 新页面要打开的路由地址
                    crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                      if (refreshFlag) {
                        // 这里写或者调刷新的方法
                        this.refresh()
                      }
                    })
                    // window.open('#/sd-flow-guide?code=AUDIT_MATERIAL&projectId='  this.projectId)
                  },
                },
                {
                  label: '批量导出附件',
                  id: 'exportdataFiles',
                  permission: null, // 纯前端操作，不需要权限控制
                  callback: this.exportMaterialFiles,
                },
              ]
            }
            // this.actions = [
            //   {
            //     label: '删除',
            //     id: 'delete',
            //     permission: 'delete',
            //     type: TableActionTypes.ex.delete,
            //   },
            //   {
            //     label: '新建',
            //     id: 'new',
            //     type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
            //     permission: 'iamAuditMaterial-create', // 权限控制
            //     callback: () => {
            //       const url = '/iam-audit-material-from?projectId=' + this.projectId // 新页面要打开的路由地址
            //       crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            //         if (refreshFlag) {
            //           // 这里写或者调刷新的方法
            //           this.refresh()
            //         }
            //       })
            //       // window.open('#/sd-flow-guide?code=AUDIT_MATERIAL&projectId=' + this.projectId)
            //     },
            //   },
            // ]
          }
        }
      })
    },
    // 刷新列表
    refresh() {
      // this.$refs.sjzlTable.refresh()
      this.$emit('refreshTable')
    },
    // 新建、详情打开新页面
    rowClick(record) {
      // const url = '/iam-audit-material-from?record=' + record.id + '&projectId=' + this.projectId // 新页面要打开的路由地址
      const url =
        '/iam-audit-material-from?record=' +
        record.id +
        '&projectId=' +
        this.projectId +
        '&hasOperatePermissions=' +
        this.hasOperatePermissions // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 查询
    handleSearch() {
      // 默认查询条件
      this.expressions = [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$root.$route.query.projectId,
        },
      ]

      // 资料名称
      if (this.formData.materialTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'materialTitle',
          op: 'like',
          stringValue: `%${this.formData.materialTitle}%`,
        })
      }

      // 资料编号
      if (this.formData.materialCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'materialCode',
          op: 'like',
          stringValue: `%${this.formData.materialCode}%`,
        })
      }
      // 材料提供部门
      if (this.formData.provisionDeptName) {
        this.expressions.push({
          dataType: 'str',
          name: 'provisionDeptName',
          op: 'like',
          stringValue: `%${this.formData.provisionDeptName}%`,
        })
      }
      // 文档状态
      if (this.formData.docStatus != null) {
        this.expressions.push({
          dataType: 'str',
          name: 'docStatus',
          op: 'eq',
          stringValue: this.formData.docStatus,
        })
      }

      // 编制日期
      if (this.formData.creationTime) {
        this.expressions.push({
          dataType: 'long',
          name: 'creationTime',
          op: 'between',
          longValues: [
            moment(moment(this.formData.creationTime[0]).startOf('day')).valueOf(),
            moment(moment(this.formData.creationTime[1]).endOf('day')).valueOf(),
          ],
        })
      }
    },
    linkDelete() {
      const userInfo = getUserInfo()
      const selectedRows = this.$refs.sjzlTable.getSelectedRows()
      const selectedRowKeys = this.$refs.sjzlTable.getSelectedRowKeys()
      let flag = false
      selectedRows.some((item) => {
        if (item.creatorId !== userInfo.id) {
          flag = true
          return flag
        }
      })
      if (flag) {
        this.userList.some((item) => {
          if (item.userAccount === userInfo.account) {
            if (item.userType === '03') {
              Modal.warning({
                title: '提示',
                content: '无删除权限!',
              })
            } else {
              this.$refs.sjzlTable.deleteRows(selectedRowKeys)
            }
            return true
          }
        })
      } else {
        this.$refs.sjzlTable.deleteRows(selectedRowKeys)
      }
    },
  },
}
</script>

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