<template>
  <!-- 备用提现账号 -->
  <div class="huifuPage flex-col">
    <s-header :name="$t('huifuMch.standbyWithdrawalAccountNo')" :noback="false"></s-header>
    <!-- 申请表单 -->
    <div class="huifuform flex-col">
      <van-form @submit="onSubmit">
        <div class="huifuBox">
          <div class="van-cell van-field">
            <div class="van-cell__title van-field__label"><span>{{ $t('huifuMch.merchantType') }}</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="type" direction="horizontal" disabled>
                <van-radio name="0" icon-size="18px">{{ $t('huifuMch.personal') }}</van-radio>
                <van-radio name="1" icon-size="18px">{{ $t('huifuMch.enterprise') }}</van-radio>
              </van-radio-group>
            </div>
          </div>
          <van-field v-model="regName" name="regName" :label="$t('huifuMch.huifuRegName')"
            :placeholder="$t('huifuMch.huifuRegNamePlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuRegNamePlaceholder') }]" />
          <van-field v-model="shortName" name="shortName" :label="$t('huifuMch.shortNameLabel')"
            :placeholder="$t('huifuMch.shortNamePlaceholder')" />
          <div v-if="type == 1">
            <van-field v-model="registeredAddress" is-link readonly name="registeredAddress"
              :label="$t('huifuMch.huifuRegisteredAddress')"
              :placeholder="$t('huifuMch.huifuRegisteredAddressPlaceholder')"
              :rules="[{ required: true, message: $t('huifuMch.huifuRegisteredAddressPlaceholder') }]"
              @click="showReAddress = true" />
            <van-field v-model="regDetail" name="regDetail" :label="$t('huifuMch.huifuRegDetail')"
              :placeholder="$t('huifuMch.huifuRegDetailPlaceholder')"
              :rules="[{ required: true, message: $t('huifuMch.huifuRegDetailPlaceholder') }]" />
          </div>
        </div>
        <div class="huifuBox" v-if="type == 1">
          <van-field v-model="companyFoundDate" readonly name="companyFoundDate" :label="$t('huifuMch.companyFoundDate')"
            :placeholder="$t('huifuMch.companyFoundDatePlaceholder')" @click="showFoundDate = true"
            :rules="[{ required: true, message: $t('huifuMch.companyFoundDatePlaceholder') }]" />
          <van-field v-model="licenseCode" name="licenseCode" :label="$t('huifuMch.licenseCode')"
            :placeholder="$t('huifuMch.licenseCodePlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.licenseCodePlaceholder') }]" />
          <div class="van-cell van-field">
            <div class="van-cell__title van-field__label"><span>{{ $t('huifuMch.validityType') }}</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="licenseValidityType" direction="horizontal">
                <van-radio name="1" icon-size="18px">{{ $t('huifuMch.permanent') }}</van-radio>
                <van-radio name="0" icon-size="18px">{{ $t('huifuMch.noPermanent') }}</van-radio>
              </van-radio-group>
            </div>
          </div>
          <van-field v-model="beginDateLicense" readonly name="beginDateLicense" :label="$t('huifuMch.beginDate')"
            :placeholder="$t('huifuMch.beginDatePlaceholder')" @click="showBeginDateLicense = true"
            :rules="[{ required: true, message: $t('huifuMch.beginDatePlaceholder') }]" />
          <van-field v-if="licenseValidityType == 0" v-model="endDateLicense" readonly name="endDateLicense"
            :label="$t('huifuMch.endDate')" :placeholder="$t('huifuMch.endDatePlaceholder')"
            @click="showEndDateLicense = true"
            :rules="[{ required: true, message: $t('huifuMch.endDatePlaceholder') }]" />
        </div>
        <div class="huifuBox">
          <van-field v-model="name" name="name" :label="$t('huifuMch.huifuContactName')"
            :placeholder="$t('huifuMch.huifuContactNamePlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuContactNamePlaceholder') }]" />
          <van-field v-model="phone" name="phone" :label="$t('huifuMch.huifuContactMobile')"
            :placeholder="$t('huifuMch.huifuContactMobilePlaceholder')"
            :rules="[{ required: true, pattern: /^1[3456789]\d{9}$/, message: $t('huifuMch.huifuContactMobileMessage') }]" />
          <van-field v-model="email" name="email" :label="$t('huifuMch.huifuContactEmail')"
            :placeholder="$t('huifuMch.huifuContactEmailPlaceholder')"
            :rules="[{ required: true, pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: $t('huifuMch.huifuContactEmailMessage') }]" />
          <van-field v-model="businessAddress" is-link readonly name="businessAddress"
            :label="$t('huifuMch.huifuBusinessAddress')" :placeholder="$t('huifuMch.huifuBusinessAddressPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuBusinessAddressPlaceholder') }]"
            @click="showArea = true" />
          <van-field v-model="detailAddr" name="detailAddr" :label="$t('huifuMch.huifuOperatingAddress')"
            :placeholder="$t('huifuMch.huifuOperatingAddressPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuOperatingAddressPlaceholder') }]" />
          <van-field v-if="type == 1" v-model="servicePhone" name="servicePhone" :label="$t('huifuMch.huifuServicePhone')"
            :placeholder="$t('huifuMch.huifuServicePhonePlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuServicePhonePlaceholder') }]" />
        </div>
        <div class="huifuBox">
          <div class="van-cell van-field" v-if="type == 1">
            <div class="van-cell__title van-field__label"><span>{{ $t('huifuMch.cardType') }}</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="cardType" direction="horizontal">
                <van-radio name="1" icon-size="18px">{{ $t('huifuMch.personalAccount') }}</van-radio>
                <van-radio name="0" icon-size="18px">{{ $t('huifuMch.corporateAccount') }}</van-radio>
              </van-radio-group>
            </div>
          </div>
          <van-field v-model="cardName" name="cardName" :label="$t('huifuMch.huifuCardName')"
            :placeholder="$t('huifuMch.huifuCardNamePlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuCardNamePlaceholder') }]" />
          <van-field v-model="cardNo" name="cardNo" :label="$t('huifuMch.huifuCardNo')"
            :placeholder="$t('huifuMch.huifuCardNoPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuCardNoPlaceholder') }]" />
          <van-field v-if="cardType == '1'" v-model="mp" name="mp" :label="$t('huifuMch.huifuMp')"
            :placeholder="$t('huifuMch.huifuMpPlaceholder')"
            :rules="[{ required: true, pattern: /^1[3456789]\d{9}$/, message: $t('huifuMch.huifuContactMobileMessage') }]" />
          <van-field v-if="cardType == 0" v-model="branchCode" name="branchCode" :label="$t('huifuMch.branchCode')"
            :placeholder="$t('huifuMch.branchCodePlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.branchCodePlaceholder') }]" />
          <van-field v-if="cardType == 0" v-model="openLicenceNo" name="openLicenceNo"
            :label="$t('huifuMch.openLicenceNo')" :placeholder="$t('huifuMch.openLicenceNoPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.openLicenceNoPlaceholder') }]" />
          <van-field v-if="cardType == '1'" v-model="bankAddress" is-link readonly name="bankAddress"
            :label="$t('huifuMch.huifuBankAddress')" :placeholder="$t('huifuMch.huifuBankAddressPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.huifuBankAddressPlaceholder') }]"
            @click="showBankAddress = true" />
          <van-field v-model="certNo" name="certNo" :label="$t('huifuMch.huifuCertNo')"
            :placeholder="$t('huifuMch.huifuCertNoPlaceholder')"
            :rules="[{ required: true, pattern: /^\d{17}[\dXx]$/, message: $t('huifuMch.huifuCertNoMessage') }]" />
          <van-field v-if="cardType == '0'" v-model="certAddress" name="certAddress" :label="$t('huifuMch.certAddress')"
            :placeholder="$t('huifuMch.certAddressPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.certAddressPlaceholder') }]" />
          <div class="van-cell van-field">
            <div class="van-cell__title van-field__label"><span>{{ $t('huifuMch.certType') }}</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="certValidityType" direction="horizontal">
                <van-radio name="1" icon-size="18px">{{ $t('huifuMch.permanent') }}</van-radio>
                <van-radio name="0" icon-size="18px">{{ $t('huifuMch.noPermanent') }}</van-radio>
              </van-radio-group>
            </div>
          </div>
          <van-field v-model="beginDate" readonly name="beginDate" :label="$t('huifuMch.beginDate')"
            :placeholder="$t('huifuMch.beginDatePlaceholder')" @click="showBeginDate = true"
            :rules="[{ required: true, message: $t('huifuMch.beginDatePlaceholder') }]" />
          <van-field v-if="certValidityType == 0" v-model="endDate" readonly name="endDate"
            :label="$t('huifuMch.endDate')" :placeholder="$t('huifuMch.endDatePlaceholder')" @click="showEndDate = true"
            :rules="[{ required: true, message: $t('huifuMch.endDatePlaceholder') }]" />
          <van-field v-model="sms" center clearable :label="$t('huifuMch.sms')"
            :placeholder="$t('huifuMch.smsPlaceholder')"
            :rules="[{ required: true, message: $t('huifuMch.smsPlaceholder') }]">
            <template #button>
              <van-button size="small" type="primary" @click="sendCode()" :disabled="time !== 0">
                {{ time === 0 ? $t('huifuMch.sendSms') : time + $t('huifuMch.replaysInSeconds') }}
              </van-button>
            </template>
          </van-field>
        </div>
        <!-- 地址弹窗 -->
        <van-popup v-model:show="showArea" position="bottom">
          <van-area :area-list="areaList" @confirm="onConfirm" @cancel="showArea = false" />
        </van-popup>
        <van-popup v-model:show="showBankAddress" position="bottom">
          <van-area :area-list="areaList" :columns-num="2" @confirm="onConfirmBankAddress"
            @cancel="showBankAddress = false" />
        </van-popup>
        <van-popup v-model:show="showReAddress" position="bottom">
          <van-area :area-list="areaList" @confirm="onConfirmReAddress" @cancel="showReAddress = false" />
        </van-popup>
        <!-- 时间弹窗 -->
        <van-popup v-model:show="showEndDateLicense" position="bottom">
          <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate" @confirm="onConfirmEndDateLicense"
            @cancel="showEndDateLicense = false" />
        </van-popup>
        <van-popup v-model:show="showBeginDateLicense" position="bottom">
          <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate" @confirm="onConfirmBeginDateLicense"
            @cancel="showBeginDateLicense = false" />
        </van-popup>
        <van-popup v-model:show="showFoundDate" position="bottom">
          <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate" @confirm="onConfirmFoundDate"
            @cancel="showFoundDate = false" />
        </van-popup>
        <van-popup v-model:show="showBeginDate" position="bottom">
          <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate" @confirm="onConfirmBeginDate"
            @cancel="showBeginDate = false" />
        </van-popup>
        <van-popup v-model:show="showEndDate" position="bottom">
          <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate" @confirm="onConfirmEndDate"
            @cancel="showEndDate = false" />
        </van-popup>
        <van-row justify="space-around" style="padding: 3em; background-color: #f6f7f9;">
          <van-button span="10" round type="primary" style=" padding: 0 5em" native-type="submit">{{
            $t('huifuMch.submit') }}
          </van-button>
        </van-row>
      </van-form>
    </div>
  </div>
</template>
  
<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import dateUtil from "@/utils/dateUtil";
import { Toast } from "vant";
import { areaList } from "@vant/area-data";
import { getHuifuMchCheck, updateMerchant, sendSms } from "@/service/huifuMch";
import { getLoginUser, getLocal, setLocal } from "@/common/js/utils";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader },
  setup() {
    // 引入语言
    const { t } = useI18n();
    const router = useRouter();
    const user = getLoginUser();
    const huifuMchCheck = ref(null); // 审核信息
    const businessAddress = ref(''); //经营地址
    const registeredAddress = ref(''); //注册地址
    const bankAddress = ref(''); // 银行地址
    const showArea = ref(false); // 是否弹窗
    const showBankAddress = ref(false);
    const showReAddress = ref(false);
    const companyFoundDate = ref(''); // 成立日期
    const showFoundDate = ref(false);
    const beginDateLicense = ref(''); // 营业执照有效开始日期
    const showBeginDateLicense = ref(false);
    const endDateLicense = ref(''); // 营业执照有效截止日期
    const showEndDateLicense = ref(false);
    const beginDate = ref(''); // 有效期开始日期
    const showBeginDate = ref(false);
    const endDate = ref(''); // 有效期截日期
    const showEndDate = ref(false);
    const showStatus = ref(null);
    const verCodeTime = reactive({
      time: 0
    });
    let addParams = reactive({
      adminId: user.id, // 当前登录账户的id
      type: '0', // 类型 String 必填 对公企业:type=0; 个人:type=1
      regName: '', // 商户名称
      shortName: '', // 商户简称
      foundDate: '', // 成立时间
      licenseCode: '', // 营业执照编号
      licenseValidityType: "1", // 营业执照有效期类型
      licenseBeginDate: '', // 营业执照有效开始日期
      licenseEndDate: '', // 营业执照有效截止日期
      regProvId: '', // 注册省编码
      regAreaId: '', // 注册市编码
      regDistrictId: '', // 注册区编码
      regDetail: '', // 注册详细地址
      name: '', // 联系人姓名
      phone: '', // 联系人手机号码
      email: '', // 联系人邮箱
      provId: '', // 省编码
      areaId: '',  // 省编码
      districtId: '', // 市编码 
      detailAddr: '', // 经营地址
      servicePhone: '', // 客服电话
      cardName: '', // 卡户名
      cardType: '1', // 结算账户类型，“0”为对公账户，“1”为个人账户
      cardNo: '', // 银行卡号
      branchCode: '', // 联行号
      openLicenceNo: '', // 基本存款账户编号或核准号
      cardProvId: '', // 省编码
      cardAreaId: '', // 省编码
      mp: '', // 结算手机号
      certNo: '', // 身份证号
      certAddress: '', // 身份证地址
      certValidityType: '1', // 身份证有效期类型
      certBeginDate: '', // 有效期开始日期
      certEndDate: '', // 有效期截止日期
      sms: '', // 验证码
    });
    // 地址选择
    const onConfirm = (areaValues) => {
      console.log(areaValues)
      showArea.value = false;
      businessAddress.value = areaValues
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/');
      addParams.provId = areaValues[0]?.code || '';
      addParams.areaId = areaValues[1]?.code || '';
      addParams.districtId = areaValues[2]?.code || '';
      // addParams.detailAddr = areaValues[0].name + areaValues[1].name + areaValues[2].name;
    };
    const onConfirmBankAddress = (areaValues) => {
      console.log(areaValues)
      showBankAddress.value = false;
      bankAddress.value = areaValues
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/');
      addParams.cardProvId = areaValues[0]?.code || '';
      addParams.cardAreaId = areaValues[1]?.code || '';
    };
    const onConfirmReAddress = (areaValues) => {
      showReAddress.value = false;
      registeredAddress.value = areaValues
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/');
      addParams.regProvId = areaValues[0]?.code || '';
      addParams.regAreaId = areaValues[1]?.code || '';
      addParams.regDistrictId = areaValues[2]?.code || '';
    };
    // 时间选择
    const onConfirmEndDateLicense = (value) => {
      endDateLicense.value = dateUtil.formateDate(value, "yyyy-MM-dd");
      addParams.licenseEndDate = endDateLicense.value.replace(/-/g, "");
      showEndDateLicense.value = false;
    };
    const onConfirmBeginDateLicense = (value) => {
      beginDateLicense.value = dateUtil.formateDate(value, "yyyy-MM-dd");
      addParams.licenseBeginDate = beginDateLicense.value.replace(/-/g, "");
      showBeginDateLicense.value = false;
    };
    const onConfirmFoundDate = (value) => {
      companyFoundDate.value = dateUtil.formateDate(value, "yyyy-MM-dd");
      addParams.foundDate = companyFoundDate.value.replace(/-/g, "");
      showFoundDate.value = false;
    };
    const onConfirmBeginDate = (value) => {
      beginDate.value = dateUtil.formateDate(value, "yyyy-MM-dd");
      addParams.certBeginDate = beginDate.value.replace(/-/g, "");
      showBeginDate.value = false;
    };
    const onConfirmEndDate = (value) => {
      endDate.value = dateUtil.formateDate(value, "yyyy-MM-dd");
      addParams.certEndDate = endDate.value.replace(/-/g, "");
      showEndDate.value = false;
    };
    // 将日期格式转换为'YYYY-MM-DD'格式
    const formatDate = (value) => {
      const year = value.slice(0, 4);
      const month = value.slice(4, 6);
      const day = value.slice(6, 8);
      return `${year}-${month}-${day}`;
    };
    // 发送验证码
    const sendCode = async () => {
      const { data } = await sendSms({
        adminId: user.id,
      });
      console.log('seedVerCodeSuccess', data);
      if (data.code === '00000') {
        Toast({
          duration: 2000,
          message: t('huifuMch.successSend')+'\n' + maskPhoneNumber(data.data.phone)
        });
        console.log('seedVerCodeSuccess');
        verCodeTime.time = 60;
        verCodeTimeInterval();
      } else {
        Toast.fail(data.message);
      }
    }
    // 格式手机号码
    const maskPhoneNumber = (value) => {
      const prefix = value.slice(0, 3);
      const suffix = value.slice(-4);
      return `${prefix}****${suffix}`;
    }
    // 验证码发送成功开始3分钟倒计时
    const verCodeTimeInterval = () => {
      verCodeTime.time--;
      setLocal('registerVerCodeTime', verCodeTime.time)
      if (verCodeTime.time !== 0) {
        setTimeout(() => {
          verCodeTimeInterval();
        }, 1000);
      }
    }
    //
    onMounted(async () => {
      const { data } = await getHuifuMchCheck({ adminId: user.id });
      console.log(data.data);
      if (data.data != null) {
        huifuMchCheck.value = data.data;
        addParams.type = data.data.type;
        addParams.regName = data.data.regName;
        addParams.shortName = data.data.shortName;
        if (data.data.type === "1") {
          addParams.regDetail = data.data.detailAddr;
          addParams.licenseCode = data.data.licenseCode;
          addParams.servicePhone = data.data.servicePhone;
          addParams.regProvId = data.data.provId;
          addParams.regAreaId = data.data.areaId;
          addParams.regDistrictId = data.data.districtId;
          addParams.foundDate = data.data.foundDate;
          addParams.licenseValidityType = data.data.licenseValidityType;
          addParams.licenseBeginDate = data.data.licenseBeginDate;
          addParams.licenseEndDate = data.data.licenseEndDate;
          companyFoundDate.value = formatDate(data.data.foundDate);
          beginDateLicense.value = formatDate(data.data.licenseBeginDate);
          endDateLicense.value = formatDate(data.data.licenseEndDate);
          registeredAddress.value = areaList.province_list[data.data.provId] + '/' + areaList.city_list[data.data.areaId] + '/' + areaList.county_list[data.data.districtId];
        }
        addParams.name = data.data.name;
        addParams.phone = data.data.phone;
        addParams.email = data.data.email;
        addParams.cardName = data.data.cardName;
        addParams.cardNo = data.data.cardNo;
        addParams.provId = data.data.provId;
        addParams.areaId = data.data.areaId;
        addParams.districtId = data.data.districtId;
        addParams.detailAddr = data.data.detailAddr;
        addParams.cardType = data.data.cardType;
        if(data.data.cardType === "0") {
          addParams.branchCode = data.data.branchCode;
          addParams.openLicenceNo = data.data.openLicenceNo;
          addParams.certAddress = data.data.certAddress;
        }
        addParams.cardProvId = data.data.cardProvId;
        addParams.cardAreaId = data.data.cardAreaId;
        addParams.mp = data.data.mp;
        addParams.certNo = data.data.certNo;
        addParams.certValidityType = data.data.certValidityType;
        addParams.certBeginDate = data.data.certBeginDate;
        addParams.certEndDate = data.data.certEndDate;
        beginDate.value = formatDate(data.data.certBeginDate);
        endDate.value = formatDate(data.data.certEndDate);
        businessAddress.value = areaList.province_list[data.data.provId] + '/' + areaList.city_list[data.data.areaId] + '/' + areaList.county_list[data.data.districtId];
        bankAddress.value = areaList.province_list[data.data.cardProvId] + '/' + areaList.city_list[data.data.cardAreaId]
        verCodeTime.time = getLocal('registerVerCodeTime');
        if (verCodeTime.time && verCodeTime.time !== '') {
          verCodeTime.time = parseInt(verCodeTime.time);
          if (verCodeTime.time > 0) {
            verCodeTimeInterval();
          }
        } else {
          verCodeTime.time = 0;
        }
      } else {
        Toast.fail(data.message);
      }
    });
    // 提交修改审核
    const submitUpdateCheck = async () => {
      const { data } = await updateMerchant(addParams);
      if (data.code == "00000") {
        console.log(data);
        Toast.success(t('huifuMch.submittedSuccessfully'));
        setTimeout(() => {
          router.go(-1);
        }, 1000);
      } else {
        Toast.fail(`${t('huifuMch.submitFailed')} ${data.message}`);
      }
    }
    const onSubmit = async () => {
      console.log('onSubmit', addParams);
      submitUpdateCheck();
    };
    return {
      ...toRefs(addParams),
      ...toRefs( verCodeTime),
      verCodeTime,
      sendCode,
      onSubmit,
      showStatus,
      businessAddress,
      bankAddress,
      registeredAddress,
      huifuMchCheck,
      areaList,

      beginDateLicense,
      endDateLicense,
      companyFoundDate,
      beginDate,
      endDate,

      showArea,
      showBankAddress,
      showReAddress,
      showBeginDateLicense,
      showEndDateLicense,
      showFoundDate,
      showBeginDate,
      showEndDate,

      onConfirm,
      onConfirmBankAddress,
      onConfirmReAddress,
      onConfirmBeginDateLicense,
      onConfirmEndDateLicense,
      onConfirmFoundDate,
      onConfirmBeginDate,
      onConfirmEndDate,

      minDate: new Date(2000, 0, 1),
      maxDate: new Date(2035, 11, 31),
      submitUpdateCheck,
      formatDate,
      maskPhoneNumber,
    };
  },
};
</script>
  
<style lang="less" scoped>
@import "../../common/style/common.less";
@import "./index.less";
</style>
  