<template>
  <div :class="$style.odrForm">
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      @actionBtnClick="actionBtnClick"
      @saveproject="saveproject"
      @afterDispatch="afterDispatch"
    >
      <template v-slot:form="{ model, fields }">
        <table>
          <tr>
            <td style="border: none">
              <audit-advanced-group
                :expand="planExpand"
                :expand-str="'planExpand'"
                :group-label="'计划信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="planExpand">
          <tr v-show="initData(model)">
            <!-- ID -->
            <sd-form-item-td name="id" />
            <!-- 随机ID -->
            <sd-form-item-td name="randomId" />
            <!-- 标题 -->
            <sd-form-item-td name="title" />
            <sd-form-item-td name="unitId" />
            <sd-form-item-td name="unitCode" />
          </tr>
          <tr>
            <!-- 计划年度 -->
            <sd-form-item-td name="planYear">
              <a-select
                v-if="
                  model.iamAuditProjectList === null ||
                  model.iamAuditProjectList === undefined ||
                  model.iamAuditProjectList?.length === 0 ||
                  model.iamAuditProjectList === ''
                "
                v-model="model.planYear"
              >
                <a-select-option v-for="year in yearArry" :key="year + ''">
                  {{ year }}
                </a-select-option>
              </a-select>
              <span v-else>{{ model.planYear }}</span>
            </sd-form-item-td>
            <!-- 审计机构 -->
            <sd-form-item-td name="unitName" />
          </tr>
          <tr>
            <!-- 计划描述 -->
            <sd-form-item-td name="description" :colspan="3">
              <a-textarea v-model="model.description" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 编制日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment
                  v-model="model.attachment"
                  :group-id="JSON.parse(fields.attachment.value).value"
                  :read-only="!editable"
                ></sd-attachment>
              </template>
            </sd-form-item-td>
          </tr>
        </table>

        <a-spin :spinning="!inited" tip="正在导入...">
          <table style="width: 90%; margin: auto; table-layout: fixed">
            <tr :class="$style.lastTr">
              <td :colspan="4">
                <sd-form-item name="iamAuditProjectList" :label="null">
                  <template v-slot:read-and-edit="{ editable }">
                    <audit-advanced-group
                      :expand="expand"
                      :expand-str="'expand'"
                      :group-label="'项目信息'"
                      @changedClick="changedClick"
                    >
                      <template>
                        <template>
                          <div v-show="expand && editable" :class="$style.btnexcel">
                            <a-button type="link" :class="$style.viewSjjh" @click="viewSjjh">
                              <a-icon type="plus-circle" theme="filled" />
                              查看审计计划安排情况
                            </a-button>
                            <a-button
                              type="link"
                              :class="$style.autoprequeue"
                              @click="autoPrequeue"
                            >
                              <a-icon type="plus-circle" theme="filled" />
                              自动预排
                            </a-button>
                            <a-button
                              :loading="importLoading"
                              type="link"
                              :class="$style.batchexcel"
                              @click="batchInport"
                            >
                              <a-icon
                                v-show="!importLoading"
                                type="sd-audit-import"
                                theme="filled"
                              />
                              批量导入
                            </a-button>
                          </div>
                        </template>
                        <sd-child-table
                          :key="childTableKey"
                          ref="tabaData"
                          v-model="model.iamAuditProjectList"
                          :class="$style.projecttable"
                          label="项目信息"
                          :read-only="!editable"
                          :fields="
                            [
                              {
                                caption: '序号',
                                name: 'sortNum',
                                dataType: 'number',
                                attr: {},
                              },
                            ].concat(Array.from(fields.iamAuditProjectList.attr.dync))
                          "
                          :columns="childColumns"
                          :handle-before-add="handleBeforeAdd"
                          @change="changeNum"
                        >
                          <!-- input-form 表示这部分是子表组件的form插槽 -->
                          <template v-slot:form="{ model, fields }">
                            <table :class="$style.iamAuditChildTable">
                              <tr>
                                <sd-form-item-td name="projectTitle"></sd-form-item-td>
                                <sd-form-item-td
                                  v-if="
                                    model.projectCode === '' ||
                                    model.projectCode === null ||
                                    model.projectCode === undefined
                                  "
                                  name="auditType"
                                ></sd-form-item-td>
                                <sd-form-item-td v-else name="auditType">{{
                                  getFormSelectFieldValue('auditType', model.auditType)
                                }}</sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td
                                  label="项目负责人"
                                  name="projectPrincipalId"
                                ></sd-form-item-td>
                                <sd-form-item-td name="projectCode">
                                  <a-input
                                    v-model="model.projectCode"
                                    :disabled="true"
                                    placeholder="系统自动生成"
                                  ></a-input>
                                </sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td
                                  name="auditedUnitIds"
                                  :colspan="3"
                                ></sd-form-item-td>
                                <!-- <sd-form-item-td name="auditBasis"></sd-form-item-td> -->
                              </tr>
                              <tr>
                                <sd-form-item-td name="auditMode"></sd-form-item-td>
                                <sd-form-item-td
                                  v-if="model.auditType === '03' || model.auditType === '04'"
                                  name="auditedUser"
                                ></sd-form-item-td>
                              </tr>
                              <tr>
                                <!-- <sd-form-item-td name="secondAuditDeptPerson"></sd-form-item-td> -->
                                <sd-form-item-td
                                  v-if="model.auditMode === '02'"
                                  name="externalUnitIds"
                                  :colspan="3"
                                >
                                  <template v-slot:read-and-edit="{ editable }">
                                    <AuditGroupPicker
                                      v-if="editable"
                                      v-model="model.externalUnitIds"
                                      :read-only="false"
                                      :selectclick="showselectexternal"
                                    />
                                    <span v-else>{{ model.externalUnitNames }}</span>
                                  </template>
                                </sd-form-item-td>
                              </tr>
                              <!-- <tr>
                                <sd-form-item-td name="whetherFinance" />
                                <sd-form-item-td name="whetherOverseas" />
                              </tr> -->
                              <!-- <tr>
                                <sd-form-item-td name="auditObjective" :colspan="3">
                                  <a-textarea v-model="model.auditObjective" :rows="3" />
                                </sd-form-item-td>
                              </tr> -->
                              <tr>
                                <sd-form-item-td name="projectContent" :colspan="3">
                                  <a-textarea v-model="model.projectContent" :rows="3" />
                                </sd-form-item-td>
                              </tr>
                              <!-- <tr>
                                <sd-form-item-td v-show="false" name="whetherFinance" />
                                <sd-form-item-td v-show="false" name="whetherOverseas" />
                              </tr> -->
                              <tr class="bklabeloverflow">
                                <sd-form-item-td name="whetherAuditCoverage" />
                              </tr>
                              <tr>
                                <sd-form-item-td
                                  name="planStartTime"
                                  @change="getDay(model)"
                                ></sd-form-item-td>
                                <sd-form-item-td
                                  name="planEndTime"
                                  range-after="planStartTime"
                                  @change="getDay(model)"
                                ></sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td name="planDays">
                                  <a-input :v-model="model.planDay"></a-input>
                                </sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td
                                  name="groupLeaderId"
                                  :colspan="3"
                                ></sd-form-item-td>
                                <!-- <sd-form-item-td
                                  name="projectSource"
                                  component="a-select"
                                ></sd-form-item-td> -->
                              </tr>
                              <!-- <tr>
                                <sd-form-item-td name="exPersonnelNum" :input-props="{ min: 0 }">
                                  <a-input-number
                                    v-model="model.exPersonnelNum"
                                    style="width: 100%"
                                  ></a-input-number>
                                </sd-form-item-td>
                                <sd-form-item-td name="predictedCost" :input-props="{ min: 0 }">
                                  <template v-slot:read-and-edit="{ editable }">
                                    <a-input-number
                                      v-if="editable"
                                      v-model="model.predictedCost"
                                      :min="0"
                                      :precision="2"
                                      style="width: 100%"
                                    ></a-input-number>
                                    <span v-else>{{
                                      model.predictedCost === undefined
                                        ? model.predictedCost
                                        : parseFloat(model.predictedCost).toFixed(2)
                                    }}</span>
                                  </template>
                                </sd-form-item-td>
                              </tr> -->
                              <!-- <tr>
                                <sd-form-item-td name="secondAuditDeptPerson" :colspan="3" />
                              </tr> -->
                              <tr>
                                <sd-form-item-td name="attachment" :colspan="3">
                                  <template v-slot:read-and-edit="{ editable }">
                                    <sd-attachment
                                      v-model="model.attachment"
                                      :read-only="editable ? false : true"
                                      :group-id="JSON.parse(fields.attachment.value).value"
                                    />
                                  </template>
                                </sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td name="projectRemarks" :colspan="3">
                                  <a-textarea v-model="model.projectRemarks" :rows="3" />
                                </sd-form-item-td>
                              </tr>
                            </table>
                          </template>
                        </sd-child-table>
                      </template>
                    </audit-advanced-group>
                  </template>
                </sd-form-item>
              </td>
            </tr>
          </table>

          <div :class="[$style.btns]">
            <audit-advanced-import
              ref="import"
              :config-id="'101'"
              :table-id="'list'"
              :relevant-column="planId"
              :class-style="[$style.buttonSpacing]"
              :v-if="false"
              @importfromfileAfter="importfromfileAfter"
              @importfromfileBefore="importfromfileBefore"
              @importHandleCancel="importHandleCancel"
            >
            </audit-advanced-import>
          </div>
        </a-spin>
        <a-modal
          :visible="modalvisible"
          title="请选择"
          width="1200px"
          :body-style="{
            minHeight: '700px',
          }"
          :destroy-on-close="true"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <sd-data-table-ex
            ref="externalTable"
            check-type="checkbox"
            :filter-expressions="expressions"
            :columns="modalcolumns"
            form-id="iamExternalBase"
            page-id="audit/auditsource/extrnal/iamExternalBase"
            :search-fields="['name', 'code', 'address']"
            show-selection
          >
          </sd-data-table-ex>
        </a-modal>

        <a-modal
          :visible="modalviewvisible"
          title="查看审计计划安排情况"
          width="1200px"
          :body-style="{
            minHeight: '700px',
          }"
          :footer="null"
          @cancel="modalviewvisible = false"
        >
          <sd-data-table
            ref="viewsjjh"
            class="auditplanformmodalcksjjh"
            :data-url="'api/xcoa-mobile/v1/iamauditplan/findPlanArrangement'"
            :process-req="processReq"
            row-key="id"
            :process-res="processRes"
            :columns="viewSjjhcolumns3"
            :filter-expressions="[]"
            :pagination="false"
            :defultpagination-pagesize="Number.MAX_VALUE"
          >
            <div slot="jl" slot-scope="text, record">
              <span
                v-if="text === '未覆盖'"
                style="
                  display: flex;
                  width: 80px;
                  padding-left: 16px;
                  color: #fff;
                  text-align: center;
                  background-color: rgb(238, 67, 76);
                  border-radius: 4px;
                "
                :title="text"
                >{{ text }}</span
              >
              <span
                v-if="text === '已安排'"
                style="
                  display: flex;
                  width: 80px;
                  padding-left: 16px;
                  color: #fff;
                  text-align: center;
                  background-color: #178fff;
                  border-radius: 4px;
                "
                :title="text"
                >{{ text }}</span
              >
              <span
                v-if="text === '已覆盖'"
                style="
                  display: flex;
                  width: 80px;
                  padding-left: 16px;
                  color: #fff;
                  text-align: center;
                  background-color: #26c686;
                  border-radius: 4px;
                "
                :title="text"
                >{{ text }}</span
              >
            </div>
            <div slot="unitName" slot-scope="text, record">
              <span style="font-size: 18px" :title="text + '(' + record.gz + ')'">{{ text }}</span
              ><br /><span
                style="font-size: 12px; color: rgb(238, 67, 76)"
                :title="text + '(' + record.gz + ')'"
                >{{ record.gz }}
              </span></div
            >
            <div slot="year" slot-scope="text, record">
              <span v-if="text && text !== ''" :title="text">{{ text }}</span>
            </div>
          </sd-data-table>
        </a-modal>
      </template>
    </sd-webflow>
  </div>
</template>

<script>
import moment from 'moment'
import { Modal, Message } from 'ant-design-vue'
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedImport from '../../components/audit-advanced-import.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import AuditService from './audit-service'
import components from './_import-components/audit-plan-form-import'
import TableColumnTypes from '@/common/services/table-column-types'
import axios from '@/common/services/axios-instance'
// 修改主子表的首行title名
export default {
  name: 'IamPlanForm',
  metaInfo: {
    title: '审计计划信息',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    AuditGroupPicker,
    auditAdvancedImport,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      importLoading: false,
      childTableKey: 0, // 刷新子表组件
      unitIdList: [],
      inited: true,
      planExpand: true,
      expand: true,
      planId: null,
      childColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'auditedUnitIds',
          width: '120px',
          customRender: (text, record, index) => {
            if (record.auditedUnitIds) {
              const array = this.formatterTitle(record.auditedUnitIds, 15)
              return <label title={array[0]}>{array[1]}</label>
            } else {
              return ''
            }
          },
        },
        { dataIndex: 'projectTitle', sorter: true, width: '25%' },
        { dataIndex: 'projectCode', sorter: true, defaultSortOrder: 'ascend', width: '15%' },
        { dataIndex: 'auditType', sorter: true, width: '15%' },
        {
          title: '项目负责人',
          dataIndex: 'projectPrincipalId',
          sorter: true,
          width: '120px',
          sdHidden: true,
        },
        { dataIndex: 'auditMode', sorter: true, width: '120px' },
        { dataIndex: 'externalUnitIds', sdHidden: true },
        { dataIndex: 'auditedUnitNames', sdHidden: true },
        { dataIndex: 'externalUnitCodes', sdHidden: true },
        { dataIndex: 'externalUnitNames', sdHidden: true },
        { dataIndex: 'auditBasis', sdHidden: true },
        { dataIndex: 'auditedUser', sdHidden: true },
        { dataIndex: 'auditObjective', sdHidden: true },
        { dataIndex: 'planStartTime', sdHidden: true },
        { dataIndex: 'planEndTime', sdHidden: true },
        { dataIndex: 'groupLeaderId', sdHidden: true },
        { dataIndex: 'projectSource', sdHidden: true },
        { dataIndex: 'exPersonnelNum', sdHidden: true },
        { dataIndex: 'predictedCost', sdHidden: true },
        { dataIndex: 'attachment', sdHidden: true },
        { dataIndex: 'projectRemarks', sdHidden: true },
        { dataIndex: 'secondAuditDeptPerson', sdHidden: true },
        { dataIndex: 'whetherFinance', sdHidden: true },
        { dataIndex: 'whetherOverseas', sdHidden: true },
        { dataIndex: 'whetherAuditCoverage', sdHidden: true },
        { dataIndex: 'projectContent', sdHidden: true },
        { dataIndex: 'planDays', sdHidden: true },
        { dataIndex: 'id', sdHidden: true },
      ],
      yearArry: [],
      modalvisible: false,
      modalcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          title: '企业名称',
          dataIndex: 'name',
          // sdClickable: true, // 列内容是否可点击
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '类型',
          dataIndex: 'category',
          width: '160px',
        },
        {
          title: '统一社会信用代码',
          dataIndex: 'code',
          width: '180px',
        },
        {
          title: '住所',
          dataIndex: 'address',
          width: '70px',
        },
        {
          title: '企业状态',
          sorter: true,
          dataIndex: 'status',
        },
        {
          title: '当前所参与项目',
          dataIndex: 'joinProject',
          width: '180px',
          scopedSlots: { customRender: 'isProject' },
        },
        {
          title: '编制人员',
          dataIndex: 'authName',
          width: '120px',
        },
        {
          title: '编制日期',
          dataIndex: 'authTime',
          sorter: true,
          defaultSortOrder: 'descend',
          sdRender: TableColumnTypes.date,
        },
      ],
      expressions: [],
      externalUnitIds: [],
      isSave: false, // 是否有保存操作
      orgid: '',
      auditTypeOptions: [],
      modalviewvisible: false,
      viewSjsize: 3,
      viewSjjhcolumns3: [
        {
          title: '单位名称',
          dataIndex: 'unitName',
        },
      ],
      viewSjjhcolumns4: [
        {
          title: '单位名称',
          dataIndex: 'unitName',
        },
      ],
      viewSjyears: [],
    }
  },
  computed: {
    // 计算随机key
    randomId() {
      let randomNum = Math.random()
      while (randomNum === 0) {
        randomNum = Math.random()
      }
      const time = new Date().getTime()
      return time + Math.ceil(randomNum * 1000000000)
    },
  },
  mounted() {
    // 监听关闭事件，关闭时如果没有保存操作且没有id，则直接删除所有子表
    window.addEventListener('beforeunload', (e) => {
      this.beforeunloadHandler(e)
    })
    // 日期下拉框初始化
    this.initDateSelect()
    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
      }
    })
    const groupId = this.$refs.flow.getFieldValue('unitId')
    // axios({
    //   url: 'api/xcoa-mobile/v1/iamauditplan/childGroup?unitCode=' + groupId,
    //   method: 'get',
    // }).then((res) => {
    //   if (res.status === 200) {
    //     this.unitIdList = res.data
    //   }
    // })
  },
  methods: {
    // 控制请求处理
    processReq(req) {
      debugger
      const groupId = this.$refs.flow.getFieldValue('unitId')
      const planYear = this.$refs.flow.getFieldValue('planYear')
      var unitIdArray = []
      var projectNames = []
      const child = this.$refs.flow.getFieldValue('iamAuditProjectList')
      if (child) {
        child.forEach((c) => {
          if (c.whetherAuditCoverage === '1') {
            if (c.auditedUnitIds) {
              JSON.parse(c.auditedUnitIds).forEach((d) => {
                unitIdArray.push(d.code)
              })
            }
            if (c.projectTitle) {
              projectNames.push(c.projectTitle)
            }
          }
        })
      } else {
        unitIdArray = this.unitIdList
      }
      var projectNameArray = []
      if (projectNames !== undefined || projectNames !== null) {
        projectNameArray = projectNames.join(',')
      }
      req.url =
        'api/xcoa-mobile/v1/iamauditplan/findPlanArrangement?groupId=' +
        groupId +
        '&unitIdList=' +
        unitIdArray.join(',') +
        '&year=' +
        planYear +
        '&projectNames=' +
        projectNameArray
      console.log(req)
      return req
    },
    processRes(res) {
      const datas = []
      res.data.forEach((d, index) => {
        const obj = {
          unitName: d['单位名称'],
          jl: d['结论'],
          gz: d['规则'],
          id: index,
        }
        this.viewSjyears.forEach((y) => {
          obj[y] = d[y]
        })
        datas.push(obj)
      })
      this.viewSjsize = res.size
      return { datas: datas, total: res.data?.length }
    },
    getFormSelectFieldValue(name, value) {
      let result = ''
      if (value !== undefined) {
        if (name === 'auditType') {
          const resultArry = this.auditTypeOptions.filter((e) => {
            return e.id === value
          })
          if (resultArry.length > 0) {
            result = resultArry[0].name
          }
        }
        if (name === 'auditMode') {
          const resultArry = this.auditModeOptions.filter((e) => {
            return e.id === value
          })
          if (resultArry.length > 0) {
            result = resultArry[0].name
          }
        }
        if (name === 'auditBasis') {
          const resultArry = this.auditBasisOptions.filter((e) => {
            return e.id === value
          })
          if (resultArry.length > 0) {
            result = resultArry[0].name
          }
        }
        if (name === 'projectSource') {
          const resultArry = this.projectSourceOptions.filter((e) => {
            return e.id === value
          })
          if (resultArry.length > 0) {
            result = resultArry[0].name
          }
        }
      }
      return result
    },
    // 关闭窗口监听
    beforeunloadHandler(e) {
      if (!this.isSave && !this.$refs.flow.getFieldValue('id')) {
        const strid = this.$refs.flow.getFieldValue('iamAuditProjectList').map((item) => {
          return item.id
        })
        if (strid.length > 0) {
          // 删除子表内容，防止垃圾数据
          axios({
            url: `api/xcoa-mobile/v1/iamauditproject/changeProject?planId=${this.planId}&ids=`,
            method: 'get',
          })
        }
      }
    },
    // 保存操作，记录标识位
    saveproject() {
      this.isSave = true
    },
    /**
     * 提交后事件
     */
    afterDispatch() {
      // 提交也认为是保存
      this.isSave = true
    },
    initData(model) {
      // eslint-disable-next-line babel/no-unused-expressions
      this.$refs.flow?.setFieldValue('randomId', this.randomId)
      if (this.$route.params.id !== '0') {
        this.orgid = model.auditOrgId
      } else {
        const params = {
          orgId: model.unitId,
        }
        AuditService.findIamOrgId(params).then((res) => {
          this.orgid = res.data
        })
      }
      return false
    },
    // 日期下拉框初始化
    initDateSelect() {
      const nowYear = new Date().getFullYear()
      this.yearArry.push(nowYear)
      for (let i = 1; i < 6; i++) {
        this.yearArry.push(nowYear - i)
      }
      for (let i = 1; i < 11; i++) {
        this.yearArry.push(nowYear + i)
      }
      this.yearArry.sort()
      if (this.$refs.flow.getFieldValue('planYear') === undefined) {
        this.$refs.flow.setFieldValue('planYear', nowYear + '')
      }
    },
    actionBtnClick(evt, context) {
      const { button, FlowData } = context
      if (button.fakeId === 'save' || button.fakeId === 'workflow-push') {
        // 保存前先校验计划是否已经存在
        evt.waitUntil(
          new Promise((resolve, reject) => {
            this.handleBeforeAdd(null, (res) => {
              if (res) {
                evt.preventDefault()
              }
              resolve()
            })
          })
        )
      }

      if (button.fakeId === 'workflow-push') {
        if (button.buttonId === 'G_1_IAM_AUDITPLAN.3') {
          const childTable = this.$refs.flow.getFieldValue('iamAuditProjectList')
          evt.waitUntil(
            new Promise(function (resolve, reject) {
              if (childTable && childTable.length === 0) {
                Modal.warning({
                  title: '提示',
                  content: '请录入项目信息!',
                })
                // eslint-disable-next-line prefer-promise-reject-errors
                reject()
              } else {
                resolve()
              }
            })
          )
        }
      }
    },
    // 序号赋值
    changeNum(data) {
      const arr = []
      data.forEach((item, index) => {
        if (item.id) {
          arr.push(`${item.id}`)
        }
        item.sortNum = index + 1
      })
      const ids = arr.join(',')
      this.planId = parseInt(this.$refs.flow.flowData.processFormData.beanId)
      if (!this.planId) {
        this.planId = this.randomId
      }
      axios.get(
        'api/xcoa-mobile/v1/iamauditproject/changeProject?planId=' + this.planId + '&ids=' + ids
      )
    },
    handleBeforeAdd(val, callback) {
      this.externalUnitIds = []
      const projectList = this.$refs.flow.FlowData.processFormData.processFormPropertyValues.find(
        (item) => {
          return item.name === 'iamAuditProjectList'
        }
      )
      if (projectList) {
        projectList.attr.dync.find((item) => {
          return item.name === 'auditedUnitIds'
        }).required = false
      }
      const id = parseInt(this.$refs.flow.flowData.processFormData.beanId)
      const planYear = this.$refs.flow.getFieldValue('planYear')
      AuditService.existYearPlan(id, planYear, this.orgid).then((res) => {
        // 检查指定年份年度计划是否已经存在
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '该年度计划已存在!',
          })
        }
        callback(res.data)
      })
    },
    // 批量导入
    batchInport() {
      this.importLoading = false
      this.handleBeforeAdd(null, (res) => {
        if (!res) {
          this.planId = parseInt(this.$refs.flow.flowData.processFormData.beanId)
          if (!this.planId) {
            this.planId = this.randomId
          }
          this.$refs.import.showImportPanel()
        } else {
          setTimeout(() => {
            this.importLoading = false
          }, 1000)
        }
      })
    },
    // 查看审计计划安排情况
    viewSjjh() {
      debugger
      const planYear = this.$refs.flow.getFieldValue('planYear')
      this.viewSjjhcolumns3 = [
        {
          title: '单位名称',
          dataIndex: 'unitName',
          scopedSlots: { customRender: 'unitName' },
        },
      ]
      // this.viewSjjhcolumns4 = [
      //   {
      //     title: '单位名称',
      //     dataIndex: 'unitName',
      //     scopedSlots: { customRender: 'unitName' },
      //   },
      // ]
      const years = []
      for (var s = 3; s > -1; s--) {
        const planYear1 = parseInt(planYear) - s
        this.viewSjjhcolumns3.push({
          title: planYear1 + '年',
          dataIndex: planYear1.toString(),
          scopedSlots: { customRender: 'year' },
        })
        // if (s !== 3) {
        //   this.viewSjjhcolumns3.push({
        //     title: planYear1 + '年',
        //     dataIndex: planYear1.toString(),
        //     scopedSlots: { customRender: 'year' },
        //   })
        // }
        years.push(planYear1.toString())
      }
      this.viewSjyears = years
      this.viewSjjhcolumns3.push({
        title: '结论',
        dataIndex: 'jl',
        scopedSlots: { customRender: 'jl' },
      })
      // this.viewSjjhcolumns4.push({
      //   title: '结论',
      //   dataIndex: 'jl',
      //   scopedSlots: { customRender: 'jl' },
      // })
      this.$nextTick(() => {
        this.modalviewvisible = !this.modalviewvisible
      })
    },
    // 自动预排
    autoPrequeue() {
      const id = this.$refs.flow.flowData.processFormData.beanId
      const planYear = this.$refs.flow.getFieldValue('planYear')
      var data = null
      AuditService.existYearPlan(id, planYear, this.orgid).then((res) => {
        // 检查指定年份年度计划是否已经存在
        if (res.data) {
          Modal.warning({
            title: '提示',
            content: '该年度计划已存在!',
          })
        } else {
          const unitCode = this.$refs.flow.getFieldValue('unitId')
          const child = this.$refs.flow.getFieldValue('iamAuditProjectList')
          const unitIdList = []
          if (child) {
            child.forEach((c) => {
              if (c.whetherAuditCoverage === '1') {
                if (c.auditedUnitIds) {
                  JSON.parse(c.auditedUnitIds).forEach((d) => {
                    unitIdList.push(d.code)
                  })
                }
              }
            })
          }
          AuditService.autoPrequeue(id, unitCode, planYear, unitIdList).then((res) => {
            debugger
            // 自动预排
            if (res.data) {
              // 更新子表项目信息
              const iamAuditProjectList = res.data
              iamAuditProjectList.forEach((item) => {
                // if (item.projectPrincipalId) {
                //   item.projectPrincipalId = JSON.stringify(item.projectPrincipalId)
                // }
                item.id = item.id || 'fakeId_' + Math.random()
                if (item.auditedUnitIds) {
                  item.auditedUnitIds = JSON.stringify(item.auditedUnitIds)
                }
              })
              const tableData = this.$refs.flow.getFieldValue('iamAuditProjectList')
              if (tableData) {
                this.$refs.flow.setFieldValue(
                  'iamAuditProjectList',
                  tableData.concat(iamAuditProjectList)
                )
              } else {
                this.$refs.flow.setFieldValue('iamAuditProjectList', iamAuditProjectList)
              }

              this.childTableKey++
            }
          })
        }
      })
    },
    getDay(model) {
      debugger
      const planStartTime = model.planStartTime
      const planEndTime = model.planEndTime
      if (planStartTime !== undefined && planEndTime !== undefined) {
        const planDays =
          (new Date(moment(planEndTime).format('YYYY/MM/DD')).getTime() -
            new Date(moment(planStartTime).format('YYYY/MM/DD')).getTime()) /
          1000 /
          60 /
          60 /
          24
        model.planDays = (1 + planDays).toString()
      } else {
        model.planDays = ''
      }
      return model
    },
    importHandleCancel() {
      // 导入取消函数
      setTimeout(() => {
        this.importLoading = false
      }, 1000)
    },
    // 导入前置函数
    importfromfileBefore() {
      this.inited = false
    },
    // 导入项目回调函数
    importfromfileAfter() {
      // 通过计划id获取计划信息
      AuditService.getAuditPlanById(this.planId).then((res) => {
        this.inited = true
        if (res.data != null && res.data !== '') {
          this.setProjectList(res.data.iamAuditProjectList)
        } else {
          axios
            .get('api/xcoa-mobile/v1/iamauditproject/getProjectEntity?id=' + this.planId)
            .then((res) => {
              this.setProjectList(res.data)
              setTimeout(() => {
                this.importLoading = false
              }, 1000)
              // // 更新子表项目信息
              // const iamAuditProjectList = res.data
              // iamAuditProjectList.forEach((item) => {
              //   if (item.projectPrincipalId) {
              //     item.projectPrincipalId = JSON.stringify(item.projectPrincipalId)
              //   }
              //   if (item.auditedUnitIds) {
              //     item.auditedUnitIds = JSON.stringify(item.auditedUnitIds)
              //   }
              // })
              // const ids = []
              // const tableData = this.$refs.flow.getFieldValue('iamAuditProjectList')
              // const clist = tableData?.filter((item) => {
              //   if (item.id) ids.push(item.id)
              //   return !item.id
              // })
              // if (!clist) {
              //   this.$refs.flow.setFieldValue('iamAuditProjectList', iamAuditProjectList)
              //   this.childTableKey++
              //   return
              // }
              // this.$refs.flow.setFieldValue(
              //   'iamAuditProjectList',
              //   clist.concat(iamAuditProjectList)
              // )
              // this.childTableKey++
            })
        }
      })
    },
    // 项目信息列表赋值
    setProjectList(res) {
      // 更新子表项目信息
      debugger
      const iamAuditProjectList = res
      iamAuditProjectList.forEach((item) => {
        if (item.projectPrincipalId) {
          item.projectPrincipalId = JSON.stringify(item.projectPrincipalId)
        }
        if (item.auditedUnitIds) {
          item.auditedUnitIds = JSON.stringify(item.auditedUnitIds)
        }
      })
      const ids = []
      const tableData = this.$refs.flow.getFieldValue('iamAuditProjectList')
      const clist = tableData?.filter((item) => {
        if (item.id) ids.push(item.id)
        return !item.id
      })
      if (!clist) {
        this.$refs.flow.setFieldValue('iamAuditProjectList', iamAuditProjectList)
        this.childTableKey++
        return
      }
      iamAuditProjectList.forEach((item) => {
        if (!ids.includes(item.id)) {
          tableData.push(item)
        }
      })
      this.$refs.flow.setFieldValue('iamAuditProjectList', tableData)
      // this.$refs.flow.setFieldValue('iamAuditProjectList', iamAuditProjectList)
      this.childTableKey++
    },
    // 初始化高级字段信息
    initAdvancedField(codeArryData, nameArryData, type) {
      const resultDataArry = []
      let codeArry = []
      let nameArry = []
      if (codeArryData !== null) {
        codeArry = codeArryData.split(',')
      }
      if (nameArryData != null) {
        nameArry = nameArryData.split(',')
      }
      for (let i = 0; i < codeArry.length; i++) {
        resultDataArry.push({
          type: type,
          code: codeArry[i],
          name: nameArry[i],
        })
      }
      return resultDataArry
    },
    // 标题格式化
    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
      }
    },
    // 展示选择列表
    showselectexternal() {
      this.modalvisible = !this.modalvisible
    },
    // 弹出窗确认
    handleOk() {
      this.showselectexternal()
      // 获取别选择的行信息
      const selectInfo = this.$refs.externalTable.getSelectedRows()
      const list = []
      selectInfo.forEach((item) => {
        const obj = {
          title: item.name,
          id: item.id,
          code: item.id,
          name: item.name,
          text: item.name,
          type: 'Group',
          props: {},
        }
        list.push(obj)
      })
      this.$refs.tabaData.$refs.form.model.externalUnitIds = list
      this.externalUnitIds = list
    },
    // 弹出窗取消
    handleCancel() {
      this.showselectexternal()
    },
  },
}
</script>

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

.odrForm {
  /* :global .sd-page-title {
     display: none;
   } */
  :global(.child-table-title) {
    display: none;
  }

  .lastTr {
    :global(.ant-form-item-control-wrapper) {
      border: none !important;
    }
  }

  :global(.header_sd-child-table_common) {
    right: 115px !important;
  }

  .btnexcel {
    position: relative;
    top: -5px;
    float: right;

    .batchexcel {
      z-index: 100;
      margin-left: 10px;
    }
    .autoprequeue {
      right: 180px;
      z-index: 100;
    }
    .viewSjjh {
      right: 180px;
      z-index: 100;
    }
  }

  :global(.ant-form-item-label > label) {
    width: 100% !important;
    white-space: normal;
  }
}

.projecttable {
  table {
    border-collapse: collapse;
  }
}

.iam-audit-child-table {
  :global(td.ant-form-item-label) {
    width: 15%;
    padding-right: 20px;
    overflow: auto;
    white-space: normal;
  }

  :global(td.ant-form-item-label::after) {
    position: absolute;
    margin: 0 8px 0 8px;
    content: ':';
  }

  :global(td.ant-form-item-label > label::after) {
    margin: 0;
    content: '';
  }

  :global(td.ant-form-item-control-wrapper) {
    width: 32%;
  }
}
:global(.auditplanformmodalcksjjh) {
  :global(.ant-pagination) {
    display: none;
  }
}
</style>
