<template>
  <BasicPopup
    v-bind="$attrs"
    @register="registerPopup"
    showOkBtn
    destroyOnClose
    :cancelText="t('common.cancelText', '取消')"
    :okText="t('common.okText', '确定')"
    @ok="handleSubmit"
    :closeFunc="onClose">
    <template #title>
      <a-space :size="10">
        <div class="text-16px font-medium">{{ title }}</div>
        <a-space-compact size="small" block v-if="dataForm.id">
          <a-tooltip :title="t('common.prevRecord')">
            <a-button size="small" :disabled="getPrevDisabled" @click="handlePrev">
              <i class="icon-ym icon-ym-caret-left text-10px"></i>
            </a-button>
          </a-tooltip>
          <a-tooltip :title="t('common.nextRecord')">
            <a-button size="small" :disabled="getNextDisabled" @click="handleNext">
              <i class="icon-ym icon-ym-caret-right text-10px"></i>
            </a-button>
          </a-tooltip>
        </a-space-compact>
      </a-space>
    </template>
    <template #insertToolbar>
      <yunzhupaasCheckboxSingle v-model:value="submitType" :label="continueText" v-if="showContinueBtn" />
    </template>
    <a-row class="p-10px dynamic-form" :style="{ margin: '0 auto', width: '100%' }">
      <a-form
        :colon="false"
        size="middle"
        layout="horizontal"
        labelAlign="right"
        :labelCol="{ style: { width: '100px' } }"
        :model="dataForm"
        :rules="dataRule"
        ref="formRef">
        <a-row :gutter="15">
          <!-- 具体表单 -->
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="company_code">
              <template #label>企业编码 </template>
              <YunzhupaasInput
                v-model:value="dataForm.company_code"
                @change="changeData('company_code', -1)"
                placeholder="请输入企业编码"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.company_code"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="company_name">
              <template #label>企业名称 </template>
              <YunzhupaasInput
                v-model:value="dataForm.company_name"
                @change="changeData('company_name', -1)"
                placeholder="请输入企业名称"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.company_name"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="short_name">
              <template #label>简称/昵称 </template>
              <YunzhupaasInput
                v-model:value="dataForm.short_name"
                @change="changeData('short_name', -1)"
                placeholder="请输入简称/昵称"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.short_name"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="entity_type">
              <template #label>类型 </template>
              <YunzhupaasRadio
                v-model:value="dataForm.entity_type"
                @change="changeData('entity_type', -1)"
                :templateJson="state.interfaceRes.entity_type"
                :style="{ width: '100%' }"
                size="default"
                :options="optionsObj.entity_typeOptions"
                :fieldNames="optionsObj.entity_typeProps"
                direction="horizontal"
                optionType="default">
              </YunzhupaasRadio>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="credit_code">
              <template #label>社会信用代码 </template>
              <YunzhupaasInput
                v-model:value="dataForm.credit_code"
                @change="changeData('credit_code', -1)"
                placeholder="请输入社会信用代码"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.credit_code"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="company_scope">
              <template #label>企业范围 </template>
              <YunzhupaasSelect
                v-model:value="dataForm.company_scope"
                @change="changeData('company_scope', -1)"
                placeholder="请选择企业范围"
                :templateJson="state.interfaceRes.company_scope"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.company_scopeOptions"
                :fieldNames="optionsObj.company_scopeProps">
              </YunzhupaasSelect>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="tax_type">
              <template #label>纳税人类别 </template>
              <YunzhupaasSelect
                v-model:value="dataForm.tax_type"
                @change="changeData('tax_type', -1)"
                placeholder="请选择纳税人类别"
                :templateJson="state.interfaceRes.tax_type"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.tax_typeOptions"
                :fieldNames="optionsObj.tax_typeProps">
              </YunzhupaasSelect>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="enterprise_scale">
              <template #label>企业规模 </template>
              <YunzhupaasSelect
                v-model:value="dataForm.enterprise_scale"
                @change="changeData('enterprise_scale', -1)"
                placeholder="请选择企业规模"
                :templateJson="state.interfaceRes.enterprise_scale"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.enterprise_scaleOptions"
                :fieldNames="optionsObj.enterprise_scaleProps">
              </YunzhupaasSelect>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="enterprise_nature">
              <template #label>企业类型 </template>
              <YunzhupaasSelect
                v-model:value="dataForm.enterprise_nature"
                @change="changeData('enterprise_nature', -1)"
                placeholder="请选择企业类型"
                :templateJson="state.interfaceRes.enterprise_nature"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.enterprise_natureOptions"
                :fieldNames="optionsObj.enterprise_natureProps">
              </YunzhupaasSelect>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="industry_code">
              <template #label>行业代码 </template>
              <YunzhupaasSelect
                v-model:value="dataForm.industry_code"
                @change="changeData('industry_code', -1)"
                placeholder="请选择行业代码"
                :templateJson="state.interfaceRes.industry_code"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.industry_codeOptions"
                :fieldNames="optionsObj.industry_codeProps">
              </YunzhupaasSelect>
            </a-form-item>
          </a-col>

          <a-col :span="8" class="ant-col-item">
            <a-form-item name="registration_date">
              <template #label>成立日期 </template>
              <YunzhupaasDatePicker
                v-model:value="dataForm.registration_date"
                @change="changeData('registration_date', -1)"
                placeholder="请选择成立日期"
                :allowClear="true"
                :style="{ width: '100%' }"
                format="yyyy-MM-dd"
                :startTime="getRelationDate(false, 1, 1, '', '')"
                :endTime="getRelationDate(false, 1, 1, '', '')">
              </YunzhupaasDatePicker>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="registered_capital">
              <template #label>注册资本 </template>
              <YunzhupaasInputNumber
                v-model:value="dataForm.registered_capital"
                @change="changeData('registered_capital', -1)"
                placeholder="请输入注册资本"
                :style="{ width: '100%' }"
                :max="999999"
                :step="1"
                :precision="4"
                addonAfter="万元"
                :controls="false">
              </YunzhupaasInputNumber>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="legal_representative">
              <template #label>法定代表人 </template>
              <YunzhupaasInput
                v-model:value="dataForm.legal_representative"
                @change="changeData('legal_representative', -1)"
                placeholder="请输入法定代表人"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.legal_representative"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="phone">
              <template #label>联系电话 </template>
              <YunzhupaasInput
                v-model:value="dataForm.phone"
                @change="changeData('phone', -1)"
                placeholder="请输入联系电话"
                :maxlength="11"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.phone"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="email">
              <template #label>邮箱 </template>
              <YunzhupaasInput
                v-model:value="dataForm.email"
                @change="changeData('email', -1)"
                placeholder="请输入邮箱"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.email"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="website">
              <template #label>网站 </template>
              <YunzhupaasInput
                v-model:value="dataForm.website"
                @change="changeData('website', -1)"
                placeholder="请输入网站"
                :maxlength="50"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.website"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="address">
              <template #label>地址 </template>
              <YunzhupaasInput
                v-model:value="dataForm.address"
                @change="changeData('address', -1)"
                placeholder="请输入地址"
                :maxlength="200"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.address"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="8" class="ant-col-item">
            <a-form-item name="province_id">
              <template #label>所属地区 </template>
              <YunzhupaasAreaSelect
                v-model:value="dataForm.province_id"
                @change="changeData('province_id', -1)"
                placeholder="请选择所属地区"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :level="2">
              </YunzhupaasAreaSelect>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="business_scope">
              <template #label>经营范围 </template>
              <YunzhupaasTextarea
                v-model:value="dataForm.business_scope"
                @change="changeData('business_scope', -1)"
                placeholder="请输入经营范围"
                :maxlength="200"
                :allowClear="true"
                :style="{ width: '100%' }"
                :autoSize="{ minRows: 3, maxRows: 3 }"
                :showCount="false">
              </YunzhupaasTextarea>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="remark">
              <template #label>备注 </template>
              <YunzhupaasTextarea
                v-model:value="dataForm.remark"
                @change="changeData('remark', -1)"
                placeholder="请输入备注"
                :maxlength="100"
                :allowClear="true"
                :style="{ width: '100%' }"
                :autoSize="{ minRows: 2, maxRows: 2 }"
                :showCount="false">
              </YunzhupaasTextarea>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-tabs v-model:activeKey="state.activetabformItem5e5d3b" tabPosition="top" class="mb-20">
              <a-tab-pane tab="客户关系" key="1" forceRender>
                <a-row :gutter="15">
                  <a-col :span="8" class="ant-col-item">
                    <a-form-item name="owner_id">
                      <template #label>客户负责人 </template>
                      <YunzhupaasUserSelect
                        v-model:value="dataForm.owner_id"
                        @change="changeData('owner_id', -1)"
                        placeholder="请选择客户负责人"
                        :allowClear="true"
                        :style="{ width: '100%' }"
                        selectType="all">
                      </YunzhupaasUserSelect>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8" class="ant-col-item">
                    <a-form-item name="org_id">
                      <template #label>归属组织 </template>
                      <YunzhupaasOrganizeSelect
                        v-model:value="dataForm.org_id"
                        @change="changeData('org_id', -1)"
                        placeholder="请选择归属组织"
                        :allowClear="true"
                        :style="{ width: '100%' }"
                        :showSearch="false"
                        selectType="all">
                      </YunzhupaasOrganizeSelect>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8" class="ant-col-item">
                    <a-form-item name="customer_level">
                      <template #label>客户等级 </template>
                      <YunzhupaasSelect
                        v-model:value="dataForm.customer_level"
                        @change="changeData('customer_level', -1)"
                        placeholder="请选择客户等级"
                        :templateJson="state.interfaceRes.customer_level"
                        :allowClear="true"
                        :style="{ width: '100%' }"
                        :showSearch="false"
                        :options="optionsObj.customer_levelOptions"
                        :fieldNames="optionsObj.customer_levelProps">
                      </YunzhupaasSelect>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8" class="ant-col-item">
                    <a-form-item name="customer_lifecycle">
                      <template #label>生命周期阶段 </template>
                      <YunzhupaasSelect
                        v-model:value="dataForm.customer_lifecycle"
                        @change="changeData('customer_lifecycle', -1)"
                        placeholder="请选择生命周期阶段"
                        :templateJson="state.interfaceRes.customer_lifecycle"
                        :allowClear="true"
                        :style="{ width: '100%' }"
                        :showSearch="false"
                        :options="optionsObj.customer_lifecycleOptions"
                        :fieldNames="optionsObj.customer_lifecycleProps">
                      </YunzhupaasSelect>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8" class="ant-col-item">
                    <a-form-item name="is_public">
                      <template #label>是否公海客户 </template>
                      <YunzhupaasRadio
                        v-model:value="dataForm.is_public"
                        @change="changeData('is_public', -1)"
                        :templateJson="state.interfaceRes.is_public"
                        :style="{ width: '100%' }"
                        size="default"
                        :options="optionsObj.is_publicOptions"
                        :fieldNames="optionsObj.is_publicProps"
                        direction="horizontal"
                        optionType="default">
                      </YunzhupaasRadio>
                    </a-form-item>
                  </a-col>

                  <a-col :span="8" class="ant-col-item">
                    <a-form-item name="last_followup_date">
                      <template #label>最后一次跟进 </template>
                      <YunzhupaasDatePicker
                        v-model:value="dataForm.last_followup_date"
                        @change="changeData('last_followup_date', -1)"
                        placeholder="请选择最后一次跟进日期"
                         :disabled="true"
                        :allowClear="true"
                        :style="{ width: '100%' }"
                        format="yyyy-MM-dd"
                        :startTime="getRelationDate(false, 1, 1, '', '')"
                        :endTime="getRelationDate(false, 1, 1, '', '')">
                      </YunzhupaasDatePicker>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-tab-pane>
              <a-tab-pane tab="联系人信息" key="2" forceRender>
                <a-row :gutter="15">
                  <a-col :span="24" class="ant-col-item mb-20px">
                    <a-form-item>
                      <yunzhupaasGroupTitle content="联系人信息" :bordered="false" helpMessage="" />
                      <a-table
                        :data-source="dataForm.mdmCompanyContactList"
                        :columns="mdmCompanyContactColumns"
                        size="small"
                        :pagination="false"
                        :scroll="{ x: 'max-content' }"
                        :rowSelection="getmdmCompanyContactRowSelection"
                        rowKey="yunzhupaasId">
                        <template #headerCell="{ column }">
                          <span class="required-sign" v-if="column.required">*</span>
                          {{ column.title }}
                          <BasicHelp :text="column.tipLabel" v-if="column.tipLabel && column.title" />
                        </template>
                        <template #bodyCell="{ column, index, record }">
                          <template v-if="column.key === 'index'">{{ index + 1 }}</template>
                          <template v-if="column.key === 'contact_name'">
                            <YunzhupaasInput
                              v-model:value="record.contact_name"
                              @change="changeData('mdmCompanyContactcontact_name', index)"
                              placeholder="请输入联系人"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyContactcontact_name"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'contact_title'">
                            <YunzhupaasInput
                              v-model:value="record.contact_title"
                              @change="changeData('mdmCompanyContactcontact_title', index)"
                              placeholder="请输入联系人职务"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyContactcontact_title"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'contact_phone'">
                            <YunzhupaasInput
                              v-model:value="record.contact_phone"
                              @change="changeData('mdmCompanyContactcontact_phone', index)"
                              placeholder="请输入电话"
                              :maxlength="11"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyContactcontact_phone"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'contact_email'">
                            <YunzhupaasInput
                              v-model:value="record.contact_email"
                              @change="changeData('mdmCompanyContactcontact_email', index)"
                              placeholder="请输入邮箱"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyContactcontact_email"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'remark'">
                            <YunzhupaasInput
                              v-model:value="record.remark"
                              @change="changeData('mdmCompanyContactremark', index)"
                              placeholder="请输入备注"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyContactremark"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'action'">
                            <a-space>
                              <a-button class="action-btn" type="link" @click="copyMdmCompanyContactRow(index)" size="small">
                                {{ t('common.copyText', '复制') }}
                              </a-button>
                              <a-button class="action-btn" type="link" color="error" @click="removeMdmCompanyContactRow(index, true)" size="small">
                                {{ t('common.delText', '删除') }}
                              </a-button>
                            </a-space>
                          </template>
                        </template>
                      </a-table>
                      <a-space class="input-table-footer-btn">
                        <a-button type="primary" preIcon="icon-ym icon-ym-btn-add" @click="addMdmCompanyContactRow">
                          {{ t('common.add1Text', '添加') }}
                        </a-button>
                        <a-button type="danger" preIcon="icon-ym icon-ym-btn-clearn" @click="batchRemoveMdmCompanyContactRow(true)">
                          {{ t('common.batchDelText', '批量删除') }}
                        </a-button>
                      </a-space>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-tab-pane>
              <a-tab-pane tab="银行卡信息" key="a930ad" forceRender>
                <a-row :gutter="15">
                  <a-col :span="24" class="ant-col-item mb-20px">
                    <a-form-item>
                      <yunzhupaasGroupTitle content="银行信息" :bordered="false" helpMessage="" />
                      <a-table
                        :data-source="dataForm.mdmCompanyBankList"
                        :columns="mdmCompanyBankColumns"
                        size="small"
                        :pagination="false"
                        :scroll="{ x: 'max-content' }"
                        :rowSelection="getmdmCompanyBankRowSelection"
                        rowKey="yunzhupaasId">
                        <template #headerCell="{ column }">
                          <span class="required-sign" v-if="column.required">*</span>
                          {{ column.title }}
                          <BasicHelp :text="column.tipLabel" v-if="column.tipLabel && column.title" />
                        </template>
                        <template #bodyCell="{ column, index, record }">
                          <template v-if="column.key === 'index'">{{ index + 1 }}</template>
                          <template v-if="column.key === 'bank_account_number'">
                            <YunzhupaasInput
                              v-model:value="record.bank_account_number"
                              @change="changeData('mdmCompanyBankbank_account_number', index)"
                              placeholder="请输入银行账号"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyBankbank_account_number"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'bank_name'">
                            <YunzhupaasInput
                              v-model:value="record.bank_name"
                              @change="changeData('mdmCompanyBankbank_name', index)"
                              placeholder="请输入开户行"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyBankbank_name"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'bank_account_name'">
                            <YunzhupaasInput
                              v-model:value="record.bank_account_name"
                              @change="changeData('mdmCompanyBankbank_account_name', index)"
                              placeholder="请输入账户名"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyBankbank_account_name"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'bank_province'">
                            <YunzhupaasInput
                              v-model:value="record.bank_province"
                              @change="changeData('mdmCompanyBankbank_province', index)"
                              placeholder="请输入开户行城市"
                              :maxlength="50"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyBankbank_province"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'remark'">
                            <YunzhupaasInput
                              v-model:value="record.remark"
                              @change="changeData('mdmCompanyBankremark', index)"
                              placeholder="请输入备注"
                              :maxlength="200"
                              :allowClear="true"
                              :style="{ width: '100%' }"
                              :maskConfig="maskConfig.mdmCompanyBankremark"
                              :showCount="false">
                            </YunzhupaasInput>
                          </template>
                          <template v-if="column.key === 'action'">
                            <a-space>
                              <a-button class="action-btn" type="link" @click="copyMdmCompanyBankRow(index)" size="small">
                                {{ t('common.copyText', '复制') }}
                              </a-button>
                              <a-button class="action-btn" type="link" color="error" @click="removeMdmCompanyBankRow(index, true)" size="small">
                                {{ t('common.delText', '删除') }}
                              </a-button>
                            </a-space>
                          </template>
                        </template>
                      </a-table>
                      <a-space class="input-table-footer-btn">
                        <a-button type="primary" preIcon="icon-ym icon-ym-btn-add" @click="addMdmCompanyBankRow"> {{ t('common.add1Text', '添加') }} </a-button>
                        <a-button type="danger" preIcon="icon-ym icon-ym-btn-clearn" @click="batchRemoveMdmCompanyBankRow(true)">
                          {{ t('common.batchDelText', '批量删除') }}
                        </a-button>
                      </a-space>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-tab-pane>
            </a-tabs>
          </a-col>
          <!-- 表单结束 -->
        </a-row>
      </a-form>
    </a-row>
  </BasicPopup>
</template>
<script lang="ts" setup>
  import { create, update, getInfo } from './helper/api';
  import { reactive, toRefs, nextTick, ref, unref, computed, toRaw, inject } from 'vue';
  import { BasicPopup, usePopup } from '@/components/Popup';
  import { yunzhupaasRelationForm } from '@/components/yunzhupaas';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useUserStore } from '@/store/modules/user';
  import type { FormInstance } from 'ant-design-vue';
  import { thousandsFormat, getDateTimeUnit, getTimeUnit } from '@/utils/yunzhupaas';
  import { getDictionaryDataSelector } from '@/api/systemData/dictionary';
  import { getDataInterfaceRes } from '@/api/systemData/dataInterface';
  import dayjs from 'dayjs';
  // 表单权限
  import { usePermission } from '@/hooks/web/usePermission';
  import { cloneDeep } from 'lodash-es';
  import { buildUUID } from '@/utils/uuid';
  import { CaretRightOutlined } from '@ant-design/icons-vue';

  interface State {
    dataForm: any;
    tableRows: any;
    dataRule: any;
    optionsObj: any;
    childIndex: any;
    isEdit: any;
    interfaceRes: any;
    //可选范围默认值
    ableAll: any;
    //掩码配置
    maskConfig: any;
    //定位属性
    locationScope: any;
    activetabformItem5e5d3b: any;
    selectedmdmCompanyContactRowKeys: any;
    selectedmdmCompanyBankRowKeys: any;
    extraOptions: any;
    title: string;
    continueText: string;
    allList: any[];
    currIndex: number;
    isContinue: boolean;
    submitType: number;
    showContinueBtn: boolean;
  }

  const emit = defineEmits(['reload']);
  const getLeftTreeActiveInfo: (() => any) | null = inject('getLeftTreeActiveInfo', null);
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const { createMessage, createConfirm } = useMessage();
  const { t } = useI18n();
  const [registerPopup, { openPopup, setPopupProps }] = usePopup();
  const formRef = ref<FormInstance>();
  const mdmCompanyContactColumns: any[] = computed(() => {
    let list = [
      {
        title: '联系人',
        dataIndex: 'contact_name',
        key: 'contact_name',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'contact_name',
      },
      {
        title: '联系人职务',
        dataIndex: 'contact_title',
        key: 'contact_title',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'contact_title',
      },
      {
        title: '电话',
        dataIndex: 'contact_phone',
        key: 'contact_phone',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'contact_phone',
      },
      {
        title: '邮箱',
        dataIndex: 'contact_email',
        key: 'contact_email',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'contact_email',
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'remark',
      },
    ];
    list.push({ title: t('component.table.action'), showLabel: true, dataIndex: 'action', key: 'action', align: 'center', fixed: 'right', width: 100 });
    const indexColumn = { title: t('component.table.index'), showLabel: true, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left', width: 50 };
    //子表复杂表头-处理
    let columnList = list;
    let complexHeaderList: any[] = [];
    if (complexHeaderList.length) {
      let childColumns: any[] = [];
      let firstChildColumns: string[] = [];
      for (let i = 0; i < complexHeaderList.length; i++) {
        const e = complexHeaderList[i];
        e.title = e.fullNameI18nCode ? t(e.fullNameI18nCode, e.fullName) : e.fullName;
        e.align = e.align;
        e.children = [];
        e.yunzhupaasKey = 'complexHeader';
        if (e.childColumns?.length) {
          childColumns.push(...e.childColumns);
          for (let k = 0; k < e.childColumns.length; k++) {
            const item = e.childColumns[k];
            for (let j = 0; j < list.length; j++) {
              const o = list[j];
              if (o.key == item && o.fixed !== 'left' && o.fixed !== 'right') e.children.push({ ...o });
            }
          }
        }
        if (e.children.length) firstChildColumns.push(e.children[0].key);
      }
      complexHeaderList = complexHeaderList.filter(o => o.children.length);
      let newList: any[] = [];
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        if (!childColumns.includes(e.key) || e.fixed === 'left' || e.fixed === 'right') {
          newList.push(e);
        } else {
          if (firstChildColumns.includes(e.key)) {
            const item = complexHeaderList.find(o => o.childColumns.includes(e.key));
            newList.push(item);
          }
        }
      }
      columnList = newList;
    }
    let columns = [indexColumn, ...columnList];
    const leftFixedList = columns.filter(o => o.fixed === 'left');
    const rightFixedList = columns.filter(o => o.fixed === 'right');
    const noFixedList = columns.filter(o => o.fixed !== 'left' && o.fixed !== 'right');
    return [...leftFixedList, ...noFixedList, ...rightFixedList];
  });

  const getmdmCompanyContactHasBatchBtn = computed(() => {
    let flist: any[] = [
      { btnIcon: 'icon-ym icon-ym-btn-add', show: true, label: '添加', btnType: 'primary', value: 'add', labelI18nCode: 'common.add1Text' },
      {
        btnIcon: 'icon-ym icon-ym-btn-clearn',
        showConfirm: 'true',
        show: true,
        label: '批量删除',
        btnType: 'danger',
        value: 'batchRemove',
        labelI18nCode: 'common.batchDelText',
      },
    ];
    return flist?.length && flist.some(o => o.value == 'batchRemove' && !!o.show);
  });

  const getmdmCompanyContactRowSelection = computed(() => {
    if (!unref(getmdmCompanyContactHasBatchBtn)) return undefined;
    const rowSelection = {
      selectedRowKeys: state.selectedmdmCompanyContactRowKeys,
      onChange: (selectedRowKeys: string[]) => {
        state.selectedmdmCompanyContactRowKeys = selectedRowKeys;
      },
    };
    return rowSelection;
  });

  const mdmCompanyBankColumns: any[] = computed(() => {
    let list = [
      {
        title: '银行账号',
        dataIndex: 'bank_account_number',
        key: 'bank_account_number',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'bank_account_number',
      },
      {
        title: '开户行',
        dataIndex: 'bank_name',
        key: 'bank_name',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'bank_name',
      },
      {
        title: '账户名',
        dataIndex: 'bank_account_name',
        key: 'bank_account_name',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'bank_account_name',
      },
      {
        title: '开户行城市',
        dataIndex: 'bank_province',
        key: 'bank_province',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'bank_province',
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        labelWidth: '',
        span: '24',
        tipLabel: '',
        required: false,
        style: { width: '100%' },
        align: 'left',
        fixed: false,
        formP: 'remark',
      },
    ];
    list.push({ title: t('component.table.action'), showLabel: true, dataIndex: 'action', key: 'action', align: 'center', fixed: 'right', width: 100 });
    const indexColumn = { title: t('component.table.index'), showLabel: true, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left', width: 50 };
    //子表复杂表头-处理
    let columnList = list;
    let complexHeaderList: any[] = [];
    if (complexHeaderList.length) {
      let childColumns: any[] = [];
      let firstChildColumns: string[] = [];
      for (let i = 0; i < complexHeaderList.length; i++) {
        const e = complexHeaderList[i];
        e.title = e.fullNameI18nCode ? t(e.fullNameI18nCode, e.fullName) : e.fullName;
        e.align = e.align;
        e.children = [];
        e.yunzhupaasKey = 'complexHeader';
        if (e.childColumns?.length) {
          childColumns.push(...e.childColumns);
          for (let k = 0; k < e.childColumns.length; k++) {
            const item = e.childColumns[k];
            for (let j = 0; j < list.length; j++) {
              const o = list[j];
              if (o.key == item && o.fixed !== 'left' && o.fixed !== 'right') e.children.push({ ...o });
            }
          }
        }
        if (e.children.length) firstChildColumns.push(e.children[0].key);
      }
      complexHeaderList = complexHeaderList.filter(o => o.children.length);
      let newList: any[] = [];
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        if (!childColumns.includes(e.key) || e.fixed === 'left' || e.fixed === 'right') {
          newList.push(e);
        } else {
          if (firstChildColumns.includes(e.key)) {
            const item = complexHeaderList.find(o => o.childColumns.includes(e.key));
            newList.push(item);
          }
        }
      }
      columnList = newList;
    }
    let columns = [indexColumn, ...columnList];
    const leftFixedList = columns.filter(o => o.fixed === 'left');
    const rightFixedList = columns.filter(o => o.fixed === 'right');
    const noFixedList = columns.filter(o => o.fixed !== 'left' && o.fixed !== 'right');
    return [...leftFixedList, ...noFixedList, ...rightFixedList];
  });

  const getmdmCompanyBankHasBatchBtn = computed(() => {
    let flist: any[] = [
      { btnIcon: 'icon-ym icon-ym-btn-add', show: true, label: '添加', btnType: 'primary', value: 'add', labelI18nCode: 'common.add1Text' },
      {
        btnIcon: 'icon-ym icon-ym-btn-clearn',
        showConfirm: 'true',
        show: true,
        label: '批量删除',
        btnType: 'danger',
        value: 'batchRemove',
        labelI18nCode: 'common.batchDelText',
      },
    ];
    return flist?.length && flist.some(o => o.value == 'batchRemove' && !!o.show);
  });

  const getmdmCompanyBankRowSelection = computed(() => {
    if (!unref(getmdmCompanyBankHasBatchBtn)) return undefined;
    const rowSelection = {
      selectedRowKeys: state.selectedmdmCompanyBankRowKeys,
      onChange: (selectedRowKeys: string[]) => {
        state.selectedmdmCompanyBankRowKeys = selectedRowKeys;
      },
    };
    return rowSelection;
  });

  const state = reactive<State>({
    dataForm: {
      company_code: undefined,
      company_name: undefined,
      short_name: undefined,
      entity_type: 'ORG',
      credit_code: undefined,
      company_scope: 'EXT',
      tax_type: '',
      enterprise_scale: '',
      enterprise_nature: '',
      industry_code: '',
      registration_date: undefined,
      registered_capital: undefined,
      legal_representative: undefined,
      phone: undefined,
      email: undefined,
      website: undefined,
      address: undefined,
      province_id: [],
      business_scope: undefined,
      remark: undefined,
      owner_id: userInfo.userId ? userInfo.userId : '',
      org_id: userInfo.organizeIdList ? userInfo.organizeIdList : '',
      customer_level: '',
      customer_lifecycle: '',
      is_public: 'N',
      last_followup_date: undefined,
      mdmCompanyContactList: [],
      mdmCompanyBankList: [],
      version: 0,
    },

    tableRows: {
      mdmCompanyContactList: {
        contact_name: '',
        contact_title: '',
        contact_phone: '',
        contact_email: '',
        remark: '',
        enabledmark: undefined,
      },
      mdmCompanyBankList: {
        bank_account_number: '',
        bank_name: '',
        bank_account_name: '',
        bank_province: '',
        remark: '',
        enabledmark: undefined,
      },
    },

    dataRule: {
      company_name: [
        {
          required: true,
          message: t('sys.validate.textRequiredSuffix', '不能为空'),
          trigger: 'blur',
        },
      ],
      entity_type: [
        {
          required: true,
          message: t('sys.validate.textRequiredSuffix', '不能为空'),
          trigger: 'change',
        },
      ],
      credit_code: [
        {
          required: true,
          message: t('sys.validate.textRequiredSuffix', '不能为空'),
          trigger: 'blur',
        },
      ],
      company_scope: [
        {
          required: true,
          message: t('sys.validate.arrayRequiredPrefix	', '请至少选择一个'),
          trigger: 'change',
        },
      ],
      is_public: [
        {
          required: true,
          message: t('sys.validate.arrayRequiredPrefix	', '请选择一个'),
          trigger: 'change',
        },
      ],
      phone: [
        {
          pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
          message: t('sys.validate.mobilePhone', '请输入正确的手机号码'),
          trigger: 'blur',
        },
      ],
      email: [
        {
          pattern: /^[a-z0-9]+([._\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
          message: t('sys.validate.email', '请输入正确的邮箱'),
          trigger: 'blur',
        },
      ],
      owner_id: [
        {
          required: true,
          message: t('sys.validate.arrayRequiredPrefix	', '请至少选择一个'),
          trigger: 'change',
        },
      ],
      org_id: [
        {
          required: true,
          message: t('sys.validate.arrayRequiredPrefix	', '请至少选择一个'),
          trigger: 'change',
        },
      ],
    },

    optionsObj: {
      entity_typeOptions: [
        { fullName: '企业', id: 'ORG' },
        { fullName: '个人', id: 'IND' },
      ],
      entity_typeProps: { label: 'fullName', value: 'id' },
      company_scopeOptions: [
        { fullName: '内部公司', id: 'INT' },
        { fullName: '客商企业', id: 'EXT' },
      ],
      company_scopeProps: { label: 'fullName', value: 'id' },
      tax_typeOptions: [
        { fullName: '一般纳税人', id: 'GENERAL' },
        { fullName: '小规模纳税人', id: 'SMALL' },
      ],
      tax_typeProps: { label: 'fullName', value: 'id' },
      enterprise_scaleOptions: [],
      enterprise_scaleProps: { label: 'fullName', value: 'enCode' },
      enterprise_natureOptions: [],
      enterprise_natureProps: { label: 'fullName', value: 'enCode' },
      industry_codeOptions: [],
      industry_codeProps: { label: 'fullName', value: 'enCode' },
      customer_levelOptions: [],
      customer_levelProps: { label: 'fullName', value: 'enCode' },
      customer_lifecycleOptions: [],
      customer_lifecycleProps: { label: 'fullName', value: 'enCode' },
      is_publicOptions: [
        { fullName: '是', id: 'Y' },
        { fullName: '否', id: 'N' },
      ],
      is_publicProps: { label: 'fullName', value: 'id' },
    },

    childIndex: -1,
    isEdit: false,
    interfaceRes: {
      mdmCompanyBankbank_name: [],
      mdmCompanyBankbank_account_name: [],
      company_scope: [],
      owner_id: [],
      industry_code: [],
      customer_level: [],
      mdmCompanyContactcontact_email: [],
      remark: [],
      is_public: [],
      mdmCompanyBankbank_province: [],
      customer_lifecycle: [],
      credit_code: [],
      mdmCompanyBankbank_account_number: [],
      company_code: [],
      email: [],
      mdmCompanyContactcontact_title: [],
      website: [],
      address: [],
      mdmCompanyContactcontact_name: [],
      legal_representative: [],
      enterprise_nature: [],
      registered_capital: [],
      business_scope: [],
      mdmCompanyContactcontact_phone: [],
      mdmCompanyBankremark: [],
      entity_type: [],
      registration_date: [],
      tax_type: [],
      phone: [],
      province_id: [],
      org_id: [],
      company_name: [],
      short_name: [],
      last_followup_date: [],
      enterprise_scale: [],
      mdmCompanyContactremark: [],
    },
    //可选范围默认值
    ableAll: {},

    //掩码配置
    maskConfig: {
      company_code: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      company_name: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      short_name: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      credit_code: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      legal_representative: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      phone: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      email: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      website: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      address: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyContactcontact_name: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyContactcontact_title: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyContactcontact_phone: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyContactcontact_email: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyContactremark: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyBankbank_account_number: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyBankbank_name: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyBankbank_account_name: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyBankbank_province: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      mdmCompanyBankremark: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
    },

    //定位属性
    locationScope: {},

    activetabformItem5e5d3b: '1',
    selectedmdmCompanyContactRowKeys: [],
    selectedmdmCompanyBankRowKeys: [],
    extraOptions: {},

    title: '',
    continueText: '',
    allList: [],
    currIndex: 0,
    isContinue: false,
    submitType: 0,
    showContinueBtn: true,
  });
  const { title, continueText, showContinueBtn, dataRule, dataForm, optionsObj, ableAll, maskConfig, submitType } = toRefs(state);

  const getPrevDisabled = computed(() => state.currIndex === 0);
  const getNextDisabled = computed(() => state.currIndex === state.allList.length - 1);
  // 表单权限
  const { hasFormP } = usePermission();

  defineExpose({ init });

  function init(data) {
    state.submitType = 0;
    state.isContinue = false;
    state.title = !data.id ? t('common.add2Text', '新增') : t('common.editText', '编辑');
    state.continueText = !data.id ? t('common.continueAndAddText', '确定并新增') : t('common.continueText', '确定并继续');
    setFormProps({ continueLoading: false });
    state.dataForm.id = data.id;
    openPopup();
    state.allList = data.allList;
    state.currIndex = state.allList.length && data.id ? state.allList.findIndex(item => item.id === data.id) : 0;
    nextTick(() => {
      getForm().resetFields();
      state.dataForm.mdmCompanyContactList = [];
      state.dataForm.mdmCompanyBankList = [];
      setTimeout(initData, 0);
    });
  }
  function initData() {
    changeLoading(true);
    state.activetabformItem5e5d3b = '1';
    if (state.dataForm.id) {
      getData(state.dataForm.id);
    } else {
      //初始化options
      getenterprise_scaleOptions();
      getenterprise_natureOptions();
      getindustry_codeOptions();
      getcustomer_levelOptions();
      getcustomer_lifecycleOptions();

      if (state.dataForm.mdmCompanyContactList) {
        for (let i = 0; i < state.dataForm.mdmCompanyContactList.length; i++) {
          state.childIndex = i;
          state.dataForm.mdmCompanyContactList[i].yunzhupaasId = buildUUID();
        }
      }
      if (state.dataForm.mdmCompanyBankList) {
        for (let i = 0; i < state.dataForm.mdmCompanyBankList.length; i++) {
          state.childIndex = i;
          state.dataForm.mdmCompanyBankList[i].yunzhupaasId = buildUUID();
        }
      }
      // 设置默认值
      state.dataForm = {
        company_code: undefined,
        company_name: undefined,
        short_name: undefined,
        entity_type: 'ORG',
        credit_code: undefined,
        company_scope: 'EXT',
        tax_type: '',
        enterprise_scale: '',
        enterprise_nature: '',
        industry_code: '',
        registration_date: undefined,
        registered_capital: undefined,
        legal_representative: undefined,
        phone: undefined,
        email: undefined,
        website: undefined,
        address: undefined,
        province_id: [],
        business_scope: undefined,
        remark: undefined,
        owner_id: userInfo.userId ? userInfo.userId : '',
        org_id: userInfo.organizeIdList ? userInfo.organizeIdList : '',
        customer_level: '',
        customer_lifecycle: '',
        is_public: 'N',
        last_followup_date: undefined,
        mdmCompanyContactList: [],
        mdmCompanyBankList: [],
        version: 0,
      };
      if (getLeftTreeActiveInfo) state.dataForm = { ...state.dataForm, ...(getLeftTreeActiveInfo() || {}) };
      state.childIndex = -1;
      changeLoading(false);
    }
  }
  function getForm() {
    const form = unref(formRef);
    if (!form) {
      throw new Error('form is null!');
    }
    return form;
  }
  function getData(id) {
    getInfo(id).then(res => {
      state.dataForm = res.data || {};
      getenterprise_scaleOptions();
      getenterprise_natureOptions();
      getindustry_codeOptions();
      getcustomer_levelOptions();
      getcustomer_lifecycleOptions();
      if (res.data?.crmCustomer != null) {
        state.dataForm.owner_id = res.data.crmCustomer.ownerId;
        state.dataForm.org_id = JSON.parse(res.data.crmCustomer.orgId);
        state.dataForm.customer_level = res.data.crmCustomer.customerLevel;
        state.dataForm.customer_lifecycle = res.data.crmCustomer.customerLifecycle;
        state.dataForm.is_public = res.data.crmCustomer.isPublic;
        state.dataForm.last_followup_date = res.data.crmCustomer.lastFollowupDate;
        
      }

      if (state.dataForm.mdmCompanyContactList) {
        for (let i = 0; i < state.dataForm.mdmCompanyContactList.length; i++) {
          state.childIndex = i;
          state.dataForm.mdmCompanyContactList[i].yunzhupaasId = buildUUID();
        }
      }
      if (state.dataForm.mdmCompanyBankList) {
        for (let i = 0; i < state.dataForm.mdmCompanyBankList.length; i++) {
          state.childIndex = i;
          state.dataForm.mdmCompanyBankList[i].yunzhupaasId = buildUUID();
        }
      }
      state.childIndex = -1;
      changeLoading(false);
    });
  }
  async function handleSubmit(type) {
    try {
      const values = await getForm()?.validate();
      if (!values) return;
      if (!mdmCompanyContactExist()) return;
      if (!mdmCompanyBankExist()) return;

      setFormProps({ confirmLoading: true });
      const formMethod = state.dataForm.id ? update : create;
      formMethod(state.dataForm)
        .then(res => {
          createMessage.success(res.msg);
          setFormProps({ confirmLoading: false });
          if (state.submitType == 1) {
            initData();
            state.isContinue = true;
          } else {
            setFormProps({ open: false });
            emit('reload');
          }
        })
        .catch(() => {
          setFormProps({ confirmLoading: false });
        });
    } catch (_) {}
  }
  function handlePrev() {
    state.currIndex--;
    handleGetNewInfo();
  }
  function handleNext() {
    state.currIndex++;
    handleGetNewInfo();
  }
  function handleGetNewInfo() {
    changeLoading(true);
    getForm().resetFields();
    const id = state.allList[state.currIndex].id;
    getData(id);
  }
  function setFormProps(data) {
    setPopupProps(data);
  }
  function changeLoading(loading) {
    setPopupProps({ loading });
  }
  async function onClose() {
    if (state.isContinue) emit('reload');
    return true;
  }

  function changeData(model, index) {
    state.isEdit = false;
    state.childIndex = index;
    for (let key in state.interfaceRes) {
      if (key != model) {
        let faceReList = state.interfaceRes[key];
        for (let i = 0; i < faceReList.length; i++) {
          let relationField = faceReList[i].relationField;
          if (relationField) {
            let modelAll = relationField.split('-');
            let faceMode = '';
            let faceMode2 = modelAll.length == 2 ? modelAll[0].substring(0, modelAll[0].length - 4) + modelAll[1] : '';
            for (let i = 0; i < modelAll.length; i++) {
              faceMode += modelAll[i];
            }
            if (faceMode == model || faceMode2 == model) {
              let options = 'get' + key + 'Options';
              eval(options)(true);
              changeData(key, index);
            }
          }
        }
      }
    }
  }
  function changeDataFormData(type, data, model, index, defaultValue) {
    if (!state.isEdit) {
      if (type == 2) {
        for (let i = 0; i < state.dataForm[data].length; i++) {
          if (index == -1) {
            state.dataForm[data][i][model] = defaultValue;
          } else if (index == i) {
            state.dataForm[data][i][model] = defaultValue;
          }
        }
      } else {
        state.dataForm[data] = defaultValue;
      }
    }
  }
  function addMdmCompanyContactRow() {
    let item = {
      contact_name: undefined,
      contact_title: undefined,
      contact_phone: undefined,
      contact_email: undefined,
      remark: undefined,
      yunzhupaasId: buildUUID(),
    };
    state.dataForm.mdmCompanyContactList.push(item);
    state.childIndex = state.dataForm.mdmCompanyContactList.length - 1;
    state.childIndex = -1;
  }

  function removeMdmCompanyContactRow(index, showConfirm = false) {
    if (showConfirm) {
      createConfirm({
        iconType: 'warning',
        title: '提示',
        content: '此操作将永久删除该数据, 是否继续?',
        onOk: () => {
          state.dataForm.mdmCompanyContactList.splice(index, 1);
        },
      });
    } else {
      state.dataForm.mdmCompanyContactList.splice(index, 1);
    }
  }

  function copyMdmCompanyContactRow(index) {
    let item = cloneDeep(state.dataForm.mdmCompanyContactList[index]);
    let copyData = {};
    for (let i = 0; i < unref(mdmCompanyContactColumns).length; i++) {
      const cur = unref(mdmCompanyContactColumns)[i];
      if (cur.key != 'index' && cur.key != 'action') {
        if (cur.children?.length && cur.yunzhupaasKey == 'complexHeader') {
          for (let j = 0; j < cur.children.length; j++) {
            copyData[cur.children[j].key] = item[cur.children[j].key];
          }
        } else {
          copyData[cur.key] = item[cur.key];
        }
      }
    }
    const copyItem = { ...copyData, yunzhupaasId: buildUUID() };
    state.dataForm.mdmCompanyContactList.push(copyItem);
    state.childIndex = state.dataForm.mdmCompanyContactList.length - 1;
    state.childIndex = -1;
  }

  function batchRemoveMdmCompanyContactRow(showConfirm = false) {
    if (!state.selectedmdmCompanyContactRowKeys.length) return createMessage.error('请选择一条数据');
    const handleRemove = () => {
      state.dataForm.mdmCompanyContactList = state.dataForm.mdmCompanyContactList.filter(o => !state.selectedmdmCompanyContactRowKeys.includes(o.yunzhupaasId));
      nextTick(() => {
        state.selectedmdmCompanyContactRowKeys = [];
      });
    };
    if (showConfirm) {
      createConfirm({
        iconType: 'warning',
        title: '提示',
        content: '此操作将永久删除该数据, 是否继续?',
        onOk: () => {
          handleRemove();
        },
      });
    } else {
      handleRemove();
    }
  }

  function mdmCompanyContactExist() {
    let isOk = true;
    for (let i = 0; i < state.dataForm.mdmCompanyContactList.length; i++) {
      const e = state.dataForm.mdmCompanyContactList[i];
    }
    return isOk;
  }

  function addMdmCompanyBankRow() {
    let item = {
      bank_account_number: undefined,
      bank_name: undefined,
      bank_account_name: undefined,
      bank_province: undefined,
      remark: undefined,
      yunzhupaasId: buildUUID(),
    };
    state.dataForm.mdmCompanyBankList.push(item);
    state.childIndex = state.dataForm.mdmCompanyBankList.length - 1;
    state.childIndex = -1;
  }

  function removeMdmCompanyBankRow(index, showConfirm = false) {
    if (showConfirm) {
      createConfirm({
        iconType: 'warning',
        title: '提示',
        content: '此操作将永久删除该数据, 是否继续?',
        onOk: () => {
          state.dataForm.mdmCompanyBankList.splice(index, 1);
        },
      });
    } else {
      state.dataForm.mdmCompanyBankList.splice(index, 1);
    }
  }

  function copyMdmCompanyBankRow(index) {
    let item = cloneDeep(state.dataForm.mdmCompanyBankList[index]);
    let copyData = {};
    for (let i = 0; i < unref(mdmCompanyBankColumns).length; i++) {
      const cur = unref(mdmCompanyBankColumns)[i];
      if (cur.key != 'index' && cur.key != 'action') {
        if (cur.children?.length && cur.yunzhupaasKey == 'complexHeader') {
          for (let j = 0; j < cur.children.length; j++) {
            copyData[cur.children[j].key] = item[cur.children[j].key];
          }
        } else {
          copyData[cur.key] = item[cur.key];
        }
      }
    }
    const copyItem = { ...copyData, yunzhupaasId: buildUUID() };
    state.dataForm.mdmCompanyBankList.push(copyItem);
    state.childIndex = state.dataForm.mdmCompanyBankList.length - 1;
    state.childIndex = -1;
  }

  function batchRemoveMdmCompanyBankRow(showConfirm = false) {
    if (!state.selectedmdmCompanyBankRowKeys.length) return createMessage.error('请选择一条数据');
    const handleRemove = () => {
      state.dataForm.mdmCompanyBankList = state.dataForm.mdmCompanyBankList.filter(o => !state.selectedmdmCompanyBankRowKeys.includes(o.yunzhupaasId));
      nextTick(() => {
        state.selectedmdmCompanyBankRowKeys = [];
      });
    };
    if (showConfirm) {
      createConfirm({
        iconType: 'warning',
        title: '提示',
        content: '此操作将永久删除该数据, 是否继续?',
        onOk: () => {
          handleRemove();
        },
      });
    } else {
      handleRemove();
    }
  }

  function mdmCompanyBankExist() {
    let isOk = true;
    for (let i = 0; i < state.dataForm.mdmCompanyBankList.length; i++) {
      const e = state.dataForm.mdmCompanyBankList[i];
    }
    return isOk;
  }

  //数据选项--数据字典初始化方法
  function getenterprise_scaleOptions() {
    getDictionaryDataSelector('797424039713832965').then(res => {
      state.optionsObj.enterprise_scaleOptions = res.data.list;
    });
  }
  //数据选项--数据字典初始化方法
  function getenterprise_natureOptions() {
    getDictionaryDataSelector('9b542177a477488994ce09fff3c93901').then(res => {
      state.optionsObj.enterprise_natureOptions = res.data.list;
    });
  }
  //数据选项--数据字典初始化方法
  function getindustry_codeOptions() {
    getDictionaryDataSelector('d59a3cf65f9847dbb08be449e3feae16').then(res => {
      state.optionsObj.industry_codeOptions = res.data.list;
    });
  }
  //数据选项--数据字典初始化方法
  function getcustomer_levelOptions() {
    getDictionaryDataSelector('797390895816114181').then(res => {
      state.optionsObj.customer_levelOptions = res.data.list;
    });
  }
  //数据选项--数据字典初始化方法
  function getcustomer_lifecycleOptions() {
    getDictionaryDataSelector('797391011549544453').then(res => {
      state.optionsObj.customer_lifecycleOptions = res.data.list;
    });
  }
  function getRelationDate(timeRule, timeType, timeTarget, timeValueData, dataValue) {
    let timeDataValue: any = null;
    let timeValue = Number(timeValueData);
    if (timeRule) {
      if (timeType == 1) {
        timeDataValue = timeValue;
      } else if (timeType == 2) {
        timeDataValue = dataValue;
      } else if (timeType == 3) {
        timeDataValue = new Date().getTime();
      } else if (timeType == 4 || timeType == 5) {
        const type = getTimeUnit(timeTarget);
        const method = timeType == 4 ? 'subtract' : 'add';
        timeDataValue = dayjs()[method](timeValue, type).valueOf();
      }
    }
    return timeDataValue;
  }
  function getRelationTime(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
    let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType;
    let timeDataValue: any = null;
    if (timeRule) {
      if (timeType == 1) {
        timeDataValue = timeValue || '00:00:00';
        if (timeDataValue.split(':').length == 3) {
          timeDataValue = timeDataValue;
        } else {
          timeDataValue = timeDataValue + ':00';
        }
      } else if (timeType == 2) {
        timeDataValue = dataValue;
      } else if (timeType == 3) {
        timeDataValue = dayjs().format(format);
      } else if (timeType == 4 || timeType == 5) {
        const type = getTimeUnit(timeTarget + 3);
        const method = timeType == 4 ? 'subtract' : 'add';
        timeDataValue = dayjs()[method](timeValue, type).format(format);
      }
    }
    return timeDataValue;
  }
</script>
