<template>
  <div>
    <!-- 高级搜索区域 -->
    <audit-advanced-query
      :expand="expand"
      :search-data="formData"
      :ref-name="searchform"
      :search-style="{ height: '130px', left: '20px', top: '110px!important' }"
      :search-fun="handleSearch"
      @searchedClick="searchedClick"
    >
      <template>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="标题" prop="title">
              <a-input v-model="formData.title" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="财务科目" prop="financialSubjects">
              <sd-select
                v-model="formData.financialSubjects"
                :options="financialSubjectsOptions"
                :allow-clear="true"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </template>
    </audit-advanced-query>
    <sd-data-table-ex
      ref="dataTable"
      :columns="columns"
      :actions="actions"
      :show-selection="hasLeaderAuthority"
      form-id="iamProjectCost"
      page-id="work/projectcost/iamProjectCost"
      :search-fields="['title', 'financialSubjects', 'costAmount', 'creatorName']"
      :filter-expressions="tableExpressions"
      :show-advance-query="true"
      :modal-props="{ class: 'noBottom' }"
      :custom-delete-fun="linkToDelete"
      @searchbtnClick="searchbtnClick"
    >
      <div slot="isLink" slot-scope="text, record">
        <a :title="text" @click="showDetail(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 auditProjectcostService from '@product/iam/audit/work/projectcost/audit-projectcost-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import components from './_import-components/audit-projectcost-list-import'

export default {
  name: 'AuditProjectcostList',
  metaInfo: {
    title: '项目费用',
  },
  components: { ...components, auditAdvancedQuery },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      projectId: '',
      searchform: 'searchform',
      tableExpressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: this.$route.query.projectId,
        },
      ],
      formData: {
        fileTitle: '',
        financialSubjects: '',
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '标题',
          dataIndex: 'title',
          width: '30%',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '财务科目',
          dataIndex: 'financialSubjects',
        },
        {
          title: '费用金额',
          dataIndex: 'costAmount',
          customRender: (text, record, index) => {
            if (text) {
              text = parseFloat(text).toFixed(2)
            }
            return text
          },
        },
        {
          title: '发生日期',
          dataIndex: 'occurrenceDate',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          defaultSortOrder: 'desc',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          type: 'delete',
          permission: null,
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.create()
          },
        },
      ],
      financialSubjectsOptions: [],
      hasLeaderAuthority: false,
    }
  },
  mounted() {
    // 初始化页面信息
    this.initData()
    // 初始化数据字典信息
    this.initDictionaryInfo()
  },
  methods: {
    initData() {
      const projectId = this.$route.query.projectId
      // const projectStatus = this.$route.query.projectStatus
      // const currentUserType = this.$route.query.currentUserType
      if (projectId) {
        this.projectId = projectId
      }
      // 初始化操作权限
      this.initOperatePermissions()
      // if (currentUserType) {
      //   // 是否拥有项目组长和项目副组长、项目负责人的权限
      //   if (
      //       currentUserType.indexOf('01') > -1 ||
      //       currentUserType.indexOf('05') > -1 ||
      //       currentUserType.indexOf('04') > -1
      //   ) {
      //     this.hasLeaderAuthority = true
      //   } else {
      //     this.actions = []
      //   }
      // }
      // if (projectStatus) {
      //   if (projectStatus === '05' || projectStatus === '07') {
      //     this.actions = []
      //     this.hasLeaderAuthority = false
      //   }
      // }
    },
    // 初始化操作权限
    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
        // 判断是否拥有项目主审的权限
        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 ||
            currentUserType.indexOf('04') > -1
          ) {
            this.hasLeaderAuthority = true
          } else {
            this.actions = []
          }
          if (projectStatus) {
            if (projectStatus === '05' || projectStatus === '07') {
              this.actions = []
              this.hasLeaderAuthority = false
            }
          } else {
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1
            ) {
              this.actions = []
              this.hasLeaderAuthority = false
            }
          }
        }
      })
    },
    create() {
      // 新建前数据校验
      auditProjectcostService.beforeCreateCheck(this.projectId).then((res) => {
        // 新建前校验
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '您没有数据操作权限，请联系管理员!',
          })
          return null
        } else {
          const url =
            '/audit-projectcost-form?projectId=' +
            this.projectId +
            '&hasLeaderAuthority=' +
            this.hasLeaderAuthority
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              // 这里写或者调刷新的方法
              this.refreshDataTable()
            }
          })
        }
      })
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=FINANCIAL_SUBJECTS',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.financialSubjectsOptions = res.data
        }
      })
    },
    refreshDataTable() {
      this.$refs.dataTable.clearSelection()
      this.$refs.dataTable.refresh()
    },
    handleSearch() {
      this.tableExpressions = []
      this.tableExpressions.push({
        dataType: 'long',
        name: 'projectId',
        op: 'eq',
        longValue: this.projectId,
      })
      // 标题
      if (this.formData.title) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'title',
          op: 'like',
          stringValue: `%${this.formData.title}%`,
        })
      }
      // 财务科目
      if (this.formData.financialSubjects[0]) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'financialSubjects',
          op: 'like',
          stringValue: `%${this.formData.financialSubjects[0].id}%`,
        })
      }
    },
    showDetail(record) {
      const url =
        '/audit-projectcost-form?record=' +
        record.id +
        '&projectId=' +
        this.projectId +
        '&hasLeaderAuthority=' +
        this.hasLeaderAuthority // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refreshDataTable()
        }
      })
    },
    // 标题格式化
    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
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/xcoa-mobile/v1/page/iamProjectCost',
              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>
