<template>
  <div :class="$style.wrapHeight">
    <a-card :bordered="false">
      <a-tabs v-model="activeKey" type="line" @change="toggleTabs">
        <a-tab-pane key="1" tab="项目计划">
          <!-- 高级搜索区域 -->
          <audit-advanced-query
            :class="$style.advancedQuery"
            :expand="isShowAdvSearch"
            :search-data="SJXMAdvSearchForm"
            :ref-name="searchform"
            :search-style="{ height: '170px', left: '0px', top: '50px' }"
            :search-fun="advSJXMSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="项目名称" prop="projectTitle">
                    <a-input v-model="SJXMAdvSearchForm.projectTitle" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="审计类型" prop="auditType">
                    <sd-select
                      v-model="SJXMAdvSearchForm.auditType"
                      :allow-clear="true"
                      :options="auditTypeOptions"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="审计方式" prop="auditMode">
                    <sd-select
                      v-model="SJXMAdvSearchForm.auditMode"
                      :allow-clear="true"
                      :options="auditModeOptions"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="项目负责人" prop="projectPrincipalName">
                    <a-input v-model="SJXMAdvSearchForm.projectPrincipalName" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="被审计单位" prop="auditedUnitNames">
                    <a-input v-model="SJXMAdvSearchForm.auditedUnitNames" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            ref="SJXMDataTable"
            style="margin-top: 25px"
            :filter-expressions="SJXMTableExpressions"
            :columns="columns1"
            show-selection
            :process-req="processReq"
            form-id="iamAuditProject"
            :data-url="dataurl1"
            :actions="actions1"
          >
            <div slot="isLink" slot-scope="text, record">
              <a :title="text" @click="showProjectDetail(record)">{{ text }}</a>
            </div>
          </sd-data-table-ex>
        </a-tab-pane>
        <a-tab-pane key="2" tab="计划变更">
          <!-- 高级搜索区域 -->
          <audit-advanced-query
            :expand="isShowAdvSearch"
            :search-data="JHBGAdvSearchForm"
            :ref-name="searchform"
            style="z-index: 1000"
            :search-style="{ height: '170px', left: '0px', top: '50px' }"
            :search-fun="advJHBGSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="项目名称" prop="projectTitle">
                    <a-input v-model="JHBGAdvSearchForm.projectTitle" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="变更类型" prop="changeType">
                    <sd-select
                      v-model="JHBGAdvSearchForm.changeType"
                      :options="changeTypeOptions"
                      :allow-clear="true"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="编制人员" prop="creatorName">
                    <a-input v-model="JHBGAdvSearchForm.creatorName" />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item :label="'年\u2003\u2003度'" prop="planYear">
                    <a-input v-model="JHBGAdvSearchForm.planYear" />
                  </a-form-model-item>
                </a-col>
                <!-- <a-col :span="8">
                  <a-form-model-item label="当前状态" prop="flowState">
                    <sd-select
                      v-model="JHBGAdvSearchForm.flowState"
                      :allow-clear="true"
                      :options="flowStateOptions"
                    />
                  </a-form-model-item>
                </a-col> -->
              </a-row>
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            ref="JHBGDataTable"
            style="margin-top: 25px"
            :filter-expressions="JHBGTableExpressions"
            :columns="columns2"
            show-selection
            form-id="iamAuditProjectChange"
            :data-url="dataurl2"
            :actions="actions2"
            @selectedRowsChanged="selectedRowsChanged"
          >
            <div slot="isLink" slot-scope="text, record">
              <a class="part-time">
                <span>
                  <a-spin v-if="pending.includes(record.id)">
                    <a-icon slot="indicator" type="loading" :class="$style.submitStatus" />
                  </a-spin>
                  <a-icon
                    v-if="batchSubmitSucceed.includes(record.id)"
                    type="check-circle"
                    :class="[$style.submitStatus, $style.success]"
                  />
                  <a-tooltip
                    v-if="batchsubmitFailed.map((item) => item.id).includes(record.id)"
                    :title="batchsubmitFailed.find((item) => item.id === record.id).message"
                  >
                    <a-icon type="close-circle" :class="[$style.submitStatus, $style.error]" />
                  </a-tooltip>
                </span>
              </a>
              <a :title="text" @click="showFlowFormDetail(record)">{{ text }}</a>
            </div>
          </sd-data-table-ex>
        </a-tab-pane>
        <a-tab-pane key="3" tab="审计计划">
          <!-- 高级搜索区域 -->
          <audit-advanced-query
            :expand="isShowAdvSearch"
            :search-data="SJJHAdvSearchForm"
            :ref-name="searchform"
            style="z-index: 1000"
            :search-style="{ height: '170px', left: '0px', top: '50px' }"
            :search-fun="advSJJHSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="计划年度" prop="planYear">
                    <a-input v-model="SJJHAdvSearchForm.planYear" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="审计机构" prop="unitName">
                    <a-input v-model="SJJHAdvSearchForm.unitName" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="编制人员" prop="creatorName">
                    <a-input v-model="SJJHAdvSearchForm.creatorName" />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <!-- <a-row>
                <a-col :span="8">
                  <a-form-model-item label="当前状态" prop="flowState">
                    <sd-select
                      v-model="SJJHAdvSearchForm.flowState"
                      :allow-clear="true"
                      :options="flowStateOptions"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row> -->
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            ref="SJJHDataTable"
            style="margin-top: 25px"
            :filter-expressions="SJJHTableExpressions"
            :columns="columns3"
            show-selection
            form-id="iamAuditPlan"
            :data-url="dataurl3"
            :actions="actions3"
            @selectedRowsChanged="selectedRowsChanged"
          >
            <div slot="isLink" slot-scope="text, record">
              <a :title="text" @click="showFlowFormDetail(record)">{{ text }}</a>
            </div>
          </sd-data-table-ex>
        </a-tab-pane>
      </a-tabs>
      <div :class="[$style.btns]">
        <a-select
          v-if="activeKey === '1'"
          v-model="searchYear"
          style="z-index: 100; width: 80px; margin-top: -30px; margin-right: 10px"
          @change="changeYearSelect"
        >
          <a-select-option v-for="year in yearArry" :key="year">
            {{ year }}
          </a-select-option>
        </a-select>
        <a-radio-group
          v-if="activeKey !== '1'"
          v-model="radioValue"
          allow-clear
          @change="radioOnChange"
        >
          <a-radio :value="1"> 全部 </a-radio>
          <a-radio :value="2"> 待处理 </a-radio>
        </a-radio-group>
        <a-input-search
          v-model="searchValue"
          style="width: 155px; vertical-align: bottom"
          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="activeKey === '1' && isCreateProject"
          type="primary"
          :class="[$style.buttonSpacing]"
          @click="createProject"
          >新建项目
        </a-button>
        <a-button
          v-if="activeKey !== '2' && isApplicationAdmin"
          type="primary"
          :class="[$style.buttonSpacing]"
          @click="createAuditPlan"
          >新建审计计划
        </a-button>
        <a-button v-if="false" type="primary" :class="[$style.buttonSpacing]" @click="batchSubmit"
          >批量提交
        </a-button>
        <a-button
          v-if="activeKey === '2' || (activeKey === '3' && isApplicationAdmin)"
          :class="[$style.buttonSpacing]"
          :disabled="deleteButtonDisable"
          @click="linkToDelete"
          >删除
        </a-button>
        <a-button
          v-if="activeKey === '1'"
          :class="[$style.buttonSpacing]"
          :loading="exportLoading"
          @click="fnexport"
          >导出
        </a-button>
        <audit-advanced-export
          ref="export"
          :v-if="false"
          :class-style="[$style.buttonSpacing]"
          :exclebxh="false"
          table-id="SJXMDataTable"
          :expressions="SJXMTableExpressions"
          :config-id="13"
        />
      </div>
      <a-modal
        :destroy-on-close="true"
        title="填写意见"
        :body-style="{ overflow: 'auto' }"
        :width="600"
        :visible="showOpinionModal"
        :wrap-class-name="$style.opinionModel"
        @ok="handleOkSubmit"
        @cancel="handleCancelSubmit"
      >
        <sd-opinion-model
          ref="opinionModel"
          v-model="form.opinion"
          :group-id="form.groupId"
          :cyy-popup-container="cyyPopupContainer"
        />
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import download from '@/common/services/download'
import { Message, message, Modal } from 'ant-design-vue'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedExport from '../../components/audit-advanced-export.vue'
import AuditService from './audit-service'
import components from './_import-components/audit-plan-list-import'
import TableColumnTypes from '@/common/services/table-column-types'
import sdOpinionModel from '@/webflow/sd-opinion-model.vue'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import storeMixin, { getUserInfo } from '@/common/store-mixin'
import FlowService from '@/webflow/flow-service'

export default {
  name: 'AuditPlanList',
  metaInfo: {
    title: '项目计划',
  },
  components: { ...components, auditAdvancedQuery, auditAdvancedExport, sdOpinionModel },
  mixins: [storeMixin, auditAdvancedQueryMixins],
  data() {
    return {
      exportLoading: false,
      activeKey: '1',
      searchYear: new Date().getFullYear().toString(),
      yearArry: [],
      radioValue: 1,
      searchValue: '',
      deleteButtonDisable: true,
      searchform: 'searchform',
      isShowAdvSearch: false,
      isCreateProject: true,
      SJXMAdvSearchForm: {
        projectTitle: '',
        projectCode: '',
        auditType: '',
        auditMode: '',
        projectPrincipalName: '',
        auditedUnitNames: '',
      },
      JHBGAdvSearchForm: {
        projectTitle: null,
        changeType: '',
        creatorName: '',
        planYear: '',
        flowState: '',
      },
      SJJHAdvSearchForm: {
        planYear: null,
        unitName: '',
        creatorName: '',
        flowState: '',
      },
      SJXMTableExpressions: [],
      JHBGTableExpressions: [],
      SJJHTableExpressions: [],
      pageId: 'audit/plan/iamAuditPlan',
      dataurl1: 'api/xcoa-mobile/v1/iamauditproject/all-list',
      dataurl2: 'api/xcoa-mobile/v1/iamauditprojectchange/all-list',
      dataurl3: 'api/xcoa-mobile/v1/iamauditplan/all-list',
      columns1: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectTitle',
          width: '30%',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '项目编号',
          dataIndex: 'projectCode',
          defaultSortOrder: 'descend',
          sortDirections: 'descend',
          width: '10%',
        },
        {
          title: '审计类型',
          dataIndex: 'auditType',
          width: '120px',
          sorter: true,
        },
        // {
        //   title: '项目负责人',
        //   dataIndex: 'projectPrincipalName',
        //   sorter: true,
        //   width: '260px',
        // },
        {
          title: '项目来源',
          dataIndex: 'isPlanIn',
          sorter: true,
          width: '80px',
        },
        {
          title: '审计方式',
          dataIndex: 'auditMode',
          sorter: true,
          width: '80px',
          sdHidden: true,
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnitNames',
          width: '15%',
        },
        {
          title: '操作',
          dataIndex: 'opt',
          aligen: 'center',
          width: '120px',
          customRender: (text, record, index) => {
            if (
              record.operateCloumnPermission &&
              (record.flowState === '结束' || record.flowState === null)
            ) {
              // 只有我发起变更操作或者发起后流程结束的项目才有此操作
              if (record.itemStatus === '01') {
                // 只有未启动的项目才可以进行编辑
                return (
                  <span>
                    <a vOn:click={(evt) => this.editProject(record.id)}>编辑</a>{' '}
                    <a vOn:click={(evt) => this.cancelProject(record.id)}>取消</a>
                  </span>
                )
              } else if (record.itemStatus !== '06') {
                return (
                  <span>
                    <a vOn:click={(evt) => this.cancelProject(record.id)}>取消</a>
                  </span>
                )
              }
            } else {
              return <span>&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&nbsp;</span>
            }
          },
        },
      ],
      actions1: [],
      columns2: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '项目名称',
          width: '25%',
          dataIndex: 'projectTitle',
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '项目编号',
          dataIndex: 'projectCode',
          width: '10%',
        },
        {
          title: '变更类型',
          dataIndex: 'changeType',
          sorter: true,
          width: '120px',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          sorter: true,
          width: '120px',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '当前状态',
          sorter: true,
          dataIndex: 'flowState',
        },
        {
          title: '当前处理人',
          dataIndex: 'creatorName',
        },
      ],
      actions2: [],
      columns3: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '计划年度',
          dataIndex: 'planYear',
          sorter: true,
          scopedSlots: { customRender: 'isLink' },
        },
        {
          title: '审计机构',
          sorter: true,
          dataIndex: 'unitName',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '当前状态',
          sorter: true,
          dataIndex: 'flowState',
        },
        {
          title: '结束发布标记',
          hidden: true,
          sorter: true,
          dataIndex: 'endType',
          sdHidden: true,
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
      ],
      actions3: [],
      formId: 'iamAuditProject',
      tableId: 'SJXMDataTable',
      itemStatusOptions: [],
      auditTypeOptions: [],
      auditModeOptions: [],
      changeTypeOptions: [],
      showOpinionModal: false,
      pending: [],
      batchSubmitSucceed: [],
      batchsubmitFailed: [],
      form: {
        opinion: '',
        groupId: '',
      },
      isApplicationAdmin: false, // 是否为审计计划管理员
      flowStateOptions: [
        {
          id: '起草',
          name: '起草',
        },
        {
          id: '审计部领导审批',
          name: '审计部领导审批',
        },
        {
          id: '结束',
          name: '结束',
        },
      ],
    }
  },
  mounted() {
    // 初始化年份下拉框
    this.initYearSelect()
    // 初始化数据字典信息
    this.initDictionaryInfo()
    // 初始化权限
    this.initJurisdiction()
  },
  methods: {
    // 初始化年份下拉框
    initYearSelect() {
      AuditService.getPlanYear().then((res) => {
        this.yearArry = []
        // 获取计划年度
        if (res.data != null && res.data !== '') {
          let flag = true
          res.data.forEach((e) => {
            this.yearArry.push(e)
            if (e === this.searchYear) {
              flag = false
            }
          })
          this.yearArry = this.yearArry.sort().reverse()
          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.changeYearSelect(this.searchYear)
          }
        } else {
          // 如果没有已经发布的计划，则显示当前年份
          this.isCreateProject = false
          this.yearArry.push(this.searchYear)
        }
      })
    },
    initDictionaryInfo() {
      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
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PRODUCT_IAM_CHANGE_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.changeTypeOptions = res.data
        }
      })
    },
    // 初始化权限
    initJurisdiction() {
      // 校验权限（检查为审计计划管理员、审计人员）
      AuditService.checkPermission().then((res) => {
        this.isApplicationAdmin = res.data.isHasPermission // 删除按钮权限（拥有计划管理员角色）
      })
    },
    // 创建审计计划
    createAuditPlan() {
      const url = '/sd-flow-guide?code=PRODUCT_IAM_SJJH' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    // 编辑项目
    editProject(id) {
      // 校验项目是否已启动
      AuditService.checkProjectIsStart(id).then((res) => {
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '该项目已启动!',
          })
          return null
        } else {
          const url =
            `/sd-flow-guide?code=PRODUCT_IAM_SJJHBG&oper=edit&projectId=${id}&planYear=` +
            this.searchYear // 新页面要打开的路由地址
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              // 这里写或者调刷新的方法
              this.refreshDataTable()
            }
          })
        }
      })
    },
    // 批量提交
    batchSubmit() {
      this.showOpinionModal = true
      this.getGroupCode()
    },
    // 取消项目
    cancelProject(id) {
      const url =
        `/sd-flow-guide?code=PRODUCT_IAM_SJJHBG&oper=cancel&projectId=${id}&planYear=` +
        this.searchYear // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    // 创建项目
    createProject() {
      // 判断能不能新建项目
      if (this.searchYear !== undefined) {
        // AuditService.existYearPlan('', this.searchYear, '').then((res) => {
        // if (res.data &&res.data === true) {
        AuditService.getPlanByPlanYear(this.searchYear).then((res) => {
          if (res.data) {
            const url =
              '/sd-flow-guide?code=PRODUCT_IAM_SJJHBG&oper=create&planYear=' + this.searchYear // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refreshDataTable()
              }
            })
          } else {
            Modal.warning({
              title: '提示',
              content: '请先维护本单位审计计划并发布',
            })
          }
        })
      } else {
        Modal.warning({
          title: '提示',
          content: '请先选择计划年度！',
        })
      }
    },
    refreshDataTable() {
      if (this.activeKey === '1') {
        this.tableId = 'SJXMDataTable'
      }
      if (this.activeKey === '2') {
        this.tableId = 'JHBGDataTable'
      }
      if (this.activeKey === '3') {
        this.tableId = 'SJJHDataTable'
      }
      if (this.$refs[`${this.tableId}`]) {
        this.$refs[`${this.tableId}`].clearSelection()
        this.$refs[`${this.tableId}`].refresh()
      }
    },
    toggleTabs(key) {
      this.activeKey = key
      if (this.activeKey === '1') {
        this.tableId = 'SJXMDataTable'
        this.SJXMTableExpressions = []
      }
      if (this.activeKey === '2') {
        this.tableId = 'JHBGDataTable'
        this.JHBGTableExpressions = []
        if (this.radioValue === 1) {
          this.JHBGTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: true,
          })
        } else if (this.radioValue === 2) {
          this.JHBGTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: false,
          })
        }
      }
      if (this.activeKey === '3') {
        this.tableId = 'SJJHDataTable'
        this.SJJHTableExpressions = []
        if (this.radioValue === 1) {
          this.SJJHTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: true,
          })
        } else if (this.radioValue === 2) {
          this.SJJHTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: false,
          })
        }
      }
      this.deleteButtonDisable = true
      if (this.$refs[`${this.tableId}`]) {
        this.$refs[`${this.tableId}`].clearSelection()
      }
    },
    linkToDelete() {
      if (this.activeKey === '1') {
        this.tableId = 'SJXMDataTable'
        this.formId = 'iamAuditProject'
      }
      if (this.activeKey === '2') {
        this.tableId = 'JHBGDataTable'
        this.formId = 'iamAuditProjectChange'
      }
      if (this.activeKey === '3') {
        this.tableId = 'SJJHDataTable'
        this.formId = 'iamAuditPlan'
      }
      const selectedRowKeys = this.$refs[`${this.tableId}`].getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }
      if (this.activeKey === '2') {
        // 计划变更删除
        if (this.checkStateDelete('0', '只能删除起草状态的计划变更！')) {
          this.deleteMethod(selectedRowKeys)
        }
      } else if (this.activeKey === '3') {
        // 计划删除
        // 删除是否为本单位校验
        if (this.checkDeptDelete()) {
          // 删除是否为起草状态校验
          if (this.checkStateDelete('0,5', '只能删除起草、结束状态的审计计划')) {
            AuditService.beforeDeleteCheck(selectedRowKeys).then((res) => {
              // 删除前校验
              if (res.data) {
                Modal.warning({
                  title: '提示',
                  content: '该计划存在已启动/已取消/已关闭/已归档项目，请先删除该项目！',
                })
                return null
              } else {
                this.deleteMethod(selectedRowKeys)
              }
            })
          }
        }
      } else {
        this.deleteMethod(selectedRowKeys)
      }
    },
    // 删除记录
    deleteMethod(selectedRowKeys) {
      let url
      if (this.activeKey === '2') {
        url = 'api/xcoa-mobile/v1/iamauditprojectchange/deleteProjectChange'
      } else {
        url = 'api/xcoa-mobile/v1/page/' + this.formId
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          cancelText: '取消',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            axios({
              url: url,
              method: 'delete',
              params: {
                ids: selectedRowKeys.join(','),
              },
            })
              .then(() => {
                const msg = '删除成功'
                message.success(msg)
                this.$refs[`${this.tableId}`].clearSelection()
                this.$refs[`${this.tableId}`].refresh()
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    // 删除是否为本单位校验
    checkDeptDelete() {
      let temp = false
      const selectedRows = this.$refs[`${this.tableId}`].getSelectedRows()
      selectedRows.some((item) => {
        if (!item.hasOperateAuthority) {
          temp = true
          return true
        }
      })
      if (temp) {
        Modal.warning({
          title: '提示',
          content: '只能删除本单位的审计计划！',
        })
        return false
      }
      return true
    },
    // 删除是否为起草状态校验
    checkStateDelete(state, message) {
      let temp = false
      const selectedRows = this.$refs[`${this.tableId}`].getSelectedRows()
      selectedRows.some((item) => {
        // if (item.flowState !== '起草') {
        if (!state.includes(item.endType)) {
          temp = true
          return true
        }
      })
      if (temp) {
        Modal.warning({
          title: '提示',
          content: message,
        })
        return false
      }
      return true
    },
    AdvSearchClick() {
      this.isShowAdvSearch = !this.isShowAdvSearch
    },
    searchedClick() {
      this.isShowAdvSearch = !this.isShowAdvSearch
    },
    changeYearSelect(value) {
      if (this.activeKey === '1') {
        this.SJXMTableExpressions = []
        if (value) {
          // 计划年度
          this.SJXMTableExpressions.push({
            dataType: 'str',
            name: 'planYear',
            op: 'like',
            stringValue: `${value}`,
          })
          // 项目状态不是'取消'
          // this.SJXMTableExpressions.push({
          //   dataType: 'str',
          //   name: 'itemStatus',
          //   op: 'ne',
          //   stringValue: '06',
          // })
        }
      }
    },
    onSearch(value) {
      if (this.activeKey === '1') {
        this.SJXMTableExpressions = []
        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: 'projectPrincipalName',
            op: 'like',
            stringValue: `%${value}%`,
          })
          // 审计方式
          // expressions.push({
          //   dataType: 'str',
          //   name: 'auditMode',
          //   op: 'like',
          //   stringValue: `%${value}%`,
          // })
          // 被审计单位
          expressions.push({
            dataType: 'str',
            name: 'auditedUnitNames',
            op: 'like',
            stringValue: `%${value}%`,
          })
          this.SJXMTableExpressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: expressions,
          })
        }
      }
      if (this.activeKey === '2') {
        this.JHBGTableExpressions = []
        if (this.radioValue === 1) {
          this.JHBGTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: true,
          })
        } else if (this.radioValue === 2) {
          this.JHBGTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: false,
          })
        }
        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: 'changeType',
            op: 'like',
            stringValue: `%${value}%`,
          })
          // 编制人员
          expressions.push({
            dataType: 'str',
            name: 'creatorName',
            op: 'like',
            stringValue: `%${value}%`,
          })
          // 编制日期
          expressions.push({
            dataType: 'long',
            name: 'creationTime',
            op: 'eq',
            longValue: moment(moment(value, 'YYYY-MM-DD HH:mm:SS')).valueOf(),
          })
          // 当前状态
          // expressions.push({
          //   dataType: 'str',
          //   name: 'flowState',
          //   op: 'like',
          //   stringValue: `%${value}%`,
          // })
          // 当前处理人
          expressions.push({
            dataType: 'str',
            name: 'currentUser',
            op: 'like',
            stringValue: `%${value}%`,
          })
          this.JHBGTableExpressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: expressions,
          })
        }
      }
      if (this.activeKey === '3') {
        this.SJJHTableExpressions = []
        if (this.radioValue === 1) {
          this.SJJHTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: true,
          })
        } else if (this.radioValue === 2) {
          this.SJJHTableExpressions.push({
            dataType: 'boolean',
            name: 'stateFlag',
            booleanValue: false,
          })
        }
        if (value) {
          const expressions = []
          // 计划年度
          expressions.push({
            dataType: 'str',
            name: 'planYear',
            op: 'eq',
            stringValue: value,
          })
          // 审计机构
          expressions.push({
            dataType: 'str',
            name: 'unitName',
            op: 'like',
            stringValue: `%${value}%`,
          })
          // 编制人员
          expressions.push({
            dataType: 'str',
            name: 'creatorName',
            op: 'like',
            stringValue: `%${value}%`,
          })
          // 编制日期
          expressions.push({
            dataType: 'long',
            name: 'creationTime',
            op: 'eq',
            longValue: moment(moment(value, 'YYYY-MM-DD HH:mm:SS')).valueOf(),
          })
          // 当前状态
          // expressions.push({
          //   dataType: 'str',
          //   name: 'flowState',
          //   op: 'like',
          //   stringValue: `%${value}%`,
          // })
          // 当前处理人
          // expressions.push({
          //   dataType: 'str',
          //   name: 'currentUser',
          //   op: 'like',
          //   stringValue: `%${value}%`,
          // })
          this.SJJHTableExpressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: expressions,
          })
        }
      }
      this.$refs[`${this.tableId}`].clearSelection()
    },
    advSJXMSearch() {
      this.SJXMTableExpressions = []
      // 计划年度
      this.SJXMTableExpressions.push({
        dataType: 'str',
        name: 'planYear',
        op: 'like',
        stringValue: `${this.searchYear}`,
      })
      // 项目状态不是'取消'
      // this.SJXMTableExpressions.push({
      //   dataType: 'str',
      //   name: 'itemStatus',
      //   op: 'ne',
      //   stringValue: '06',
      // })
      // 项目名称
      if (this.SJXMAdvSearchForm.projectTitle) {
        this.SJXMTableExpressions.push({
          dataType: 'str',
          name: 'projectTitle',
          op: 'like',
          stringValue: `${this.SJXMAdvSearchForm.projectTitle}`,
        })
      }
      // 项目编号
      if (this.SJXMAdvSearchForm.projectCode) {
        this.SJXMTableExpressions.push({
          dataType: 'str',
          name: 'projectCode',
          op: 'like',
          stringValue: `${this.SJXMAdvSearchForm.projectCode}`,
        })
      }
      // 审计类型
      if (this.SJXMAdvSearchForm.auditType[0]) {
        this.SJXMTableExpressions.push({
          dataType: 'str',
          name: 'auditType',
          op: 'like',
          stringValue: `${this.SJXMAdvSearchForm.auditType[0].id}`,
        })
      }
      // 审计方式
      if (this.SJXMAdvSearchForm.auditMode[0]) {
        this.SJXMTableExpressions.push({
          dataType: 'str',
          name: 'auditMode',
          op: 'like',
          stringValue: `${this.SJXMAdvSearchForm.auditMode[0].id}`,
        })
      }
      // 项目负责人
      if (this.SJXMAdvSearchForm.projectPrincipalName) {
        this.SJXMTableExpressions.push({
          dataType: 'str',
          name: 'projectPrincipalName',
          op: 'like',
          stringValue: `${this.SJXMAdvSearchForm.projectPrincipalName}`,
        })
      }
      // 被审计单位
      if (this.SJXMAdvSearchForm.auditedUnitNames) {
        this.SJXMTableExpressions.push({
          dataType: 'str',
          name: 'auditedUnitNames',
          op: 'like',
          stringValue: `${this.SJXMAdvSearchForm.auditedUnitNames}`,
        })
      }
      this.$refs[`${this.tableId}`].clearSelection()
    },
    advJHBGSearch() {
      this.JHBGTableExpressions = []
      if (this.radioValue === 1) {
        this.JHBGTableExpressions.push({
          dataType: 'boolean',
          name: 'stateFlag',
          booleanValue: true,
        })
      } else if (this.radioValue === 2) {
        this.JHBGTableExpressions.push({
          dataType: 'boolean',
          name: 'stateFlag',
          booleanValue: false,
        })
      }
      // 项目名称
      if (this.JHBGAdvSearchForm.projectTitle) {
        this.JHBGTableExpressions.push({
          dataType: 'str',
          name: 'projectTitle',
          op: 'like',
          stringValue: `${this.JHBGAdvSearchForm.projectTitle}`,
        })
      }
      // 变更类型
      if (this.JHBGAdvSearchForm.changeType[0]) {
        this.JHBGTableExpressions.push({
          dataType: 'str',
          name: 'changeType',
          op: 'like',
          stringValue: `${this.JHBGAdvSearchForm.changeType[0].id}`,
        })
      }
      // 编制人员
      if (this.JHBGAdvSearchForm.creatorName) {
        this.JHBGTableExpressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `${this.JHBGAdvSearchForm.creatorName}`,
        })
      }
      // 年度
      if (this.JHBGAdvSearchForm.planYear) {
        this.JHBGTableExpressions.push({
          dataType: 'str',
          name: 'planYear',
          op: 'like',
          stringValue: `${this.JHBGAdvSearchForm.planYear}`,
        })
      }
      // 当前状态
      // if (this.JHBGAdvSearchForm.flowState[0]) {
      //   this.JHBGTableExpressions.push({
      //     dataType: 'str',
      //     name: 'flowState',
      //     op: 'like',
      //     stringValue: `${this.JHBGAdvSearchForm.flowState[0].id}`,
      //   })
      // }
      this.$refs[`${this.tableId}`].clearSelection()
    },
    advSJJHSearch() {
      this.SJJHTableExpressions = []
      if (this.radioValue === 1) {
        this.SJJHTableExpressions.push({
          dataType: 'boolean',
          name: 'stateFlag',
          booleanValue: true,
        })
      } else if (this.radioValue === 2) {
        this.SJJHTableExpressions.push({
          dataType: 'boolean',
          name: 'stateFlag',
          booleanValue: false,
        })
      }
      // 计划年度
      if (this.SJJHAdvSearchForm.planYear) {
        this.SJJHTableExpressions.push({
          dataType: 'str',
          name: 'planYear',
          op: 'like',
          stringValue: this.SJJHAdvSearchForm.planYear,
        })
      }
      // 审计机构
      if (this.SJJHAdvSearchForm.unitName) {
        this.SJJHTableExpressions.push({
          dataType: 'str',
          name: 'unitName',
          op: 'like',
          stringValue: `${this.SJJHAdvSearchForm.unitName}`,
        })
      }
      // 编制人员
      if (this.SJJHAdvSearchForm.creatorName) {
        this.SJJHTableExpressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `${this.SJJHAdvSearchForm.creatorName}`,
        })
      }
      // 当前状态
      // if (this.SJJHAdvSearchForm.flowState[0]) {
      //   this.SJJHTableExpressions.push({
      //     dataType: 'str',
      //     name: 'flowState',
      //     op: 'like',
      //     stringValue: `${this.SJJHAdvSearchForm.flowState[0].id}`,
      //   })
      // }
      this.$refs[`${this.tableId}`].clearSelection()
    },
    showProjectDetail(record) {
      var url = '/audit-project-detail?record=' + record.id
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    showFlowFormDetail(record) {
      if (
        (this.activeKey === '2' && (record.flowState === '起草') | (record.flowState === '开始')) ||
        (this.activeKey === '3' &&
          (record.flowState === '起草') | (record.flowState === '开始') &&
          record.hasOperateAuthority)
      ) {
        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)
      }
    },
    radioOnChange(e) {
      if (this.selectedType !== e.target.value) {
        if (this.activeKey === '2') {
          this.JHBGTableExpressions = []
          this.selectedType = e.target.value
          if (e.target.value === 1) {
            this.JHBGTableExpressions.push({
              dataType: 'boolean',
              name: 'stateFlag',
              booleanValue: true,
            })
          } else if (e.target.value === 2) {
            const userInfo = getUserInfo()
            this.JHBGTableExpressions.push({
              dataType: 'boolean',
              name: 'stateFlag',
              booleanValue: false,
            })
            this.JHBGTableExpressions.push({
              dataType: 'str',
              name: 'currentUser',
              op: 'like',
              stringValue: `%${userInfo.name}%`,
            })
          }
        } else {
          this.SJJHTableExpressions = []
          this.selectedType = e.target.value
          if (e.target.value === 1) {
            this.SJJHTableExpressions.push({
              dataType: 'boolean',
              name: 'stateFlag',
              booleanValue: true,
            })
          } else if (e.target.value === 2) {
            this.SJJHTableExpressions.push({
              dataType: 'boolean',
              name: 'stateFlag',
              booleanValue: false,
            })
          }
        }
      }
      this.$refs[`${this.tableId}`].clearSelection()
    },
    // 标题格式化
    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
      }
    },
    getGroupCode() {
      // 获取groupId
      FlowService.getGroupCode().then((res) => {
        if (res.status === 200) {
          if (res.data) {
            this.form.groupId = res.data.toString()
          } else {
            Message.error('获取groupId失败')
          }
        } else {
          Message.error(res.statusText)
        }
      })
    },
    handleOkSubmit() {
      this.showOpinionModal = false
      this.pending = []
      this.batchSubmitSucceed = []
      this.batchsubmitFailed = []
      const selectedRows = this.$refs.JHBGDataTable.getSelectedRows()
      selectedRows.forEach((record) => {
        const id = record.id
        this.pending.push(id)
        const params = {
          id,
          opinion: this.form.opinion,
          attachment: this.form.groupId,
        }
        const srcTrustId = record.srcTrustId
        AuditService.projectChangeBatchSubmit(params, srcTrustId).then((res) => {
          // 批量提交
          if (res.code === '1') {
            this.batchSubmitSucceed.push(id)
          } else {
            this.batchsubmitFailed.push({ id: id, ...res })
          }
          const index = this.pending.findIndex((item) => item === id)
          this.pending.splice(index, 1)
          // 所有的都处理完刷新列表
          if (
            this.batchSubmitSucceed.length + this.batchsubmitFailed.length ===
            selectedRows.length
          ) {
            this.$refs.JHBGDataTable.refresh()
            this.$refs.JHBGDataTable.clearSelection()
          }
        })
      })
    },
    handleCancelSubmit() {
      this.showOpinionModal = false
      this.form.opinion = ''
      this.form.groupId = ''
    },
    cyyPopupContainer() {
      return document.body
    },
    processReq(req) {
      const url = req.url
      const arr = req.data.expressions
      if (url === 'api/xcoa-mobile/v1/iamauditproject/all-list') {
        arr.push({
          dataType: 'str',
          name: 'planYear',
          op: 'like',
          stringValue: `${this.searchYear}`,
        })
        // arr.push({
        //   dataType: 'str',
        //   name: 'itemStatus',
        //   op: 'ne',
        //   stringValue: '06',
        // })
      }
      return req
    },
    selectedRowsChanged(row) {
      if (row.length > 0) {
        this.deleteButtonDisable = false
      } else {
        this.deleteButtonDisable = true
      }
    },
    // 导出
    fnexport() {
      this.exportLoading = true
      // 计划年度
      // this.SJXMTableExpressions.push({
      //   dataType: 'str',
      //   name: 'planYear',
      //   op: 'like',
      //   stringValue: `%${this.searchYear}%`,
      // })
      // 项目状态不是'取消'
      // this.SJXMTableExpressions.push({
      //   dataType: 'str',
      //   name: 'itemStatus',
      //   op: 'ne',
      //   stringValue: '06',
      // })
      // this.$refs.export.exportdata()
      const conditions = { configId: '13', year: this.searchYear }
      axios({
        url: 'api/xcoa-mobile/v1/iamauditproject/exportPaper',
        method: 'post',
        data: conditions,
        responseType: 'blob',
      }).then((res) => {
        if (res.status === 200) {
          const url = URL.createObjectURL(res.data)
          const filename = res.headers['content-disposition']
          const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
          download(url, decodeURI(fname))
        }
      })
      setTimeout(() => {
        this.exportLoading = false
      }, 1000)
    },
  },
}
</script>

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

.wrap-height {
  :global(.ant-col-offset-10) {
    margin-left: 0;
  }
}

.btns {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 100;
}

.buttonSpacing {
  margin-left: 5px;
}

.advancedQuery {
  :global(.ant-col .ant-form-item-label) {
    width: 30% !important;
  }

  :global(.ant-col .ant-form-item-control-wrapper) {
    width: 60% !important;
  }
}

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

.search-icon {
  margin-left: 1px !important;
  font-size: 12px;
}

.wrap-height {
  .success {
    color: $alert-success-icon-color;
  }

  .error {
    color: $alert-error-icon-color;
  }

  :global(.part-time) {
    padding-right: 5px !important;
  }
}
</style>
