<template>
  <div>
    <sd-data-table-ex
      ref="dataTable"
      form-id="iamProjectAccount"
      page-id="audit/work/projectmanage/account/iamProjectAccount"
      :columns="columns"
      :actions="actions"
      :custom-delete-fun="linkToDelete"
      :show-selection="hasOperatePermissions"
      :filter-expressions="[
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: projectId,
        },
      ]"
    >
      <div slot="isLink" slot-scope="text, record">
        <a :title="text" @click="showAccountDetail(record)">{{ text }}</a>
      </div>
    </sd-data-table-ex>
    <audit-advanced-export
      ref="export"
      :v-if="false"
      :exclebxh="false"
      table-id="SJXMDataTable"
      :expressions="[
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: projectId,
        },
      ]"
      :config-id="131"
    />
  </div>
</template>

<script>
import auditAdvancedExport from '@product/iam/components/audit-advanced-export.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableActionTypes from '@/common/services/table-action-types'
import { message, Modal } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
import auditAccountService from '@product/iam/audit/work/projectmanage/account/audit-account-service'
import components from './_import-components/audit-account-list-import'

export default {
  name: 'AuditAccountList',
  metaInfo: {
    title: '项目台账',
  },
  components: { ...components, auditAdvancedExport },
  props: {
    projectId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectTitle',
          scopedSlots: { customRender: 'isLink' },
          width: '30%',
        },
        {
          title: '项目组人数（个）',
          dataIndex: 'projectPeopleNum',
        },
        {
          title: '项目投入人天数(人天)',
          dataIndex: 'projectPeopleDays',
        },
        {
          title: '审计类型',
          dataIndex: 'auditType',
        },
        {
          title: '项目费用（万元）',
          dataIndex: 'projectCost',
        },
        {
          title: '审计金额（万元）',
          dataIndex: 'auditAmount',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: null,
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          callback: () => {
            this.create()
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: 'delete',
          permission: null,
        },
        {
          label: '导出',
          id: 'export',
          permission: null,
          callback: () => {
            this.$refs.export.exportdata()
          },
        },
      ],
      hasLeaderAuthority: false,
      hasOperatePermissions: true,
    }
  },
  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 (userList) {
          const currentUserType = userList.map((item) => {
            if (item.userAccount === getUserInfo().account) {
              return item.userType
            } else {
              return false
            }
          })
          if (currentUserType.indexOf('01') > -1 || currentUserType.indexOf('05') > -1) {
            this.hasLeaderAuthority = true
          }
        }
        // 判断是否拥有操作的权限
        if (projectStatus === '05' || projectStatus === '07') {
          this.actions = [
            {
              label: '导出',
              id: 'delete',
              permission: null,
              callback: () => {
                this.$refs.export.exportdata()
              },
            },
          ]
          this.hasOperatePermissions = false
        } else {
          if (
            readAuthorityCodes != null &&
            readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
            !isProjectUser
          ) {
            this.actions = [
              {
                label: '导出',
                id: 'delete',
                permission: null,
                callback: () => {
                  this.$refs.export.exportdata()
                },
              },
            ]
            this.hasOperatePermissions = false
          }
        }
      })
    },
    create() {
      // 新建前数据校验
      auditAccountService.beforeCreateCheck(this.projectId).then((res) => {
        // 新建前校验
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '您没有数据操作权限，请联系管理员!',
          })
          return null
        } else {
          const url =
            '/audit-account-form?projectId=' +
            this.projectId +
            '&hasLeaderAuthority=' +
            this.hasLeaderAuthority // 新页面要打开的路由地址
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              // 这里写或者调刷新的方法
              this.refreshDataTable()
            }
          })
        }
      })
    },
    refreshDataTable() {
      this.$refs.dataTable.clearSelection()
      this.$refs.dataTable.refresh()
    },
    showAccountDetail(record) {
      const url =
        '/audit-account-form?record=' +
        record.id +
        '&projectId=' +
        this.projectId +
        '&hasLeaderAuthority=' +
        this.hasLeaderAuthority // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refreshDataTable()
        }
      })
    },
    linkToDelete() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/xcoa-mobile/v1/page/iamProjectAccount',
              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()
          },
        })
      })
    },
    // 标题格式化
    formatterTitle(val, length) {
      var resultArry = []
      let title = ''
      let result = ''
      if (val === undefined || val === null || 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
      }
    },
  },
}
</script>

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