<template>
  <div>
    <!-- 高级搜索区域 -->
    <audit-advanced-query
      :expand="expand"
      :search-data="formData"
      :ref-name="searchform"
      :search-fun="handleSearch"
      @searchedClick="searchedClick"
    >
      <template>
        <p></p>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="文件标题" prop="fileTitle">
              <a-input v-model="formData.fileTitle" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="编制人员" prop="creatorName">
              <a-input v-model="formData.creatorName" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </template>
    </audit-advanced-query>
    <sd-data-table-ex
      ref="dataTable"
      :columns="columns"
      :actions="actions"
      :custom-delete-fun="linkToDelete"
      show-selection
      form-id="iamAuditComdocument"
      :search-fields="[
        'fileTitle',
        'fileCode',
        'creatorName',
        'creationTime',
        'flowState',
        'currentUser',
      ]"
      :data-url="dataUrl"
      :filter-expressions="tableExpressions"
      :show-advance-query="true"
      :modal-props="{ class: 'noBottom' }"
      @searchbtnClick="searchbtnClick"
    >
      <div slot="isLink" slot-scope="text, record">
        <a :title="text" @click="showComdocumentDetail(record)">{{
          formatterTitle(text, 15)[1]
        }}</a>
      </div>
    </sd-data-table-ex>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
import { getUserInfo } from '@/common/store-mixin'
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 AuditComdocumentService from '@product/iam/audit/work/projectmanage/comdocument/audit-comdocument-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import components from './_import-components/audit-auditdocument-list-import'

export default {
  name: 'AuditComdocumentList',
  metaInfo: {
    title: '项目台账',
  },
  components: { ...components, auditAdvancedQuery },
  mixins: [auditAdvancedQueryMixins],
  props: {
    projectId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      dataUrl: '',
      searchform: 'searchform',
      tableExpressions: [],
      formData: {
        fileTitle: '',
        creatorName: '',
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '文件标题',
          dataIndex: 'fileTitle',
          width: '30%',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '文件编号',
          dataIndex: 'fileCode',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '当前状态',
          sorter: true,
          dataIndex: 'flowState',
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            const url = '/sd-flow-guide?code=PRODUCT_IAM_ZHWD&&projectId=' + this.projectId // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refreshDataTable()
              }
            })
          },
        },
        {
          label: '删除',
          type: 'delete',
          permission: null,
        },
      ],
      expand: false,
      hasOperatePermissions: true,
    }
  },
  created() {
    this.dataUrl = 'api/xcoa-mobile/v1/iamauditcomdocument/all-list/' + this.projectId
  },
  mounted() {
    // 初始化操作权限
    this.initOperatePermissions()
  },
  methods: {
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },
    // 初始化操作权限
    initOperatePermissions() {
      axios({
        url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + this.projectId,
      }).then((res) => {
        const projectStatus = res.data.itemStatus
        const readAuthorityCodes = res.data.readAuthorityCodes
        const userList = res.data.iamProjectUserList
        var isProjectUser = this.inProjectUser(userList)
        if (projectStatus === '05' || projectStatus === '07') {
          this.actions = []
          this.hasOperatePermissions = false
        } else {
          if (
            readAuthorityCodes != null &&
            readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
            !isProjectUser
          ) {
            this.actions = []
            this.hasOperatePermissions = false
          }
        }
      })
    },
    refreshDataTable() {
      this.$refs.dataTable.clearSelection()
      this.$refs.dataTable.refresh()
    },
    searchedClick() {
      this.expand = !this.expand
    },
    handleSearch() {
      this.tableExpressions = []
      // 文件标题
      if (this.formData.fileTitle) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'fileTitle',
          op: 'like',
          stringValue: `%${this.formData.fileTitle}%`,
        })
      }
      // 编制人员
      if (this.formData.creatorName) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.creatorName}%`,
        })
      }
    },
    showComdocumentDetail(record) {
      if (
        (record.flowState === '起草') | (record.flowState === '开始') &&
        this.hasOperatePermissions
      ) {
        const loginUser = getUserInfo()
        if (loginUser.account === record.creatorAccount) {
          const url = '/sd-webflow/pages/draft/' + record.instId // 编辑面要打开的路由地址
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              // 这里写或者调刷新的方法
              this.refreshDataTable()
            }
          })
        } else {
          window.open('#/sd-webflow/done-pages/' + record.instId)
        }
      } else {
        window.open('#/sd-webflow/done-pages/' + record.instId)
      }
    },
    // 标题格式化
    formatterTitle(val, length) {
      var resultArry = []
      let title = ''
      let result = ''
      if (val === undefined || val === '' || val === '[]') {
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      } else {
        try {
          JSON.parse(val).forEach((e) => {
            result += e.name + ','
          })
        } catch (e) {
          result = val
        }
        if (result.lastIndexOf(',') > 0) {
          result = result.substr(0, result.length - 1)
        }
        title = result
        if (result.length > length) {
          result = result.substr(0, length) + '...'
        }
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      }
    },
    linkToDelete() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }
      // 删除前数据校验
      AuditComdocumentService.beforeDeleteCheck(selectedRowKeys).then((res) => {
        // 删除前校验
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '您没有数据操作权限，请联系管理员!',
          })
          return null
        } else {
          return new Promise((resolve) => {
            Modal.confirm({
              title: '您确定删除这项内容吗？',
              content: '删除这条数据后，就无法恢复初始的状态。',
              okText: '删除',
              okType: 'danger',
              onOk: () => {
                axios({
                  url: 'api/xcoa-mobile/v1/page/iamAuditComdocument',
                  method: 'delete',
                  params: {
                    ids: selectedRowKeys.join(','),
                  },
                })
                  .then(() => {
                    const msg = '删除成功'
                    message.success(msg)
                    this.$refs.dataTable.clearSelection()
                    this.$refs.dataTable.refresh()
                  })
                  .catch((err) => {
                    const msg = errorUtil.getMessage(err) || '删除失败'
                    message.error(msg)
                  })
                  .finally(resolve)
              },
              onCancel: () => {
                resolve()
              },
            })
          })
        }
      })
    },
  },
}
</script>

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