
<template>
  <div class="jeepay-m-center" style="margin-top: 5px; margin-left: 20px;">
    <a-steps v-show="(vdata.showStyle == showStyleEnum.step)&& !isMobile" :current="vdata.currentStep - 1" type="navigation">
      <a-step title="主体信息" />
      <a-step title="经营信息" />
      <a-step title="结算账户" />
      <a-step title="签约信息" />
      <a-step title="费率配置"/>
    </a-steps>
    <a-divider v-show="!isMobile" />
    <a-divider v-show="isMobile" class="jeepay-m-divider" orientation="left" style="color: #1A66FF;"><span style="color: #2980FD;">{{ vdata.currentStep }}</span>/{{ vdata.steps.length }} {{ vdata.steps[vdata.currentStep - 1] }}</a-divider>
    <!-- 1. 主体信息  -->
    <a-form
        v-show="vdata.showStyle == showStyleEnum.block || vdata.currentStep == 1"
        ref="stepForm1Ref"
        style="margin-top: 20px;"
        :model="applymentDetailInfo"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 8 }"
        :rules="vdata.step1Rules"
    >
      <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">基础项</a-divider>
      <!-- <a-form-item label="进件方式" name="applyType">
        <a-radio-group v-model:value="applymentDetailInfo.applyType">
          <a-radio :value="1">
            普通进件
            <a-tooltip title="需提交证件信息">
              <info-circle-outlined />
            </a-tooltip>
          </a-radio>
          <a-radio :value="2">
            免证件进件
            <a-tooltip title="提供已实名认证的支付宝账号免提交证照进件">
              <info-circle-outlined />
            </a-tooltip>
          </a-radio>
        </a-radio-group>
      </a-form-item> -->
      <div>
        <a-form-item label="商户类型" name="merchantType">
          <a-radio-group v-model:value="applymentDetailInfo.merchantType"  @change="changeMerchantType">
            <a-radio :value="1">小微</a-radio>
            <a-radio :value="2">个体工商户</a-radio>
            <a-radio :value="3">企业</a-radio>
          </a-radio-group>
        </a-form-item>

        <div v-if="applymentDetailInfo.merchantType != 1">
          <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">营业执照</a-divider>

          <a-form-item label="营业执照照片" name="licenseImg">
            <JeepayUpload v-model:src="applymentDetailInfo.licenseImg" bizType="applyment" ocrType="license" @ocrScan="ocrScanFunc" />
            <span class="jeepay-tip-text">(上传图片自动识别 营业执照编号)</span>
          </a-form-item>

          <a-form-item label="营业执照编号" name="licenseNo">
            <a-input v-model:value.trim="applymentDetailInfo.licenseNo" />
          </a-form-item>
        </div>

        <a-form-item label="营业执照名称" name="mchFullName" v-if="applymentDetailInfo.merchantType != 1">
          <a-input v-model:value.trim="applymentDetailInfo.mchFullName" />
          <!--          <span class="jeepay-tip-text">(个体工商户可放宽至法人姓名)</span>-->
        </a-form-item>

        <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">法定代表人证件</a-divider>

        <a-form-item label="法人身份证人像面照片" name="idcard1Img">
          <JeepayUpload v-model:src="applymentDetailInfo.idcard1Img" bizType="applyment" ocrType="idCard" @ocrScan="ocrScanFunc" />
          <span class="jeepay-tip-text">(上传图片自动识别 身份证名称 身份证号)</span>
        </a-form-item>

        <a-form-item label="法人身份证国徽面照片" name="idcard2Img">
          <JeepayUpload v-model:src="applymentDetailInfo.idcard2Img" bizType="applyment" ocrType="idCard" @ocrScan="ocrScanFunc" />
          <span class="jeepay-tip-text">(上传图片自动识别 有效期)</span>
        </a-form-item>

        <a-form-item label="法人身份证姓名" name="idcardName">
          <a-input v-model:value.trim="applymentDetailInfo.idcardName" />
        </a-form-item>

        <a-form-item label="法人身份证号" name="idcardNo">
          <a-input v-model:value.trim="applymentDetailInfo.idcardNo" />
        </a-form-item>

        <a-form-item label="法人身份证起始有效期" name="idcardEffectBegin">
          <a-input v-model:value.trim="applymentDetailInfo.idcardEffectBegin" />
        </a-form-item>

        <a-form-item class="jeepay-valid" label="法人身份证结束有效期" name="idcardEffectEnd">
          <a-input v-model:value.trim="applymentDetailInfo.idcardEffectEnd" :disabled="applymentDetailInfo.idcardEffectEnd == '长期'" style="width: 150px;margin-right: 10px;" />
          <a-checkbox :checked="applymentDetailInfo.idcardEffectEnd == '长期' " @change="(e) => applymentDetailInfo.idcardEffectEnd = e.target.checked ? '长期' : '' ">长期</a-checkbox>
        </a-form-item>
      </div>
    </a-form>

    <!-- 2. 经营信息  -->
    <a-form
        v-show="vdata.showStyle == showStyleEnum.block || vdata.currentStep == 2"
        ref="stepForm2Ref"
        :model="applymentDetailInfo"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 8 }"
        :rules="vdata.step2Rules"
    >
      <a-form-item label="用户名称" name="mchFullName" v-if="applymentDetailInfo.merchantType == 1">
        <a-input v-model:value.trim="applymentDetailInfo.mchFullName" />
        <span class="jeepay-tip-text">小微必须使用法人名称</span>
      </a-form-item>
      <a-form-item label="商户简称" name="mchShortName">
        <a-input v-model:value.trim="applymentDetailInfo.mchShortName" />
        <span class="jeepay-tip-text">在支付完成页向买家展示</span>
      </a-form-item>
      <a-form-item label="经营类目" name="mccCode">
        <JeepayZftMccSelect v-model:value="applymentDetailInfo.mccCode" @change="changeMccFunc" />
      </a-form-item>

      <a-form-item label="资质图片" name="industryQualificationImage">
        <JeepayUpload v-model:src="applymentDetailInfo.industryQualificationImage" bizType="applyment" />
        <span class="jeepay-tip-text">特殊经营类目需上传资质</span>
      </a-form-item>



      <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">经营信息</a-divider>

      <a-form-item label="是否为法人（自动补全）" name="isLegalInfo">
        <a-radio-group v-model:value="applymentDetailInfo.isLegalInfo"
                       @change="funLegalInfo(applymentDetailInfo.isLegalInfo)">
          <a-radio value="1">是</a-radio>
          <a-radio value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>


      <a-form-item label="商户联系人姓名" name="contactName">
        <a-input v-model:value.trim="applymentDetailInfo.contactName" />
      </a-form-item>

      <a-form-item label="商户联系人手机号" name="contactPhone">
        <a-input v-model:value.trim="applymentDetailInfo.contactPhone" />
      </a-form-item>

      <a-form-item label="商户经营省市县" name="areaCode">
        <JeepayAreaSelect v-model:value="applymentDetailInfo.areaCode" @change="changeMchAreaFunc"/>
      </a-form-item>

      <a-form-item label="商户经营地址" name="address">
        <a-input v-model:value.trim="applymentDetailInfo.mchAddress" :addon-before="applymentDetailInfo.mchAddressCodeName"  @change="changeMchAddressFunc"/>
        <span class="jeepay-tip-text" v-if="applymentDetailInfo.address">请输入详细经营地址,需要精确到门牌号</span>
      </a-form-item>

      <a-form-item label="门头照" name="storeOuterImg">
        <JeepayUpload v-model:src="applymentDetailInfo.storeOuterImg" bizType="applyment" />
      </a-form-item>

      <a-form-item label="店内环境照" name="storeInnerImg">
        <JeepayUpload v-model:src="applymentDetailInfo.storeInnerImg" bizType="applyment" />
      </a-form-item>
      <a-form-item label="收银台照" name="storeCashierImg">
        <JeepayUpload v-model:src="applymentDetailInfo.storeCashierImg" bizType="applyment" :imgSize="2"/>
      </a-form-item>
      <a-form-item label="结算人在收银台内合影" name="cashierWithSettlerImg">
        <JeepayUpload v-model:src="applymentDetailInfo.cashierWithSettlerImg" bizType="applyment" />
        <span class="jeepay-tip-text">(请提供结算人站在收银台内的照片<a href="javascript:void(0)" class="jeepay-tip-bos-img" @click="lookUp(3)"><b>《查看示例》</b></a>  )</span>
      </a-form-item>
    </a-form>

    <!-- 3. 结算账户  -->
    <a-form
        v-show="vdata.showStyle == showStyleEnum.block || vdata.currentStep == 3"
        ref="stepForm3Ref"
        :model="applymentDetailInfo"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 8 }"
        :rules="vdata.step3Rules"
    >
      <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">账户信息</a-divider>
      <a-form-item label="结算类型" name="defaultSettleType">
        <a-radio-group v-model:value="applymentDetailInfo.defaultSettleType" @change="() => emit('itemRender')">
          <a-radio value="alipayAccount">支付宝账号</a-radio>
          <a-radio value="bankCard" v-if="applymentDetailInfo.merchantType != 1">银行卡</a-radio>
        </a-radio-group>
      </a-form-item>



      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'alipayAccount'" label="结算支付宝账号" name="alipayLogonId">
        <a-input v-model:value.trim="applymentDetailInfo.alipayLogonId" />
      </a-form-item>

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="结算账户类型" name="settAccountType">
        <a-radio-group v-model:value="applymentDetailInfo.settlementAccountType" @change="getSettlementAccountType">
          <a-radio :value="1">法人对私</a-radio>
          <a-radio :value="3" v-if="applymentDetailInfo.merchantType != 1">对公</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard' && applymentDetailInfo.settlementAccountType ==1" label="结算卡数字面" name="settAccountLicenseImg">
        <JeepayUpload v-model:src="applymentDetailInfo.settAccountLicenseImg" bizType="applyment" :imgSize="2"
                      ocrType="bankCard" @ocrScan="ocrScanFunc"/>
        <span class="jeepay-tip-text">(上传图片自动识别 银行卡号)</span>
      </a-form-item>
      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard' && applymentDetailInfo.settlementAccountType ==3" label="开户许可证照片" name="settAccountLicenseImg">
        <JeepayUpload v-model:src="applymentDetailInfo.settAccountLicenseImg" bizType="applyment" :imgSize="2"/>
      </a-form-item>

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="结算卡开户名" name="settAccountName">
        <!--        <a-input v-model:value.trim="applymentDetailInfo.settAccountName" />-->
        <!--        <span class="jeepay-tip-text">如：张三</span>-->
        <a-input v-model:value.trim="applymentDetailInfo.settAccountName"  v-if="applymentDetailInfo.merchantType == 1" disabled />
        <a-input v-model:value.trim="applymentDetailInfo.settAccountName"  v-if="applymentDetailInfo.merchantType != 1 && applymentDetailInfo.settlementAccountType == 1 && applymentDetailInfo.settAccountType == 'C'" disabled />
        <a-input v-model:value.trim="applymentDetailInfo.settAccountName"  v-if="applymentDetailInfo.merchantType != 1 && applymentDetailInfo.settlementAccountType == 2 && applymentDetailInfo.settAccountType == 'C'"  />
        <a-input v-model:value.trim="applymentDetailInfo.settAccountName"  v-if="applymentDetailInfo.merchantType != 1 && applymentDetailInfo.settAccountType == 'B'"  disabled />
        <span class="jeepay-tip-text" v-if="applymentDetailInfo.merchantType == 1">（小微商户结算卡必须为法人本人结算卡）</span>
      </a-form-item>

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="结算银行卡账号" name="settAccountNo">
        <a-input v-model:value.trim="applymentDetailInfo.settAccountNo" />
      </a-form-item>

      <!--      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="银行名称" name="settAccountBankName">-->
      <!--        <a-input v-model:value.trim="applymentDetailInfo.settAccountBankName" />-->
      <!--        <span class="jeepay-tip-text">如：工商银行</span>-->
      <!--      </a-form-item>-->

      <!--      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="银行简称" name="accountInstId">-->
      <!--        <a-input v-model:value.trim="applymentDetailInfo.accountInstId" />-->
      <!--        <span class="jeepay-tip-text">如：ICBC</span>-->
      <!--      </a-form-item>-->

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="开户行省市县" name="settAccountBankBranchAreaCode">
        <JeepayAreaSelect v-model:value="applymentDetailInfo.settAccountBankBranchAreaCode" @change="changeBankAreaFunc" />
      </a-form-item>

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard'" label="开户支行名称" name="settAccountBankBranchName">
        <!--        <a-input v-model:value.trim="applymentDetailInfo.settAccountBankBranchName" placeholder="开户支行名称" />-->
        <a-select
            v-model:value="applymentDetailInfo.settAccountBankBranchName"
            placeholder="选择支行"
            show-search
            label-in-value
            :filter-option="false"
            @search="handleBankSearch"
            @change="handleBankChange"
            :getPopupContainer="(triggerNode) => triggerNode.parentElement"
        >
          <a-select-option v-for="(item, index) in vdata.filteredBankInfoList" :key="index" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
        <span class="jeepay-tip-text">(填写银行卡号并且选择开户行省市县后将展开支行列表)</span>
      </a-form-item>

      <a-form-item v-if="applymentDetailInfo.defaultSettleType == 'bankCard' && applymentDetailInfo.settlementAccountType == 1" label="授权函照" name="licenseAuthLetterImage">
        <JeepayUpload v-model:src="applymentDetailInfo.licenseAuthLetterImage" bizType="applyment" />
        <!--        <span class="jeepay-tip-text">开户名与法人不一致需上传授权函</span>-->
        <span class="jeepay-tip-text">
        <p>1.当结算人与法人不是同一人时必需上传非法人授权函图片 <a href="javascript:void(0)" class="jeepay-tip-bos-img" @click="lookUp(1)">《查看示例》</a>  <a href="javascript:void(0)" class="jeepay-tip-bos-img" @click="download">《下载支付宝直付通非法人授权函》</a></p>
        <p>2.若商户为个体商户，仅需法人和被授权人签字+按手印</p>
        <p>3.若商户为企业商户，法人需要签字+按手印+盖公章</p>
        <p>4.底部日期填写填写表单日期即可</p>
        </span>
      </a-form-item>

      <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">结算类型

      </a-divider>


      <a-form-item  label="结算类型" name="settlementType" >
        <div style="display: grid">
          <a-radio-group v-model:value="applymentDetailInfo.settlementType">
            <a-radio value="T1" v-if="vdata.settlementMethod.indexOf('T1') !== -1" :disabled='true'>T1-工作日次日到账</a-radio>
            <a-radio value="D1" v-if="vdata.settlementMethod.indexOf('D1') !== -1" >D1-次日到账</a-radio>
            <a-radio value="D0" v-if="vdata.settlementMethod.indexOf('D0') !== -1" :disabled='true'>D0-实时到账</a-radio>
          </a-radio-group>
          <!--          <div class="jeepay-tip-text jeepay-tip-span" v-if="applymentDetailInfo.settAccountCut == 'D0'">(注意：D0实时到账会有额外的秒到手续费，详见下一步费率信息)</div>-->
        </div>
      </a-form-item>
    </a-form>

    <!-- 4. 签约信息  -->
    <a-form
        v-show="vdata.showStyle == showStyleEnum.block || vdata.currentStep == 4"
        ref="stepForm4Ref"
        :model="applymentDetailInfo"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        :rules="vdata.step4Rules"
    >
      <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">签约资料</a-divider>
      <a-form-item label="签约支付宝账号" name="bindingAlipayLogonId">
        <a-input v-model:value.trim="applymentDetailInfo.bindingAlipayLogonId" />
        <span class="jeepay-tip-text" v-if="applymentDetailInfo.merchantType == 3">(如是商户类型为企业，必须跟营业执照对应的企业支付宝)</span>
      </a-form-item>

      <a-form-item label="选择服务" name="zftService">
        <a-checkbox-group v-model:value="applymentDetailInfo.zftService" name="checkboxgroup" :options="plainOptions" />
        <span class="jeepay-tip-text">(下面站点信息必填，按照真实填写)</span>

      </a-form-item>

      <a-form-item label="站点信息" name="siteInfos">
        <a-card class="jeepay-card-zft" style="width: 100%" title="">
          <template #extra>
            <a-button class="jeepay-m-btn" data-type="text" style="background: dodgerblue; color: white" @click="addReceiverRow()">添加站点</a-button>
          </template>
          <a-table :columns="accTableColumns" :data-source="vdata.receiverTableData.filter((item: any) => item.siteType)" :pagination="false" rowKey="rowKey">
            <template #bodyCell="{column, record}">
              <template v-if="column.key == 'siteType'">
                <a-select v-model:value="record.siteType" style="width: 150px" placeholder="站点类型" default-value="01">
                  <a-select-option value="01">网站</a-select-option>
                  <a-select-option value="02">APP</a-select-option>
                  <a-select-option value="03">服务窗</a-select-option>
                  <a-select-option value="04">公众号</a-select-option>
                  <a-select-option value="05">其他</a-select-option>
                  <a-select-option value="06">支付宝小程序</a-select-option>
                </a-select>
              </template>

              <template v-if="column.key == 'siteUrl'">
                <a-input v-model:value.trim="record.siteUrl" />
              </template>

              <template v-if="column.key == 'siteName'">
                <a-input v-model:value.trim="record.siteName" />
              </template>

              <template v-if="column.key == 'account'">
                <a-input v-model:value.trim="record.account" />
              </template>

              <template v-if="column.key == 'password'">
                <a-input v-model:value.trim="record.password" />
              </template>

              <template v-if="column.key == 'op'"><a-button type="link" @click="delRow(record)">删除</a-button></template>
            </template>
          </a-table>
        </a-card>
      </a-form-item>

      <!-- <div>
        <a-col :offset="1"><a-divider orientation="left" style="color: #1A66FF;">补充资料</a-divider></a-col>
        <a-form-item label="证件类型" name="additionalCertType">
          <a-radio-group v-model:value="applymentDetailInfo.additionalCertType" @change="() => emit('itemRender')">
            <a-radio value="201">营业执照号</a-radio>
            <a-radio value="204">民办非企业登记证书</a-radio>
            <a-radio value="206">社会团体法人登记证书</a-radio>
            <a-radio value="218">事业单位法人证书</a-radio>
            <a-radio value="219">党政机关批准设立文件/行政执法主体资格证</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="证件号" name="additionalCertNo">
          <a-input v-model:value.trim="applymentDetailInfo.additionalCertNo" />
        </a-form-item>

        <a-form-item label="证件图片" name="additionalCertImage">
          <JeepayUpload v-model:src="applymentDetailInfo.additionalCertImage" bizType="applyment" />
        </a-form-item>
      </div> -->
    </a-form>

    <!-- 4. 费率配置  -->
    <a-form
        v-show="vdata.showStyle == showStyleEnum.block || vdata.currentStep == 5"
        ref="stepForm4Ref"
        :model="applymentDetailInfo"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        :rules="vdata.step4Rules"
    >
      <div label="配置费率" name="fee" style="width:100%;">
        <!--        <JeepayPaywayRatePanel-->
        <!--            ref="jeepayPaywayRatePanelRef"-->
        <!--            :configMode="configMode"-->
        <!--            :infoId=" (mchApplymentData.applyId || '') + '_' + mchApplymentData.mchNo"-->
        <!--            :selectIfCode="mchApplymentData.ifCode"-->
        <!--            onlyRate="true"-->
        <!--            :channelStatus="'2'"-->
        <!--            :channelNo="mchApplymentData.isvNo"-->
        <!--            :channelAppId="mchApplymentData.autoConfigMchAppId"-->
        <!--        />-->

        <JeepayPaywayRateUserOfflinePanel
            v-if="mchApplymentData.range == 0"
            ref="jeepayPaywayRateUserOfflinePanelRef"
            :configMode="configMode"
            :infoId="
            (mchApplymentData.applyId || '') + '_' + mchApplymentData.mchNo
          "
            :selectIfCode="mchApplymentData.ifCode"
            onlyRate="true"
            :channelNo="mchApplymentData.isvNo"
            :channelRange="mchApplymentData.range"
            :channelAppId="mchApplymentData.autoConfigMchAppId"
            :settlementMethod="vdata.settlementMethod"
        />
        <JeepayPaywayRateUserOnlinePanel
            v-if="mchApplymentData.range == 1"
            ref="jeepayPaywayRateUserOnlinePanelRef"
            :configMode="configMode"
            :infoId="
            (mchApplymentData.applyId || '') + '_' + mchApplymentData.mchNo
          "
            :selectIfCode="mchApplymentData.ifCode"
            onlyRate="true"
            :channelNo="mchApplymentData.isvNo"
            :channelRange="mchApplymentData.range"
            :channelAppId="mchApplymentData.autoConfigMchAppId"
            :settlementMethod="vdata.settlementMethod"
        />
      </div>
    </a-form>

    <a-divider />

    <div class="jeepay-btn-box jeepay-m-btn-box" style="margin-top: 50px; margin-bottom: 50px;text-align: center;">
      <a-button v-show="vdata.showStyle == showStyleEnum.step && vdata.currentStep > 1" class="jeepay-m-btn" data-type="inline" type="primary" @click="toPrevStep"><left-circle-outlined /> 上一步 </a-button>
      <a-button v-show="vdata.showStyle == showStyleEnum.step && vdata.currentStep < 5" class="jeepay-m-btn" data-type="inline" type="primary" @click="toNextStep">下一步 <right-circle-outlined /> </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">

import {reactive, getCurrentInstance, defineEmits, inject, ref} from 'vue'
import ruleGenerator from '@/utils/ruleGenerator'
import { genRowKey } from '@/utils/util'
import {debounce} from "lodash-es";
import {$bankBranchList, $getSettType} from '@/api/manage'
import fileDownload from 'js-file-download'
import {SelectProps} from "ant-design-vue";

// 获取当前实例的代理对象
const { proxy } : any = getCurrentInstance()

const { $infoBox,$viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

const jeepayPaywayRateUserOfflinePanelRef = ref()
const jeepayPaywayRateUserOnlinePanelRef = ref()

// 显示类型枚举值
const showStyleEnum = {
  step: 'step',
  block: 'block'
}
const accTableColumns = [
  { key: 'siteType', title: '站点类型' },
  { key: 'siteUrl', title: '站点地址' },
  { key: 'siteName', title: '站点名称' },
  { key: 'account', title: '测试账号' },
  { key: 'password', title: '测试密码' },
  { key: 'op', title: '操作' }
]

const defaultReceiverTemplate ={
  siteType: '',
  siteUrl: '',
  siteName: '',
}

// 服务选项
const plainOptions = [
  // { label: '当面付', value: '当面付' },
  { label: 'APP支付', value: 'app支付' },
  { label: 'WAP支付', value: 'wap支付' },
  { label: '电脑支付', value: '电脑支付' },
  { label: '小程序支付', value: '小程序支付' },
]

// emit： 向父组件进行通讯。
const emit = defineEmits(['itemRender'])

// 参数注入： 是否手机端
let isMobile : any = inject('isMobile')

// 响应式数据
const vdata : any = reactive({
  filteredBankInfoList:[] as any,
  bankInfoList:[] as any,
  settlementMethod:[] as any,
  showStyle: 'step', // 显示类型： step-分步,  block-整页显示
  steps: ['主体信息', '经营信息', '结算信息', '签约信息'],
  isTempData: false, // 是否保存草稿
  isvDefaultPaywayFee: {} as any, // 服务商默认费率
  currentStep: 1,
  receiverTableData: [] as any,
  step1Rules: {
    merchantType: [ ruleGenerator.requiredSelect('商户类型', 'number') ],
    licenseImg: [ ruleGenerator.requiredUpload('营业执照照片') ],
    licenseNo: [ ruleGenerator.requiredInput('营业执照编号') ],
    mchFullName: [ ruleGenerator.requiredInput('用户名称') ],
    idcard1Img: [ ruleGenerator.requiredUpload('法人身份证人像面照片') ],
    idcardName: [ ruleGenerator.requiredInput('身份证中的姓名') ],
    idcardNo: [ ruleGenerator.requiredInput('身份证号') ],
    idcard2Img: [ ruleGenerator.requiredUpload('法人身份证国徽面照片') ],
    idcardEffectBegin: [ ruleGenerator.requiredInput('身份证起始有效期'), ruleGenerator.date ],
    idcardEffectEnd: [ ruleGenerator.requiredInput('身份证有效期截止日期'), ruleGenerator.dateOrForever ],
  },
  step2Rules: {
    mchFullName: [ ruleGenerator.requiredSelect('名称') ],
    mccCode: [ ruleGenerator.requiredSelect('行业') ],
    mchShortName: [ ruleGenerator.requiredInput('商户简称') ],
    contactName: [ ruleGenerator.requiredInput('联系人姓名') ],
    contactPhone: [ ruleGenerator.requiredInput('联系人电话') ],
    areaCode: [ ruleGenerator.requiredSelect('位置编码', 'array') ],
    address: [ ruleGenerator.requiredInput('经营地址') ],
    storeInnerImg: [ ruleGenerator.requiredUpload('门头照') ],
    storeOuterImg: [ ruleGenerator.requiredUpload('店内环境照') ],
    storeCashierImg: [ruleGenerator.requiredUpload('收银台照')],
    cashierWithSettlerImg: [ ruleGenerator.requiredInput('结算人与收银台合影') ],
  },
  step3Rules: {
    settAccountType: [ ruleGenerator.requiredSelect('账户类型') ],
    defaultSettleType: [ ruleGenerator.requiredSelect('结算类型') ],
    settAccountNo: [ ruleGenerator.requiredInput('银行帐号') ],
    settAccountName: [ ruleGenerator.requiredInput('开户名') ],
    settAccountBankName: [ ruleGenerator.requiredInput('银行名称') ],
    // accountInstId: [ ruleGenerator.requiredInput('银行简称') ],
    settAccountBankBranchAreaCode: [ ruleGenerator.requiredSelect('支行地区', 'array') ],
    settAccountBankBranchName: [ ruleGenerator.requiredInput('开户支行名称') ],
    alipayLogonId: [ ruleGenerator.requiredInput('结算支付宝账号') ],
    licenseAuthLetterImage: [ ruleGenerator.requiredInput('授权函照') ],
    settAccountLicenseImg: [ ruleGenerator.requiredInput('结算卡数字面') ],

  },
  step4Rules: {
    bindingAlipayLogonId: [ ruleGenerator.requiredSelect('签约支付宝账号') ],
    zftService: [ ruleGenerator.requiredSelect('服务', 'array') ],

  }

})

// 接收进件参数（包含 用户号， ifCode ）
let mchApplymentDataRef : any = inject('mchApplymentData')
let mchApplymentData : any = mchApplymentDataRef.value

// 接收父组件的进件详细参数
let applymentDetailInfoInject : any = inject('applymentDetailInfo')
let applymentDetailInfo : any = applymentDetailInfoInject.value

// 参数注入： 配置方式
let configMode : any = inject('configMode')

getSettType()
// 下一步
function toNextStep() {
  // 验证是否通过
  proxy.$refs['stepForm'+vdata.currentStep+'Ref'].validate().then( () => {
    vdata.currentStep ++
  })
}

// 上一步
function toPrevStep(){
  vdata.currentStep --
}

function validateAllForm(step: number){
  return proxy.$refs['stepForm'+step+'Ref'].validate().then( () => {
    if(step >= 4){
      return Promise.resolve()
    }
    return validateAllForm(++step)

  })
}

if(applymentDetailInfo.siteInfos) {
  vdata.receiverTableData = applymentDetailInfo.siteInfos
}

// 图片识别的回调函数
function ocrScanFunc(orcObject: any){
  if(orcObject){
    if(applymentDetailInfo.merchantType == 1){
      applymentDetailInfo.mchFullName  = orcObject.idcardName
    }
    Object.assign(applymentDetailInfo, orcObject)
  }
  getIdcardName()
}

// 点击【保存】的前置事件, 需要返回Promise对象
function saveDataPreCallback(isTemp){

  // 站点信息
  applymentDetailInfo.siteInfos = vdata.receiverTableData
  // 保存草稿只校验当前步骤数据
  if (isTemp) {
    return Promise.resolve()
  }
  if(mchApplymentData.range == 0 && jeepayPaywayRateUserOfflinePanelRef.value){
    // 放置费率配置项
    let paywayFeeList = jeepayPaywayRateUserOfflinePanelRef.value.getReqMchRatePaywayFeeList();
    if (typeof paywayFeeList != "object") {
      return Promise.reject();
    }
    // 赋值到对象中
    applymentDetailInfo.paywayFeeList = paywayFeeList;
  }

  if(mchApplymentData.range == 1 && jeepayPaywayRateUserOnlinePanelRef.value){
    // 放置费率配置项
    let paywayFeeList = jeepayPaywayRateUserOnlinePanelRef.value.getReqMchRatePaywayFeeList();
    if (typeof paywayFeeList != "object") {
      return Promise.reject();
    }
    // 赋值到对象中
    applymentDetailInfo.paywayFeeList = paywayFeeList;
  }

  // 验证所有表单
  return validateAllForm(1).then(() => {
    return Promise.resolve()
  }).catch((params: any) => {
    $infoBox.message.error('数据填写不完整， 请检查后提交')
    return Promise.reject()
  })
}


// 省市区选择回调
// function searchAreaFunc(value) {
//   applymentDetailInfo.accountInstProvince = value[0].label
//   applymentDetailInfo.accountInstCity = value[1].label
//
// }

// 开户行所在省市区
const changeBankAreaFunc:any = debounce((value) => {
  console.log(value,'changeBankAreaFuncchangeBankAreaFuncchangeBankAreaFunc')
  applymentDetailInfo.accountInstProvince = value[0].label
  applymentDetailInfo.accountInstCity = value[1].label
  // 区编码
  if (applymentDetailInfo?.settAccountBankBranchAreaCode?.[1]) {
    applymentDetailInfo.settAccountBankBranchAreaName = [];
    applymentDetailInfo.settAccountBankBranchAreaName = [value[0].label,value[1].label,value[2].label]
    applymentDetailInfo.openAccCity = applymentDetailInfo?.settAccountBankBranchAreaCode?.[1];
    applymentDetailInfo.openAccCityName = value[1].label;

    // 区编码
    if (applymentDetailInfo?.openAccCity) {
      vdata.bankInfoList = []
      vdata.filteredBankInfoList = []

      const param = {
        cityCode: applymentDetailInfo.openAccCityName,
        branchName: applymentDetailInfo.settAccountBankName,
      };
      console.log(mchApplymentData,'mchApplymentData')
      $bankBranchList(mchApplymentData.mchNo, mchApplymentData.ifCode, param,mchApplymentData.isvNo).then((res) => {
        if (res?.length) {
          res.forEach(element => {
            const item = {
              label: element.branchName,
              value: element.branchNo,
              bankName: element.bankName,
              bankCode: element.bankAbbr,
            };
            vdata.bankInfoList.push(item);
            vdata.filteredBankInfoList.push(item);
          })
        } else {
          $infoBox.message.error('该地区下未找到对应银行列表')
        }
      })
    } else {
      $infoBox.message.warn('请先选择地区')
    }
  }
}, 300)

// 添加一行账号信息
function addReceiverRow () {
  vdata.receiverTableData.push(Object.assign({}, defaultReceiverTemplate, { rowKey: genRowKey(), siteType: '01', siteUrl: '', siteName: '', account: '', password: '' }))
}
function changeMchAddressFunc(){
  const areaCodeName =  applymentDetailInfo.areaCodeName.replaceAll('/', '');
  applymentDetailInfo.address = areaCodeName+(applymentDetailInfo.mchAddress??"")
}
function changeMchAreaFunc(value) {
  if (applymentDetailInfo.address) {
    applymentDetailInfo.address = ''
  }
  vdata.city = value[1].label;
  applymentDetailInfo.areaName = [] as any;
  const areaCodeName = value[0].label + '' + value[1].label + '' + value[2]?.label + ''
  applymentDetailInfo.areaCodeName=areaCodeName
  applymentDetailInfo.mchAddressCodeName=areaCodeName

  applymentDetailInfo.areaName.push(value[0].label)
  applymentDetailInfo.areaName.push(value[1].label)
  applymentDetailInfo.areaName.push(value[2].label)


  applymentDetailInfo.address =( areaCodeName+applymentDetailInfo.mchAddress).replaceAll('undefined', '');

  applymentDetailInfo.areaCodeName = value[0].label + '/' + value[1].label + '/' + value[2]?.label + ''
}

function funLegalInfo(value) {
  if (value == '1') {
    // 联系人姓名
    applymentDetailInfo.contactName = applymentDetailInfo.idcardName
    // 联系人手机号
    applymentDetailInfo.contactPhone = applymentDetailInfo.legalPersonPhone
  } else {
    // 联系人姓名
    applymentDetailInfo.contactName = ''
    // 联系人手机号
    applymentDetailInfo.contactPhone = ''
  }
}
// 删除某一行
function delRow (item) {
  const index = vdata.receiverTableData.indexOf(item)
  if (index > -1) {
    vdata.receiverTableData.splice(index, 1)
  }
}

// 行业编码选择
function changeMccFunc (value) {
  if(value[1] && value[1].licenseCode) {
    applymentDetailInfo.industryQualificationType = value[1] && value[1].licenseCode
  }else{
    applymentDetailInfo.industryQualificationType = ''
  }
}
function lookUp(type){
  let  images = 'https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/zftletterOfAuthPic.png';
  if(type == 3){
    images = 'https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/cashier_photo.jpg';
  }else if(type == 4){
    images = 'https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/zftletterOfAuthPhoto.png';
  }
  $viewerApi({images: [images]})
}
function changeMerchantType() {
  getDiySettAccountName();
  if (applymentDetailInfo.merchantType == 1) {
    applymentDetailInfo.mchFullName = applymentDetailInfo.idcardName
    return
  }
}
function download(){
  let fileUrl = 'https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/zftletterOfAuthPhoto.png';
  if(isMobile){
    lookUp(4)
    return false;
  }
  // 创建一个虚拟的 a 标签
  const link = document.createElement('a');
  link.href = fileUrl;
  link.target = '_blank'; // 在新窗口或标签页中打开
  link.download = 'filename'; // 下载的文件名，你可以根据需要更改

  // 将 a 标签添加到 DOM 中
  document.body.appendChild(link);

  // 模拟点击 a 标签，触发下载
  link.click();

  // 移除添加的 a 标签
  document.body.removeChild(link);
}
function getDiySettAccountName() {

  applymentDetailInfo.settAccountName =   applymentDetailInfo.mchFullName;
}
function getIdcardName() {
  console.log(applymentDetailInfo.settlementAccountType,'applymentDetailInfosettlementAccountType')
  if(applymentDetailInfo.settlementAccountType == 3){
    applymentDetailInfo.settAccountName =   applymentDetailInfo.mchFullName
  }else{
    applymentDetailInfo.settAccountName =   applymentDetailInfo.idcardName;
  }
  applymentDetailInfo.standByStlAccNm =   applymentDetailInfo.idcardName;
}
function getSettlementAccountType() {
  if(applymentDetailInfo.settlementAccountType == 1){
    applymentDetailInfo.settAccountType = "C"
    applymentDetailInfo.authSettle = "N"
  }
  if(applymentDetailInfo.settlementAccountType == 2){
    applymentDetailInfo.settAccountType = "C"
    applymentDetailInfo.authSettle = "Y"
  }

  if(applymentDetailInfo.settlementAccountType == 3){
    applymentDetailInfo.settAccountType = "B"
  }
  getIdcardName()
  emit('itemRender')
}
function getSettType() {
  $getSettType( mchApplymentData.ifCode,mchApplymentData.isvNo).then((res) => {
    vdata.settlementMethod = res
  })
}
const handleBankChange: SelectProps['onChange'] = (option :any) => {
  applymentDetailInfo.settAccountBankBranchCode = option.value;
  vdata.filteredBankInfoList.forEach(item => {
    if (item.value == option.value) {
      applymentDetailInfo.settAccountBankBranchName = item.label
      applymentDetailInfo.settAccountBankBranchCode = item.value
    }
  });
};
const handleBankSearch = (option) => {
  console.log("handBankSearch", option);
  if(!isChinese(option)){
    return false;
  }
  addCity(option)
};
function isChinese(str) {
  var reg = /[\u4e00-\u9fa5]/; // Unicode范围内的汉字编码
  return reg.test(str);
}
function addCity(value) {
  vdata.bankInfoList = []
  vdata.filteredBankInfoList = []
  const param = {
    cityCode: applymentDetailInfo.openAccCityName,
    branchName: value,
  };
  console.log(param,'mchApplymentData')
  $bankBranchList(mchApplymentData.mchNo, mchApplymentData.ifCode, param,mchApplymentData.isvNo).then((res) => {
    if (res?.length) {
      res.forEach(element => {
        const item = {
          label: element.branchName,
          value: element.branchNo,
        };
        vdata.bankInfoList.push(item);
        vdata.filteredBankInfoList.push(item);
      })
    } else {
      $infoBox.message.error('该支行名称未搜索到或该地区没有对应的银行列表')
    }
  })
}
defineExpose({ saveDataPreCallback })

</script>

<style lang="less" scoped>
.jeepay-tip-text{
  font-size: 10px; color: rebeccapurple
}
.option-left {
  width: 50%;
  word-wrap: break-word;
  white-space: normal;
  word-break: break-all;
}
.option-right {
  color: rgb(153, 153, 153);
}
.option-bottom {
  word-wrap: break-word;
  white-space: normal;
  word-break: break-all;
  color: rgb(153, 153, 153);
}
.jeepay-btn-box {
  margin: 15px -12px !important;
}
.jeepay-btn-box .ant-btn {
  margin: 0 10px;
}
</style>