<template>
  <a-spin :spinning="!inited" tip="正在删除...">
    <div :class="$style.projectListDiv">
      <a-card :bordered="false">
        <!-- 高级搜索区域 -->
        <audit-advanced-query
          :expand="isShowAdvSearch"
          :search-data="advSearchForm"
          :ref-name="searchform"
          :search-style="{
            height: '170px',
            left: '30px',
            top: '65px !important',
            width: 'calc(100% - 40px) !important',
          }"
          :search-fun="advSearch"
          @searchedClick="searchedClick"
        >
          <template>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="项目名称" prop="projectTitle">
                  <a-input v-model="advSearchForm.projectTitle" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目编号" prop="projectCode">
                  <a-input v-model="advSearchForm.projectCode" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目组长" prop="groupLeaderName">
                  <a-input v-model="advSearchForm.groupLeaderName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="审计方式" prop="auditMode">
                  <sd-select
                    v-model="advSearchForm.auditMode"
                    :allow-clear="true"
                    :options="auditModeOptions"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目状态" prop="itemStatus">
                  <sd-select
                    v-model="advSearchForm.itemStatus"
                    :allow-clear="true"
                    :options="itemStatusOptions"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="审计类型" prop="auditType">
                  <sd-select
                    v-model="advSearchForm.auditType"
                    :allow-clear="true"
                    :options="auditTypeOptions"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </template>
        </audit-advanced-query>
        <sd-data-table-ex
          ref="dataTable"
          style="margin-top: 42px"
          :columns="columns"
          :process-req="processReq"
          show-selection
          form-id="iamAuditProject"
          data-url="api/xcoa-mobile/v1/iamauditproject/all-list"
          :filter-expressions="tableExpressions"
          @change="changeNum"
          @selectedRowsChanged="selectedRowsChanged"
        >
          <div slot="isLink" slot-scope="text, record">
            <a :title="text" @click="linkProject(record)">{{ text }}</a>
          </div>
          <div slot="opt" slot-scope="text, record" :class="$style.operatecol">
            <span v-for="(bt, index) in buttonsfortable" :key="index">
              <a-button
                v-if="
                  (!bt.showCondition || bt.showCondition === record.itemStatus) &&
                  checkPermission(bt.permission, record.operatePermission)
                "
                type="link"
                size="small"
                :title="bt.label"
                :class="$style.optbutton"
                @click="optbuttonClick(bt.id, record)"
              >
                <sd-icon :type="bt.icontype" :theme="bt.theme" />
              </a-button>
            </span>
          </div>
        </sd-data-table-ex>
        <div :class="[$style.btns]">
          <a-col :span="7" :offset="0">
            <a-select v-model="searchYear" style="width: 80px" @change="changeYearSelect">
              <a-select-option v-for="year in yearArry" :key="year">
                {{ year }}
              </a-select-option>
            </a-select>
            <a-checkbox v-model="checkboxValue" style="margin-left: 15px" @change="onChange">
              仅显示我参与的
            </a-checkbox>
          </a-col>
          <a-col v-if="isAuditLeader === true" :span="6" :offset="0">
            <a-form-model layout="horizontal" v-bind="{ wrapperCol: { span: 24 } }">
              <a-form-model-item>
                <AuditGroupPicker
                  v-model="auditUnit"
                  :single="true"
                  :read-only="false"
                  :root-node="rootNode"
                  @change="changeAuditUnit"
                />
              </a-form-model-item>
            </a-form-model>
          </a-col>
          <a-col :span="7" :offset="10" :class="$style.actionBtn">
            <a-input-search
              v-model="searchValue"
              style="width: 200px"
              placeholder="请输入搜索条件"
              allow-clear
              @search="onSearch"
            />
            <a-button title="高级搜索" :class="$style.advSearchBtn" @click="AdvSearchClick">
              <a-icon type="sd-audit-advancesearch" theme="filled" :class="$style.searchIcon" />
            </a-button>
            <a-button
              v-if="isApplicationAdmin"
              :class="[$style.buttonSpacing]"
              :disabled="deleteButtonDisable"
              @click="linkToDelete"
              >删除
            </a-button>
          </a-col>
        </div>
        <div v-show="false">
          <sd-user-picker
            ref="assignTeamLeader"
            v-model="mainSendUnit"
            :single="setType === 'groupLeader'"
            :read-only="false"
            @change="change"
          />
        </div>
      </a-card>
    </div>
  </a-spin>
</template>

<script>
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 AuditService from '@product/iam/audit/plan/audit-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import AuditProjectService from './audit-project-service'
import components from './_import-components/audit-project-list-import'
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'

export default {
  name: 'AuditProjectList',
  metaInfo: {
    title: '审计项目列表',
  },
  components: { ...components, auditAdvancedQuery, AuditGroupPicker },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      rootNode: {},
      auditUnit: [],
      inited: true,
      initedSteps: 0,
      searchYear: new Date().getFullYear().toString(),
      yearArry: [],
      searchValue: '',
      mainSendUnit: [],
      checkboxValue: false,
      isApplicationAdmin: false, // 是否为应用管理员
      deleteButtonDisable: true,
      pageId: 'audit/project/iamAuditProject',
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectTitle',
          width: '35%',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '项目编号',
          width: '10%',
          sorter: true,
          dataIndex: 'projectCode',
        },
        {
          title: '审计类型',
          width: '110px',
          dataIndex: 'auditType',
        },
        {
          title: '项目状态',
          sorter: true,
          dataIndex: 'itemStatusStr',
          width: '120px',
        },
        {
          title: '审计组长',
          sorter: true,
          dataIndex: 'groupLeaderName',
          width: '120px',
        },
        {
          title: '审计方式',
          dataIndex: 'auditMode',
          width: '120px',
        },
        {
          title: '项目评价',
          dataIndex: 'projectScore',
          width: '120px',
        },
        {
          title: '操作',
          dataIndex: 'id',
          sdHidden: false,
          scopedSlots: { customRender: 'opt' },
          width: '150px',
        },
      ],
      actions: [],
      tableExpressions: [],
      buttonsfortable: [
        {
          label: '分配组长',
          id: 'assignTeamLeader',
          icontype: 'sd-audit-changeuser',
          theme: 'fill',
          // showCondition: '01', // 未启动
          permission: '04', // 项目负责人
        },
        {
          label: '启动项目',
          id: 'startproject',
          icontype: 'sd-audit-start',
          theme: 'fill',
          showCondition: '01', // 未启动
          permission: '05,99', // 项目组长
        },
        {
          label: '关闭项目',
          id: 'closeProject',
          icontype: 'sd-audit-closeproject',
          theme: 'fill',
          showCondition: '04', // 报告阶段
          permission: '05,01', // 项目组长、项目副组长
        },
        {
          label: '重启项目',
          id: 'restart',
          icontype: 'sd-audit-restart',
          theme: 'fill',
          showCondition: '05', // 已关闭
          permission: '05,01', // 项目组长、项目副组长
        },
        {
          label: '项目评分',
          id: 'projectScore',
          icontype: 'sd-audit-support-center',
          theme: 'fill',
          showCondition: '05', // 已关闭
          permission: '05,01', // 项目组长、项目副组长
        },
        // {
        //   label: '归档',
        //   id: 'projectArchive',
        //   icontype: 'sd-audit-archive',
        //   theme: 'fill',
        //   showCondition: '05', // 已关闭
        //   permission: '05,01', // 项目组长、项目副组长
        // },
        // {
        //   label: '设定查阅范围',
        //   id: 'setReadAuthority',
        //   icontype: 'sd-audit-set-searchread',
        //   theme: 'fill',
        //   showCondition: '05', // 已关闭
        //   permission: '05,01,04', // 项目组长、项目副组长、项目负责人
        // },
      ],
      searchform: 'searchform',
      isShowAdvSearch: false,
      advSearchForm: {
        projectTitle: '',
        projectCode: '',
        groupLeaderName: '',
        auditMode: '',
        itemStatus: '',
        auditType: '',
      },
      itemStatusOptions: [],
      auditTypeOptions: [],
      auditModeOptions: [],
      projectId: '',
      setType: '',
    }
  },
  computed: {
    isAuditLeader() {
      const userInfo = getUserInfo()
      return (
        userInfo.roles.filter(
          (e) =>
            e.code === 'G-1_AUDIT_SECTION_MANAGER' ||
            e.code === 'G-1_AUDIT_DEPARTMENT_LEADER' ||
            e.code === 'G-1_AUDIT_CHARGE_LEADER' ||
            e.code === 'G-1_DEPARTMENT_LEADER'
        ).length > 0
      )
    },
  },

  mounted() {
    // 初始化年份下拉框
    this.initYearSelect()
    // 初始化数据字典信息
    this.initDictionaryInfo()
    // 初始化权限
    this.initJurisdiction()
    if (this.isAuditLeader === true) {
      this.initAuditUnit()
    }
  },
  methods: {
    // 初始化权限
    initJurisdiction() {
      // 校验权限（检查层级资源权限权限和是否为审计人员）
      AuditProjectService.checkPermission().then((res) => {
        this.isApplicationAdmin = res.data.isHasPermission // 删除按钮权限（拥有应用管理员角色）
      })
    },
    initAuditUnit() {
      let userInfo = getUserInfo()
      if (this.isAuditLeader) {
        const params = {
          orgId: userInfo.deptId,
        }
        axios({
          url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
          method: 'get',
        }).then((res) => {
          userInfo = res.data
          params.orgId = res.data.id
          axios({
            url: 'api/xcoa-mobile/v1/iamorg/findIamOrg',
            method: 'post',
            params,
          }).then((res) => {
            const deptCode = userInfo.id.toString()
            const deptName = res.data.orgName
            this.rootNode = { code: deptCode, name: deptName, id: res.data.id }
            this.auditUnit = [this.rootNode]
            this.initedSteps++
            // if (this.initedSteps === (this.isAuditLeader ? 2 : 1)) {
            this.changeAuditUnit(this.auditUnit)
            // }
          })
        })
      }
    },
    // 初始化年份下拉框
    initYearSelect() {
      AuditService.getPlanYear().then((res) => {
        // 获取计划年度
        if (res.data != null && res.data !== '') {
          let flag = true
          res.data.forEach((e) => {
            this.yearArry.push(e)
            if (e === this.searchYear) {
              flag = false
            }
          })
          if (flag === true) {
            const arry = res.data.filter((e) => e < this.searchYear).reverse()
            if (arry.length > 0) {
              this.searchYear = arry[0]
            } else {
              this.searchYear = this.yearArry[this.yearArry.length - 1]
            }
          }
          this.yearArry.sort().reverse()
        } else {
          // 如果没有已经发布的计划，则显示当前年份
          this.yearArry.push(this.searchYear)
        }
        this.initedSteps++
        // if (this.initedSteps === (this.isAuditLeader ? 2 : 1)) {
        this.changeYearSelect(this.searchYear)
        // }
      })
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PRODUCT_IAM_AUDIT_PROJECT_STATUS',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.itemStatusOptions = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PRODUCT_IAM_AUDIT_METHOD',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.auditModeOptions = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PRODUCT_IAM_AUDIT_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.auditTypeOptions = res.data
        }
      })
    },
    changeAuditUnit(value) {
      this.tableExpressions = []
      if (value.length > 0) {
        // 计划年度
        this.tableExpressions.push({
          dataType: 'str',
          name: 'planYear',
          op: 'like',
          stringValue: this.searchYear,
        })

        let isMyParticipateValue
        if (this.checkboxValue) {
          isMyParticipateValue = '1'
        } else {
          isMyParticipateValue = '0'
        }
        // 仅我参与的
        this.tableExpressions.push({
          dataType: 'str',
          name: 'isMyParticipate',
          op: 'eq',
          stringValue: `${isMyParticipateValue}`,
        })
        // 审计机构
        this.tableExpressions.push({
          dataType: 'str',
          name: 'unitName',
          op: 'like',
          stringValue: `${value[0].name}`,
        })
      }
      this.$refs.dataTable.clearSelection()
    },
    changeYearSelect(value) {
      this.tableExpressions = []
      if (value) {
        // 计划年度
        this.tableExpressions.push({
          dataType: 'str',
          name: 'planYear',
          op: 'like',
          stringValue: `${value}`,
        })

        let isMyParticipateValue
        if (this.checkboxValue) {
          isMyParticipateValue = '1'
        } else {
          isMyParticipateValue = '0'
        }
        // 仅我参与的
        this.tableExpressions.push({
          dataType: 'str',
          name: 'isMyParticipate',
          op: 'eq',
          stringValue: `${isMyParticipateValue}`,
        })

        // 审计机构
        if (this.auditUnit.length > 0) {
          this.tableExpressions.push({
            dataType: 'str',
            name: 'unitName',
            op: 'like',
            stringValue: this.auditUnit[0].name,
          })
        }
      }
      this.$refs.dataTable.clearSelection()
    },
    onSearch(value) {
      this.tableExpressions = []
      // 计划年度
      this.tableExpressions.push({
        dataType: 'str',
        name: 'planYear',
        op: 'like',
        stringValue: `%${this.searchYear}%`,
      })
      let isMyParticipateValue
      if (this.checkboxValue) {
        isMyParticipateValue = '1'
      } else {
        isMyParticipateValue = '0'
      }
      // 仅我参与的
      this.tableExpressions.push({
        dataType: 'str',
        name: 'isMyParticipate',
        op: 'eq',
        stringValue: `${isMyParticipateValue}`,
      })
      if (value) {
        const expressions = []
        // 项目名称
        expressions.push({
          dataType: 'str',
          name: 'projectTitle',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 项目编号
        expressions.push({
          dataType: 'str',
          name: 'projectCode',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 审计类型
        expressions.push({
          dataType: 'str',
          name: 'auditType',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 项目状态
        expressions.push({
          dataType: 'str',
          name: 'itemStatus',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 项目组长
        expressions.push({
          dataType: 'str',
          name: 'groupLeaderName',
          op: 'like',
          stringValue: `%${value}%`,
        })
        // 审计方式
        expressions.push({
          dataType: 'str',
          name: 'auditMode',
          op: 'like',
          stringValue: `%${value}%`,
        })
        this.tableExpressions.push({
          dataType: 'exps',
          op: 'or',
          expressionsValue: expressions,
        })
      }
      this.$refs.dataTable.clearSelection()
    },
    searchedClick() {
      this.isShowAdvSearch = !this.isShowAdvSearch
      this.$refs.dataTable.clearSelection()
    },
    advSearch() {
      this.tableExpressions = []
      // 计划年度
      this.tableExpressions.push({
        dataType: 'str',
        name: 'planYear',
        op: 'like',
        stringValue: `${this.searchYear}`,
      })
      let isMyParticipateValue
      if (this.checkboxValue) {
        isMyParticipateValue = '1'
      } else {
        isMyParticipateValue = '0'
      }
      // 仅我参与的
      this.tableExpressions.push({
        dataType: 'str',
        name: 'isMyParticipate',
        op: 'eq',
        stringValue: `${isMyParticipateValue}`,
      })
      // 项目名称
      if (this.advSearchForm.projectTitle) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'projectTitle',
          op: 'like',
          stringValue: `${this.advSearchForm.projectTitle}`,
        })
      }
      // 项目编号
      if (this.advSearchForm.projectCode) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'projectCode',
          op: 'like',
          stringValue: `${this.advSearchForm.projectCode}`,
        })
      }
      // 项目组长
      if (this.advSearchForm.groupLeaderName) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'groupLeaderName',
          op: 'like',
          stringValue: `${this.advSearchForm.groupLeaderName}`,
        })
      }
      // 审计方式
      if (this.advSearchForm.auditMode[0]) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'auditMode',
          op: 'like',
          stringValue: `${this.advSearchForm.auditMode[0].id}`,
        })
      }
      // 项目状态
      if (this.advSearchForm.itemStatus[0]) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'itemStatus',
          op: 'like',
          stringValue: `${this.advSearchForm.itemStatus[0].id}`,
        })
      }
      // 审计类型
      if (this.advSearchForm.auditType[0]) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'auditType',
          op: 'like',
          stringValue: `${this.advSearchForm.auditType[0].id}`,
        })
      }
      this.$refs.dataTable.clearSelection()
    },
    linkProject(record) {
      if (
        (record.operatePermission || this.hsaReadAuthorityPermission(record)) &&
        (record.itemStatus === '02' ||
          record.itemStatus === '03' ||
          record.itemStatus === '04' ||
          record.itemStatus === '05' ||
          record.itemStatus === '07')
      ) {
        window.open('#/audit-work/?projectId=' + record.id)
      } else {
        var url = '/audit-project-detail?record=' + record.id
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            return this.$refs.SJXMDataTable.refresh(true)
          }
        })
      }
    },
    // 是否拥有查阅范围权限
    hsaReadAuthorityPermission(record) {
      if (
        record.readAuthorityCodes != null &&
        record.readAuthorityCodes.indexOf(getUserInfo().account) > -1
      ) {
        return true
      }
      return false
    },
    onChange(e) {
      let isMyParticipateValue
      this.tableExpressions = []
      if (e.target.checked) {
        isMyParticipateValue = '1'
      } else {
        isMyParticipateValue = '0'
      }
      // 仅我参与的
      this.tableExpressions.push({
        dataType: 'str',
        name: 'isMyParticipate',
        op: 'eq',
        stringValue: `${isMyParticipateValue}`,
      })
      // 计划年度
      this.tableExpressions.push({
        dataType: 'str',
        name: 'planYear',
        op: 'like',
        stringValue: `%${this.searchYear}%`,
      })

      // 审计机构
      if (this.auditUnit.length > 0) {
        this.tableExpressions.push({
          dataType: 'str',
          name: 'unitName',
          op: 'like',
          stringValue: this.auditUnit[0].name,
        })
      }
      this.$refs.dataTable.clearSelection()
    },
    // 项目组长配置保存
    change(val) {
      let codes = ''
      let names = ''
      if (val.length > 0) {
        val.forEach((e) => {
          codes += e.code + ','
          names += e.name + ','
        })
        codes = codes.substr(0, codes.length - 1)
        names = names.substr(0, names.length - 1)
      }
      if (this.setType === 'groupLeader') {
        return new Promise((resolve) => {
          // 分配项目组长配置
          AuditProjectService.assignTeamLeader(this.projectId, codes, names).then((res) => {
            if (res.data) {
              this.$refs.dataTable.clearSelection()
              this.$refs.dataTable.refresh()
            }
          })
        })
      }
      if (this.setType === 'readAuthority') {
        return new Promise((resolve) => {
          // 设定查阅范围
          AuditProjectService.assignReadAuthority(this.projectId, codes, names).then((res) => {
            if (res.data) {
              this.$refs.dataTable.clearSelection()
              this.$refs.dataTable.refresh()
            }
          })
        })
      }
    },
    AdvSearchClick() {
      this.isShowAdvSearch = !this.isShowAdvSearch
    },
    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: () => {
            this.inited = false
            axios({
              url: `api/xcoa-mobile/v1/iamauditproject/deleteProject`,
              method: 'delete',
              params: {
                ids: selectedRowKeys.join(','),
              },
            })
              .then((res) => {
                this.inited = true
                if (res.data) {
                  const msg = '删除成功'
                  message.success(msg)
                  this.$refs.dataTable.clearSelection()
                  this.$refs.dataTable.refresh()
                } else {
                  message.error('删除失败，请联系管理员！')
                }
              })
              .catch((err) => {
                this.inited = true
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    optbuttonClick(val, record) {
      // 启动项目
      if (val === 'startproject') {
        return new Promise((resolve) => {
          // 项目启动前校验是否有变更申请单
          AuditProjectService.checkBeforeStartProject(record.id).then((res) => {
            if (res.data) {
              Modal.warning({
                title: '提示',
                content: '该项目的《变更申请》未结束!',
              })
              return null
            } else {
              // 启动操作
              const url = '/audit-project-start-form?record=' + record.id // 新页面要打开的路由地址
              crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                if (refreshFlag) {
                  this.$refs.dataTable.clearSelection()
                  this.$refs.dataTable.refresh()
                }
              })
            }
          })
        })
      }
      // 分配项目组长操作 or 设定查阅范围操作
      if (val === 'assignTeamLeader') {
        this.setType = 'groupLeader'
        const jsonArry = []
        if (record.groupLeaderAccount !== '' && record.groupLeaderAccount !== null) {
          if (record.groupLeaderAccount.indexOf(',') > -1) {
            const codes = record.groupLeaderAccount.split(',')
            const names = record.groupLeaderName.split(',')
            for (let i = 0; i < codes.length; i++) {
              jsonArry.push({ type: 'User', code: codes[i], name: names[i], attrs: [] })
            }
          } else {
            jsonArry.push({
              type: 'User',
              code: record.groupLeaderAccount,
              name: record.groupLeaderName,
              attrs: [],
            })
          }
        }
        this.mainSendUnit = jsonArry
        this.projectId = record.id
        setTimeout(() => {
          this.$refs.assignTeamLeader.openPicker()
        }, 0)
      }
      // 设定查阅范围操作
      if (val === 'setReadAuthority') {
        this.setType = 'readAuthority'
        const jsonArry = []
        if (record.readAuthorityCodes !== '' && record.readAuthorityCodes !== null) {
          if (record.readAuthorityCodes.indexOf(',') > -1) {
            const codes = record.readAuthorityCodes.split(',')
            const names = record.readAuthorityNames.split(',')
            for (let i = 0; i < codes.length; i++) {
              jsonArry.push({ type: 'User', code: codes[i], name: names[i], attrs: [] })
            }
          } else {
            jsonArry.push({
              type: 'User',
              code: record.readAuthorityCodes,
              name: record.readAuthorityNames,
              attrs: [],
            })
          }
        }
        this.mainSendUnit = jsonArry
        this.projectId = record.id
        setTimeout(() => {
          this.$refs.assignTeamLeader.openPicker()
        }, 0)
      }
      // 关闭项目
      if (val === 'closeProject') {
        return new Promise((resolve) => {
          // 关闭项目前的校验
          AuditProjectService.checkBeforeCloseProject(record.id).then((res) => {
            if (res.data) {
              Modal.warning({
                title: '提示',
                content: '该项目的《审计报告》未结束!',
              })
              return null
            } else {
              Modal.confirm({
                title: '您确定要关闭该项目吗？',
                content: '关闭该项目后，就无法恢复初始的状态。',
                okText: '关闭',
                okType: 'danger',
                cancelText: '取消',
                onOk: () => {
                  axios({
                    url: `api/xcoa-mobile/v1/iamauditproject/closeProject?id=` + record.id,
                    method: 'get',
                  })
                    .then(() => {
                      const msg = '关闭成功！'
                      message.success(msg)
                      this.$refs.dataTable.clearSelection()
                      this.$refs.dataTable.refresh()
                      // this.writeBackToEvaluation(record.id)
                    })
                    .catch((err) => {
                      const msg = errorUtil.getMessage(err) || '关闭失败'
                      message.error(msg)
                    })
                    .finally(resolve)
                },
                onCancel: () => {
                  resolve()
                },
              })
            }
          })
        })
      }
      // 重启项目
      if (val === 'restart') {
        return new Promise((resolve) => {
          Modal.confirm({
            title: '您确定要重启该项目吗？',
            content: '重启该项目后，就无法恢复初始的状态。',
            okText: '重启',
            okType: 'danger',
            onOk: () => {
              axios({
                url: `api/xcoa-mobile/v1/iamauditproject/restartProject?id=` + record.id,
                method: 'get',
              })
                .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()
            },
          })
        })
      }
      if (val === 'projectArchive') {
        // 项目归档
        AuditProjectService.projectArchive(record.id).then((res) => {
          if (res.data) {
            const url = '/audit-archives-form?record=' + res.data + '&fromFlag=projectList' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.$refs.dataTable.clearSelection()
                this.$refs.dataTable.refresh()
              }
            })
          }
        })
      }
      if (val === 'projectScore') {
        // 项目归档
        const url = '/audit-project-score?record=' + record.id // 新页面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.$refs.dataTable.clearSelection()
            this.$refs.dataTable.refresh()
          }
        })
      }
    },
    // 回写外聘机构考评信息
    writeBackToEvaluation(id) {
      // debugger
      // var id = this.$refs.form.getFieldValue('id')
      if (id && id != null) {
        axios({
          url: `api/xcoa-mobile/v1/iamauditproject/evaluation?id=` + id,
          method: 'get',
        }).then((res) => {
          if (res.status === 200) {
            if (res.data) {
              // this.$refs.form.saveBtnClick()
            }
          }
        })
      } else {
        // this.$refs.form.saveBtnClick()
      }
    },
    changeNum(data) {
      data.forEach((item, index) => {
        item.sortNum = index + 1
      })
    },
    selectedRowsChanged(row) {
      if (row.length > 0) {
        this.deleteButtonDisable = false
      } else {
        this.deleteButtonDisable = true
      }
    },
    // 校验操作权限
    checkPermission(btnPerm, dataPerm) {
      let result = false
      if (dataPerm !== null && dataPerm.includes(',')) {
        const dataPermArry = dataPerm.split(',')
        dataPermArry.forEach((item) => {
          if (btnPerm.includes(item)) {
            result = true
          }
        })
      } else {
        if (dataPerm !== '' && btnPerm.includes(dataPerm)) {
          result = true
        }
      }
      return result
    },
    processReq(req) {
      const url = req.url

      const arr = req.data.expressions

      if (url === 'api/xcoa-mobile/v1/iamauditproject/all-list' && arr.length === 0) {
        arr.push({
          dataType: 'str',
          name: 'planYear',
          op: 'like',
          stringValue: `%${this.searchYear}%`,
        })

        arr.push({
          dataType: 'str',
          name: 'isMyParticipate',
          op: 'eq',
          stringValue: '0',
        })
      }
      return req
    },
  },
}
</script>

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

.project-list-div {
  :global(.ant-col-offset-10) {
    margin-left: 0;
  }
}

.btns {
  position: absolute;
  top: 23px;
  right: 0;
  left: 20px;
  z-index: 100;
  width: calc(100% - 40px);
}

.operatecol {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  float: left;

  :global(.ant-btn-sm) {
    padding: 0 3px;
  }
}

.advSearchBtn {
  width: 35px;
  padding: 0;
  margin-left: -5px;
  border-radius: 0 5px 5px 0;
}

.actionBtn {
  float: right;
  width: auto;

  * {
    vertical-align: middle;
  }
}

.buttonSpacing {
  margin-left: 5px;
}

.search-icon {
  margin-left: 1px !important;
  font-size: 12px;
}
.optbutton {
  font-size: 20px;
}
</style>
