<template>
  <sd-detail-form
    ref="form"
    v-sd-watermark="waterMark"
    page-id="audit/project/iamAuditProject"
    form-id="iamAuditProject"
    :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
    :class="[$style.form, $style.projectstartform]"
    @close="close(true)"
    @saved="saved"
    @sdFormReady="
      () => {
        this.initData()
      }
    "
  >
    <template v-slot="{ model, fields }">
      <table>
        <tr>
          <td
            colspan="4"
            style="
              height: 60px;
              padding-right: 5px;
              padding-left: 5px;
              line-height: 60px;
              border: none;
            "
          >
            <a-steps direction="horizontal" :current="progressJd" size="small">
              <a-step>
                <template slot="title">
                  <span>完善项目信息</span>
                </template>
              </a-step>
              <a-step>
                <template slot="title">
                  <span>指定项目成员</span>
                </template>
              </a-step>
              <a-step>
                <template slot="title">
                  <span>启动成功</span>
                </template>
              </a-step>
            </a-steps>
          </td>
        </tr>
      </table>

      <table v-show="projectStep === '1'">
        <tr>
          <td style="padding-left: 5px; border: none">
            <audit-advanced-group
              :expand="projectinfoExpand"
              :expand-str="'projectinfoExpand'"
              :group-label="'项目信息'"
              tablestyle="''"
              @changedClick="changedClick"
            ></audit-advanced-group>
          </td>
        </tr>
      </table>

      <table v-show="projectinfoExpand && projectStep === '1'">
        <tr>
          <sd-form-item-td name="projectTitle" />
          <sd-form-item-td name="auditType">
            <span>{{ fields.auditType.attr.displayValue }}</span>
          </sd-form-item-td>
        </tr>
        <tr class="projectstartform">
          <sd-form-item-td name="projectPrincipalId">
            <sd-user-picker
              v-model="dataobj.projectPrincipalId"
              :single="true"
              @change="(evt) => handleChange(model, evt, 'projectPrincipalId', 1)"
            />
          </sd-form-item-td>
          <sd-form-item-td name="projectCode">
            <span>{{ model.projectCode }}</span>
          </sd-form-item-td>
        </tr>
        <tr>
          <sd-form-item-td name="auditedUnitIds" :colspan="3">
            <sd-group-picker
              v-model="dataobj.auditedUnitIds"
              @change="(evt) => handleChange(model, evt, 'auditedUnitIds', 3)"
            />
          </sd-form-item-td>
          <!-- <sd-form-item-td name="auditBasis" /> -->
        </tr>
        <tr>
          <sd-form-item-td name="auditMode" />
          <sd-form-item-td
            v-if="model.auditType === '03' || model.auditType === '04'"
            name="auditedUser"
          ></sd-form-item-td>
        </tr>
        <tr>
          <sd-form-item-td v-if="model.auditMode === '02'" name="externalUnitIds" :colspan="3">
            <AuditGroupPicker
              v-model="model.externalUnitIds"
              :read-only="false"
              :selectclick="showselectexternal"
            />
          </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 name="whetherFinance" hidden="true" />
          <sd-form-item-td name="whetherOverseas" hidden="true" />
        </tr>
        <tr class="bklabeloverflow">
          <sd-form-item-td name="whetherAuditCoverage" />
        </tr>
        <tr>
          <sd-form-item-td name="planStartTime" @change="timeChange" />
          <sd-form-item-td name="planEndTime" @change="timeChange" />
        </tr>
        <tr>
          <sd-form-item-td name="planDays"></sd-form-item-td>
        </tr>
        <tr>
          <sd-form-item-td name="groupLeaderId" :colspan="3">
            <sd-user-picker
              v-model="dataobj.groupLeaderId"
              read-only
              :single="true"
              @change="(evt) => handleChange(model, evt, 'groupLeaderId', 2)"
            />
          </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" hidden="true">
            <a-input-number v-model="model.exPersonnelNum" style="width: 100%"></a-input-number>
          </sd-form-item-td>
          <sd-form-item-td name="predictedCost" hidden="true">
            <a-input-number
              v-model="model.predictedCost"
              :min="0"
              :precision="2"
              style="width: 100%"
            ></a-input-number>
          </sd-form-item-td>
        </tr>
        <tr>
          <sd-form-item-td name="auditProcess">
            <sd-select v-model="model.auditProcess" :options="auditProcessOptions" />
          </sd-form-item-td>
          <sd-form-item-td name="linkmanIds" :label="'被审计单位联系人'">
            <sd-user-picker
              v-model="dataobj.linkmanIds"
              @change="(evt) => handleChange(model, evt, 'linkmanIds', 4)"
            />
          </sd-form-item-td>
        </tr>
        <tr class="bklabeloverflow">
          <sd-form-item-td
            :name="['auditperiodStart', 'auditperiodEnd']"
            :input-props="[{ placeholder: '开始' }, { placeholder: '结束' }]"
            :label="'审计期间'"
          />
          <sd-form-item-td name="auditAssets">
            <a-input-number
              v-model="model.auditAssets"
              :min="0"
              :precision="2"
              style="width: 100%"
            ></a-input-number>
          </sd-form-item-td>
        </tr>
        <!-- <tr>
          <sd-form-item-td name="overseas" />

        </tr> -->
        <tr>
          <sd-form-item-td name="auditDomains" hidden="true">
            <a-checkbox-group v-model="model.auditDomains">
              <a-checkbox
                v-for="(item, index) in fields.auditDomains.attr.selectListItem"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-checkbox>
            </a-checkbox-group>
          </sd-form-item-td>
          <sd-form-item-td name="readAuthorityIds" :label="'项目阅读权限范围'" />
        </tr>
        <tr>
          <sd-form-item-td name="attachment" :colspan="3">
            <template v-slot:read-and-edit="{ editable }">
              <sd-attachment
                :group-id="JSON.parse(fields.attachment.value).value"
                :read-only="!editable"
              ></sd-attachment>
            </template>
          </sd-form-item-td>
        </tr>
        <tr>
          <sd-form-item-td v-if="initParam(model)" name="projectRemarks" :colspan="3">
            <a-textarea v-model="model.projectRemarks" :rows="3" />
          </sd-form-item-td>
        </tr>
      </table>

      <table v-show="projectStep === '2'">
        <tr>
          <td style="padding-left: 5px; border: none">
            <audit-advanced-group
              :expand="projectmemberExpand"
              :expand-str="'projectmemberExpand'"
              :group-label="'项目成员'"
              tablestyle="''"
              @changedClick="changedClick"
            >
            </audit-advanced-group>
          </td>
        </tr>
      </table>

      <table v-show="projectmemberExpand && projectStep === '2'">
        <tr>
          <td :colspan="4" :class="$style.childTableTd">
            <a-spin :spinning="selectUserFlag">
              <sd-form-item name="iamProjectUserList" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <!-- 添加按钮，打开选人组件 -->
                  <a-button type="link" :class="$style.addBtn" @click="openProjectUserSelect">
                    <a-icon type="plus-circle" :theme="'filled'" />
                    添加
                  </a-button>
                  <xm-child-table
                    v-show="projectmemberExpand"
                    ref="tabaData"
                    v-model="iamProjectUserList1"
                    :addbuttonvisiable="false"
                    :show-selection="showSelection"
                    :class="$style.deptPlanChild"
                    label=""
                    :read-only="!editable"
                    :fields="Array.from(fields.iamProjectUserList.attr.dync)"
                    :columns="columns"
                    :datachange="dataonload(model)"
                    :dzcl="true"
                    :fncheckdelete="fncheckdelete"
                    :addfun="addfun"
                    @change="fnchange"
                  >
                    <template v-slot:userId="{ field, text, index, value }">
                      <span
                        v-if="
                          value[index]['userType'] === '04' || value[index]['userType'] === '05'
                        "
                        >{{ getDisplayVaule(field, text) }}</span
                      >
                      <sd-form-item
                        v-else
                        :name="field.name"
                        :label="null"
                        :input-props="{
                          defaultValue:
                            value[index][field.name] !== undefined
                              ? JSON.parse(value[index][field.name])
                              : '',
                        }"
                        @change="changep(index, field, value[index])"
                      >
                      </sd-form-item>
                    </template>

                    <template v-slot:joinStartTime="{ field, text, index, value }">
                      <audit-project-input
                        :ref="'sDate_' + index"
                        :value="iamProjectUserList1[index].joinStartTime"
                        lx="s"
                        :field="field"
                        :index="index"
                        @change="setchange"
                      />
                    </template>
                    <template v-slot:joinEndTime="{ field, text, index, value }">
                      <audit-project-input
                        :ref="'eDate_' + index"
                        :value="iamProjectUserList1[index].joinEndTime"
                        lx="t"
                        :field="field"
                        :index="index"
                        @change="setchange"
                      />
                    </template>
                  </xm-child-table>
                </template>
              </sd-form-item>
            </a-spin>
          </td>
        </tr>
      </table>

      <table v-show="projectStep === '3'" style="margin-top: 40px">
        <tr>
          <td style="height: 150px; padding-left: 5px; text-align: center; border: none">
            <sd-icon type="check-circle" :theme="'fill'" :class="$style.iconclass" />
            <div style="margin-top: 10px">启动成功</div>
          </td>
        </tr>
      </table>

      <table>
        <tr>
          <td style="margin-top: 20px; text-align: center; border: none">
            <span style="padding: 0 5px">
              <a-button
                v-if="projectStep === '1'"
                :loading="isSubmitting"
                type="primary"
                @click="fnstep('2')"
                >下一步</a-button
              >
              <a-button v-if="projectStep === '2'" :loading="isSubmitting1" @click="fnstep('1')"
                >上一步</a-button
              >
            </span>
            <span v-if="projectStep === '2'" style="padding: 0 5px">
              <a-button type="primary" :loading="isconfrimSubmitting" @click="fnconfirm"
                >确定</a-button
              >
            </span>
            <span v-if="projectStep !== '3'" style="padding: 0 5px">
              <a-button @click="close(true)">取消</a-button>
            </span>
            <span v-else style="padding: 0 5px">
              <a-button @click="close(true)">关闭</a-button>
            </span>
          </td>
        </tr>
      </table>

      <!-- 选择人员组件 -->
      <div v-show="false">
        <sd-user-picker
          ref="projectUserSelect"
          :single="false"
          :read-only="false"
          :required="true"
          @change="projectUserChange"
        />
      </div>
      <a-modal
        :visible="modalvisible"
        title="请选择"
        width="1200px"
        :body-style="{
          padding: 20,
          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>
    </template>
  </sd-detail-form>
</template>

<script>
import moment from 'moment'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { getComponentSpec } from '@/common/components/sd-form'
import { Message, Modal, Select } from 'ant-design-vue'
import systemManage from '@/system-manage/system-manage'
import TableColumnTypes from '@/common/services/table-column-types'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import logUtil from '@/common/services/log-util'
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import xmChildTableMixins from '../../components/xm-child-table-mixins'
import auditProjectInput from './audit-project-input.vue'
import components from './_import-components/audit-project-start-form-import'

export default {
  name: 'AuditProjectStartForm',
  metaInfo: {
    title: '启动项目',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    AuditGroupPicker,
    auditProjectInput,
  },
  mixins: [auditAdvancedGroupMixins, xmChildTableMixins],
  data() {
    return {
      selectUserFlag: false, // 选人之后的加载状态
      waterMark: systemManage.getFormWaterMark(),
      progressData: [{ title: '完善项目信息' }, { title: '指定项目组成员' }],
      progressJd: 0,
      progre: 50,
      projectinfoExpand: true,
      projectmemberExpand: true,
      projectStep: '1',
      auditDomainsOptions: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '姓名',
          dataIndex: 'userId',
          width: '150px',
        },
        {
          title: '姓名',
          dataIndex: 'userName',
          sdHidden: true,
        },
        {
          dataIndex: 'userAccount',
          sdHidden: true,
        },
        {
          title: '项目角色',
          dataIndex: 'userType',
          width: '150px',
        },
        // {
        //   title: '人员类型',
        //   dataIndex: 'userJob',
        //   width: '150px',
        // },
        // {
        //   title: '所属机构名称',
        //   dataIndex: 'orgName',
        //   width: '150px',
        // },

        {
          title: '参与开始日期',
          dataIndex: 'joinStartTime',
          sdRender: TableColumnTypes.date,
          width: '150px',
        },
        {
          title: '参与结束日期',
          dataIndex: 'joinEndTime',
          sdRender: TableColumnTypes.date,
          width: '150px',
        },
        {
          title: '任务说明',
          dataIndex: 'taskExplain',
          width: 'auto',
        },
        {
          title: '手机号码',
          dataIndex: 'phoneNumber',
          width: '13%',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          width: '18%',
        },
        {
          dataIndex: 'userScore',
          sdHidden: true,
        },
        {
          dataIndex: 'examineResult',
          sdHidden: true,
        },
      ],
      dataobjflag: false,
      flag: true,
      dataobj: {
        projectPrincipalId: [],
        groupLeaderId: [],
        auditedUnitIds: [],
        linkmanIds: [],
      },
      auditProcessOptions: [],
      iamProjectUserList1: [],
      iamProjectUserListflag: false,
      visible: false,
      isSubmitting: false,
      isSubmitting1: false,
      isconfrimSubmitting: false,
      modalvisible: false,
      modalcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '20px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          title: '企业名称',
          dataIndex: 'name',
          width: '300px',
        },
        {
          title: '类型',
          dataIndex: 'category',
          width: '150px',
        },
        {
          title: '住所',
          dataIndex: 'address',
          width: '100px',
        },
      ],
      expressions: [],
      externalUnitIds: [],
      index: 0,
    }
  },
  mounted() {
    // 初始化数据字典信息
    this.initDictionaryInfo()
    var _this = this
    logUtil.$on('modifyLogCustomData', function (modifyLogData) {
      _this.modifyLogCustomData(modifyLogData)
    })
  },
  methods: {
    timeChange() {
      const start = this.$refs.form.getFieldValue('planStartTime')
      const end = this.$refs.form.getFieldValue('planEndTime')
      this.iamProjectUserList1.forEach((item, index) => {
        item.joinStartTime = moment(start).valueOf()
        item.joinEndTime = moment(end).valueOf()
        this.$refs['sDate_' + index].model = moment(start)
        this.$refs['eDate_' + index].model = moment(end)
      })
      if (start !== undefined && end !== undefined) {
        const planDays =
          (new Date(moment(end).format('YYYY/MM/DD')).getTime() -
            new Date(moment(start).format('YYYY/MM/DD')).getTime()) /
          1000 /
          60 /
          60 /
          24
        this.$refs.form.setFieldValue('planDays', planDays + 1)
      } else {
        this.$refs.form.setFieldValue('planDays', undefined)
      }
      this.$nextTick()
    },
    showSelection(record) {
      if ((record.userType === '04') | (record.userType === '05')) {
        return false
      }
      return true
    },
    setchange(value, field, index, lx) {
      this.$refs.tabaData.$refs[field.name + '_' + index][0].setFieldValue(field.name, value)
      this.iamProjectUserList1[index][field.name] = value
      if (lx === 's') {
        // 设置 开始时间
        this.$refs['eDate_' + index].time = value
      } else {
        this.$refs['sDate_' + index].time = value
      }
    },
    getDisplayVaule(field, text) {
      if (getComponentSpec(field).getDisplayValue) {
        if (typeof text !== 'undefined' && text !== null) {
          const value = getComponentSpec(field).parseBackendValue?.(text) || text
          return getComponentSpec(field).getDisplayValue(value)
        } else {
          return ''
        }
      }
      return text
    },
    changep(i, field, value) {
      const user = this.$refs.tabaData.$refs[field.name + '_' + i][0].getFieldValue(field.name)
      if (user.length > 0) {
        axios({
          url:
            'api/xcoa-mobile/v1/iamuserbase/getUserBaseInfoByAccount?userAccount=' + user[0].code,
          method: 'get',
        }).then((res) => {
          if (res.data.userPhone === null) {
            value.phoneNumber = ''
          } else {
            value.phoneNumber = res.data.userPhone
          }
          if (res.data.userMail === null) {
            value.email = ''
          } else {
            value.email = res.data.userMail
          }
          value.userId = JSON.stringify(user)
          this.$refs.tabaData.$refs['phoneNumber_' + i][0].setFieldValue(
            'phoneNumber',
            value.phoneNumber
          )
          this.$refs.tabaData.$refs['email_' + i][0].setFieldValue('email', value.email)
        })
      }
    },
    modifyLogCustomData(modifyLogData) {
      // 修改modifyLogData中的元素
      let childTableIndex
      modifyLogData.forEach((item, index) => {
        if (item.key === 'iamProjectUserList') {
          childTableIndex = index
        }
      })
      // 去掉子表的修改记录
      modifyLogData.splice(childTableIndex, 1)
      return modifyLogData
    },
    initDictionaryInfo() {
      // 获取审计流程下拉框信息
      const projectId = this.$route.query.record
      axios({
        url: 'api/xcoa-mobile/v1/iamauditproject/getProjectProcessList?projectId=' + projectId,
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.auditProcessOptions = res.data
        }
      })
    },
    handleChange(model, event, field, i) {
      this.$refs.form.setFieldValue(field, this.dataobj[field])
      this.dataobj[field] = [...event]
    },
    initParam(model) {
      if (this.flag) {
        if (!this.dataobjflag) {
          this.setFeildvaluexm(model)
        }
        this.initExternalUnitIdsData(model)
        this.flag = false
      }
      return true
    },
    setFeildvaluexm(model) {
      const fields = [
        {
          name: 'projectPrincipalName',
          code: 'projectPrincipalAccount',
          field: 'projectPrincipalId',
          type: 'User',
          i: 1,
        },
        {
          name: 'groupLeaderName',
          code: 'groupLeaderAccount',
          field: 'groupLeaderId',
          type: 'User',
          i: 2,
        },
        {
          name: 'auditedUnitNames',
          code: 'auditedUnitCodes',
          field: 'auditedUnitIds',
          type: 'Dept',
          i: 3,
        },
        {
          name: 'linkmanName',
          code: 'linkmanCode',
          field: 'linkmanIds',
          type: 'User',
          i: 4,
        },
      ]
      fields.forEach((item) => {
        if (item.name !== '') {
          const name = model[item.name]
          const code = model[item.code]
          const id = model[item.field]
          if (name !== '' && name !== undefined) {
            if (name.indexOf(',') > 0) {
              const names = name.split(',')
              const codes = code.split(',')
              const obj = []
              for (var i = 0; i < names.length; i++) {
                obj.push({ code: codes[i], name: names[i], text: names[i], type: item.type })
              }
              this.dataobj[item.field] = obj
              this.dataobjflag = true
            } else {
              const obj = [{ code: code, name: name, text: name, type: item.type }]
              this.dataobj[item.field] = obj
              this.dataobjflag = true
            }
          }
        }
      })
    },
    validator(rule, value, callback) {
      debounce(() => {
        axios
          .get(
            `api/xcoa-mobile/v1/businesstype-manage/categories/check-code?categoryCode=${value}&id=${
              this.$refs.dataTable.getDetailModal().getFieldValue('id') || ''
            }`
          )
          .then((res) => {
            if (res?.data?.status === 'success') {
              callback()
            } else {
              callback('已存在分类编码，不可以重复')
            }
          })
      }, 500)()
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      Message.success('保存成功', 1).then((res) => {
        // this.close(true)
        this.progressJd = 2
        this.projectStep = '3'
        this.isconfrimSubmitting = false
      })
    },
    // 保存
    saveForm() {
      // 需要校验定义新增行是否还有editable
      this.$refs.form.setFieldValue('projectPrincipalId', this.dataobj.projectPrincipalId)
      this.$refs.form.setFieldValue('groupLeaderId', this.dataobj.groupLeaderId)
      this.$refs.form.setFieldValue('auditedUnitIds', this.dataobj.auditedUnitIds)
      this.$refs.form.setFieldValue('linkmanIds', this.dataobj.linkmanIds)

      if (this.projectStep === '2') {
        this.$refs.form.saveBtnClick().catch((res) => {
          this.isconfrimSubmitting = false
        })
      } else {
        this.$refs.form.saveBtnClick()
      }
    },
    // 序号赋值
    changeNum(data) {
      data.forEach((item, index) => {
        item.sortNum = index + 1
      })
    },
    fnstep(step) {
      if (step === '1') {
        this.isSubmitting1 = true
        this.$refs.tabaData.valid().then((res) => {
          // 校验动态子表
          if (res) {
            this.progressJd = 0
            this.progre = 50
            this.projectStep = step
          }
          this.isSubmitting1 = false
        })
        // .catch(() => {
        //   this.isSubmitting1 = false
        // })
      } else {
        this.isSubmitting = true
        // 将高级字段赋值
        this.$refs.form.setFieldValue('projectPrincipalId', this.dataobj.projectPrincipalId)
        this.$refs.form.setFieldValue('groupLeaderId', this.dataobj.groupLeaderId)
        this.$refs.form.setFieldValue('auditedUnitIds', this.dataobj.auditedUnitIds)
        this.$refs.form.setFieldValue('linkmanIds', this.dataobj.linkmanIds)
        // 校验当前页面必填是否
        this.$refs.form
          .validateFields()
          .then((res) => {
            if (res) {
              this.progressJd = 1
              this.progre = 99
              this.projectStep = step
              this.isSubmitting = false
              setTimeout(() => {
                this.$refs.tabaData.fnsettablesize()
              }, 1000)
            }
          })
          .catch(() => {
            this.isSubmitting = false
          })
      }
    },
    addfun(data) {
      const sl = new Date(this.$refs.form.getFieldValue('planStartTime')).getTime()
      const el = new Date(this.$refs.form.getFieldValue('planEndTime')).getTime()
      data.joinStartTime = sl
      data.joinEndTime = el
      return data
    },
    dataonload(model) {
      // console.log(model, '数据--model')
      const projectPrincipalId = 'projectPrincipalId'
      const groupLeaderId = 'groupLeaderId'
      const fzr = this.dataobj[projectPrincipalId]
      const xmjl = this.dataobj[groupLeaderId]
      const sl = new Date(model.planStartTime).getTime()
      const el = new Date(model.planEndTime).getTime()
      let data = []
      // const data = this.$refs.form.getFieldValue('iamProjectUserList')
      if (this.iamProjectUserListflag) {
        data = this.iamProjectUserList1
      } else {
        data = model.iamProjectUserList
        this.iamProjectUserListflag = true
      }
      // 04 项目负责人 05 项目组长
      if (data === undefined) {
        const ndata = []
        if (fzr.length !== 0) {
          ndata.push({
            userId: JSON.stringify(fzr),
            userType: '04',
            joinStartTime: sl,
            joinEndTime: el,
          })
        }
        if (xmjl.length !== 0) {
          ndata.push({
            userId: JSON.stringify(xmjl),
            userType: '05',
            joinStartTime: sl,
            joinEndTime: el,
          })
        }
        this.iamProjectUserList1 = ndata
      } else {
        let flag = false
        let xmjlflag = false
        data.forEach((item) => {
          if (item.userType === '04') {
            flag = true
            if (fzr[0].text !== item.userName || item.userId === '[]') {
              item.userId = JSON.stringify(fzr)
            }
          } else if (item.userType === '05') {
            xmjlflag = true
            if (xmjl.length === 0) {
              data.splice(1, 1)
            } else {
              if (xmjl[0].text !== item.userName || item.userId === '[]') {
                item.userId = JSON.stringify(xmjl)
              }
            }
          }
        })
        if (!flag) {
          if (fzr.length !== 0) {
            data.splice(0, 0, {
              userId: JSON.stringify(fzr),
              userType: '04',
              joinStartTime: sl,
              joinEndTime: el,
            })
          }
        }
        if (!xmjlflag) {
          if (xmjl.length !== 0) {
            data.splice(1, 0, {
              userId: JSON.stringify(xmjl),
              userType: '05',
              joinStartTime: sl,
              joinEndTime: el,
            })
          }
        }
        this.iamProjectUserList1 = data
        // this.$refs.form.setFieldValue('iamProjectUserList', data)
      }
      console.log(model, '数据--莫德罗----2')
    },
    fnconfirm() {
      // 启动前需要校验 动态表格数据是否都已填写完毕
      this.isconfrimSubmitting = true
      this.$refs.tabaData.valid().then((res) => {
        // 校验动态子表
        if (res) {
          this.$refs.form.setFieldValue('itemStatus', '02')
          this.saveForm()
        } else {
          this.isconfrimSubmitting = false
        }
      })
      // .catch(() => {})
    },
    fncheckdelete(data, i) {
      if (typeof i === 'object') {
        let flag = true
        i.forEach((xh) => {
          if (data[xh].userType === '04' || data[xh].userType === '05') {
            flag = false
          }
        })
        if (flag) {
          return true
        } else {
          return false
        }
      } else {
        if (data[i].userType === '04' || data[i].userType === '05') {
          return false
        } else {
          return true
        }
      }
    },
    fnchange() {
      this.iamProjectUserList1.forEach((item) => {
        if (item.userId !== undefined) {
          const userid = JSON.parse(item.userId)
          item.userName = userid[0].text
          item.userAccount = userid[0].code
        }
      })
      this.$refs.form.setFieldValue('iamProjectUserList', this.iamProjectUserList1)
    },
    // 展示选择列表
    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.form.setFieldValue('externalUnitIds', list)
    },
    // 弹出窗取消
    handleCancel() {
      this.showselectexternal()
    },
    initExternalUnitIdsData(model) {
      const list = []
      let codes = []
      let names = []
      const externalUnitCodes = model.externalUnitCodes
      const externalUnitNames = model.externalUnitNames
      if (externalUnitCodes) {
        codes = externalUnitCodes.split(',')
        names = externalUnitNames.split(',')
        for (let i = 0; i < codes.length; i++) {
          const obj = {
            title: names[i],
            id: codes[i],
            code: codes[i],
            name: names[i],
            text: names[i],
            type: 'Group',
            props: {},
          }
          list.push(obj)
        }
        this.externalUnitIds = list
      }
    },
    initData() {
      if (this.externalUnitIds.length > 0) {
        this.$refs.form.setFieldValue('externalUnitIds', this.externalUnitIds)
      }
      if (this.auditProcessOptions.length > 0) {
        this.$refs.form.setFieldValue('auditProcess', [this.auditProcessOptions[0]])
      }
    },
    getPikerData(projectId) {
      return function () {
        return new Promise((resolve) => {
          axios({
            url: 'api/xcoa-mobile/v1/audit/auditsource/extrnal/iamExternalBase',
            method: 'get',
          }).then((res) => {
            const dataSource = []
            res.data.forEach((item) => {
              dataSource.push({
                name: item.name,
                code: item.code,
                type: 'Group',
              })
            })
            resolve(dataSource)
          })
        })
      }
    },
    // 打开选择人员的组件
    openProjectUserSelect() {
      this.$refs.projectUserSelect.openPicker()
    },
    //
    projectUserChange(val) {
      this.selectUserFlag = true
      const sl = new Date(this.$refs.form.getFieldValue('planStartTime')).getTime()
      const el = new Date(this.$refs.form.getFieldValue('planEndTime')).getTime()
      const userList = val.map((item) => {
        return {
          id: null,
          joinEndTime: el,
          joinStartTime: sl,
          projectId: this.$route.query.record,
          userAccount: item.code,
          userId:
            '[{"code":"' +
            item.code +
            '","name":"' +
            item.name +
            '","text":"' +
            item.name +
            '","type":"User"}]',
          userName: item.name,
          userType: '03',
        }
      })
      // 获取电话号码及邮箱
      userList.forEach((item, index) => {
        axios({
          url:
            'api/xcoa-mobile/v1/iamuserbase/getUserBaseInfoByAccount?userAccount=' +
            item.userAccount,
          method: 'get',
        }).then((res) => {
          if (res.data.userMobile === null) {
            item.phoneNumber = ''
          } else {
            item.phoneNumber = res.data.userMobile
          }
          if (res.data.userMail === null) {
            item.email = ''
          } else {
            item.email = res.data.userMail
          }
          // 最后一次循环，赋值
          if (index === userList.length - 1) {
            this.iamProjectUserList1 = this.iamProjectUserList1.concat(userList)
            // 将子表信息赋值，否则无法保存
            this.fnchange()
            // 取消加载状态
            this.selectUserFlag = false
          }
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

.projectstartform {
  .iconclass {
    margin-right: 8px;
    font-size: 70px;
    color: #1890ff;
    vertical-align: middle;
  }

  :global(.ant-checkbox-group > label:first-child) {
    margin-left: 9px !important;
  }

  :global(.title_sd-detail-form_common > span) {
    visibility: hidden;
  }

  :global(.title_sd-detail-form_common ::after) {
    padding: 0 100px 0 0;
    visibility: visible;
    content: '启动项目';
  }
}

.form {
  :global(.buttons_sd-detail-form_common) {
    display: none;
  }
  :global .projectstartform > td.ant-form-item-label > label {
    width: 160px;
    white-space: break-spaces !important;
  }
}
.add-btn {
  position: absolute;
  top: 7px;
  right: 85px;
  z-index: 99;
}
.child-table-td {
  :global(.ant-form-item-children) {
    display: block;
  }
}
</style>
