<template>
  <!-- 提现账号 -->
  <div class="shandeMchPage flex-col" :class="{ page1: pageType === '1', page2: pageType === '2', page3: pageType === '3', page4: pageType === '4' }" >
    <s-header :name="'提现账号'" :noback="false"></s-header>
    <div class="shandeMchBox flex-col">
      <div class="topSpeed" v-if="pageType !== '4'" :class="{ page1: pageType === '1', page2: pageType === '2', page3: pageType === '3' }" ></div>
      <div v-if="pageType === '1' || pageType === '4'">
        <van-form @submit="saveJoinPayMchFun">
          <van-field
            v-model="altMchName"
            name="altMchName"
            label="商户名称"
            readonly
          />
          <van-field
            v-model="altMchNo"
            name="altMchNo"
            label="商户账号"
            readonly
          />
          <van-field
            v-model="altMchShortName"
            name="altMchShortName"
            label="商户简称"
            readonly
          />
          <div class="van-cell van-field requiredLeft">
            <div class="van-cell__title van-field__label"><span>商户类型:</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="altMerchantType" direction="horizontal" @change="fieldUpdate">
                <van-radio name="10" icon-size="18px">个人</van-radio>
                <van-radio name="11" icon-size="18px">个体工商户</van-radio>
                <van-radio name="12" icon-size="18px">企业</van-radio>
              </van-radio-group>
            </div>
          </div>
          <div class="intervalRow"></div>
          <van-field
            class="requiredLeft"
            v-model="busiContactName"
            name="busiContactName"
            label="联系人姓名"
            :placeholder="'请输入联系人姓名'"
            :rules="[{ required: true, message: '请输入联系人姓名' }]"
            @update:model-value="fieldUpdate"
          />
          <van-field
            class="requiredLeft"
            v-model="busiContactMobileNo"
            name="busiContactMobileNo"
            label="联系人手机"
            :placeholder="'请输入联系人手机'"
            :rules="[{ required: true, message: '请输入联系人手机' }]"
            @update:model-value="fieldUpdate"
          />
          <van-field
            class="requiredLeft"
            v-model="legalPerson"
            name="legalPerson"
            label="法人/个人姓名"
            :placeholder="'请输入法人/个人姓名'"
            :rules="[{ required: true, message: '请输入法人/个人姓名' }]"
            @update:model-value="fieldUpdate"
          />
          <van-field
            class="requiredLeft"
            v-model="phoneNo"
            name="phoneNo"
            label="法人/个人手机号"
            :placeholder="'请输入法人/个人手机号'"
            :rules="[{ required: true, message: '请输入法人/个人手机号' }]"
            @update:model-value="fieldUpdate"
          />
          <van-field
            class="requiredLeft"
            v-model="idCardNo"
            name="idCardNo"
            label="身份证"
            :placeholder="'请输入身份证'"
            :rules="[{ required: true, message: '请输入身份证' }]"
            @update:model-value="fieldUpdate"
          />
          <van-cell title="身份证有效期" :value="idCardExpiry" @click="idCardExpiryShow = true" />
          <van-calendar v-model:show="idCardExpiryShow" @confirm="idCardExpiryOnConfirm" />
          <div class="van-cell van-field" v-if="pageType === '4'">
            <div class="van-cell__title van-field__label"><span>图片审核情况:</span></div>
            <div class="van-cell__value van-field__value radioBox" style="display: flex; justify-content: space-around; align-items: center;">
              {{approveStatus}}
              <van-button
                span="5"
                round
                type="primary"
                style="height: 2em; padding: 0 2em"
                @click='updateSentImage()'
                >重新上传</van-button
              >
            </div>
          </div>
          <div class="van-cell van-field" v-if="pageType === '4'">
            <div class="van-cell__title van-field__label"><span>签约状态:</span></div>
            <div class="van-cell__value van-field__value radioBox" style="display: flex; justify-content: space-around; align-items: center;">
              {{signStatus}}
              <van-button
                span="5"
                round
                type="primary"
                style="height: 2em; padding: 0 2em"
                @click='altMchSignFun()'
                >签约</van-button
              >
            </div>
          </div>
          <div class="intervalRow"></div>
          <div class="van-cell van-field requiredLeft">
            <div class="van-cell__title van-field__label"><span>账户类型:</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="bankAccountType" direction="horizontal" @change="fieldUpdate">
                <van-radio name="1" icon-size="18px">借记卡</van-radio>
                <van-radio name="4" icon-size="18px">对公账户</van-radio>
              </van-radio-group>
            </div>
          </div>
          <van-field
            class="requiredLeft"
            v-model="bankAccountName"
            name="bankAccountName"
            label="银行账户名称"
            :placeholder="'请输入银行账户名称'"
            :rules="[{ required: true, message: '请输入银行账户名称' }]"
            @update:model-value="fieldUpdate"
          />
          <van-field
            class="requiredLeft"
            v-model="bankAccountNo"
            name="bankAccountNo"
            label="银行账号"
            :placeholder="'请输入银行账号'"
            :rules="[{ required: true, message: '请输入银行账号' }]"
            @update:model-value="fieldUpdate"
          />
          <div :class="{requiredLeft: bankAccountType === '4'}">
            <van-field
              v-model="bankChannelNo"
              name="bankChannelNo"
              label="联行号"
              :placeholder="'请输入联行号'"
              :rules="[{ required: bankAccountType === '4', message: '请输入联行号' }]"
              @update:model-value="fieldUpdate"
            />
            <van-field
              v-model="licenseNo"
              name="licenseNo"
              label="营业执照编号"
              :placeholder="'请输入营业执照编号'"
              :rules="[{ required: bankAccountType === '4', message: '请输入营业执照编号' }]"
              @update:model-value="fieldUpdate"
            />
            <van-cell title="营业执照有效期" :value="licenseExpiry" @click="licenseExpiryShow = true" />
            <van-calendar v-model:show="licenseExpiryShow" @confirm="licenseExpiryOnConfirm" />
          </div>
          <div class="intervalRow"></div>
          <div class="van-cell van-field">
            <div class="van-cell__title van-field__label"><span>结算方式:</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="settMode" direction="horizontal" @change="fieldUpdate">
                <van-radio name="1" icon-size="18px">由汇聚自动结算</van-radio>
                <van-radio name="2" icon-size="18px">由商户平台手工结算</van-radio>
              </van-radio-group>
            </div>
          </div>
          <div class="van-cell van-field">
            <div class="van-cell__title van-field__label"><span>结算周期类型:</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group v-model="settDateType" direction="horizontal" @change="fieldUpdate">
                <van-radio name="1" icon-size="18px">工作日</van-radio>
                <van-radio name="2" icon-size="18px">自然日</van-radio>
                <van-radio name="3" icon-size="18px">月结日</van-radio>
              </van-radio-group>
            </div>
          </div>
          <van-field
            v-model="riskDay"
            name="riskDay"
            label="结算周期"
            :placeholder="'请输入结算周期'"
            @update:model-value="fieldUpdate"
          />
          <van-field
            v-model="manageScope"
            name="manageScope"
            label="经营范围"
            :placeholder="'请输入经营范围'"
            @update:model-value="fieldUpdate"
          />
          <van-field
            v-model="manageAddr"
            name="manageAddr"
            label="经营地址"
            :placeholder="'请输入经营地址'"
            @update:model-value="fieldUpdate"
          />
          <!-- 操作 -->
          <van-row justify="space-around" style="padding: 1em">
            <van-button
              span="5"
              round
              type="primary"
              style="height: 2em; padding: 0 2em"
              native-type="submit"
              >提交资料进行审核</van-button
            >
          </van-row>
        </van-form>
      </div>
      <div v-if="pageType === '2'" class="joinPayMch2" >
        <img src='../../assets/joinPayMch/center.png' style="width: 50%; margin-top: 3em;" />
        <div v-if="joinPayMchType === '0'" style="width: 100%;">
          <div style="width: 100%; text-align: center;">
            <span style=" font-size: 1.4em; font-weight: bold; line-height: 3;">平台管理员审核中</span>
          </div>
          <div style="width: 100%; text-align: center;">
            <span style="line-height: 1.2;">你可以<span style="color: #4d6add; text-decoration: underline;" @click='updateJoinPay()'>撤回重新修改</span></span>
          </div>
        </div>
        <div v-if="joinPayMchType === '2' || joinPayMchType === '3'" style="width: 100%;">
          <div style="width: 100%; text-align: center;">
            <span style=" font-size: 1.4em; font-weight: bold; line-height: 3; color: #ee0a24;">审核不通过</span>
          </div>
          <div style="width: 100%; text-align: center;">
            <span style="line-height: 1.2;">审核不通过,<span style="color: #4d6add; text-decoration: underline;" @click='pageType = "1"'>点击这里重新填写资料</span></span>
          </div>
        </div>
        <div v-if="joinPayMchStep === '0'">
          <div style="width: 100%; text-align: center;">
            <span style=" font-size: 1.4em; font-weight: bold; line-height: 3; color: #07c160;">审核已通过</span>
          </div>
          <div style="width: 100%; text-align: center;">
            <span style="line-height: 1.2;">审核通过,你可以<span style="color: #4d6add; text-decoration: underline;" @click='pageType = "1"'>点击这里重新填写并提交审核</span></span>
          </div>
          <van-row justify="space-around" style="padding: 1em">
            <van-button
              span="5"
              round
              type="primary"
              style="height: 2em; padding: 0 2em"
              @click='pageType = "3"'
              >下一步,去上传证件照片</van-button
            >
          </van-row>
        </div>
      </div>
      <div v-if="pageType === '3'">
        <van-form @submit="sentImageFun">
          <div class="upLoaderRow">
            <div class="baseRow flex-row justify-between">
              <div class="group2 flex-col"></div>
              <span class="baseText">请上传身份证</span>
            </div>
            <div class="cardRow">
              <div class="cardLi">
                <van-uploader v-model="cardNegativeList" :max-size="2 * 1024 * 1024" :max-count="1" :after-read="afterRead" @oversize="onOversize"/>
                <p>上传人像面</p>
              </div>
              <div class="cardLi">
                <van-uploader v-model="cardPositiveList" :max-size="2 * 1024 * 1024" :max-count="1" :after-read="afterRead" @oversize="onOversize"/>
                <p>上传国徽面</p>
              </div>
            </div>
          </div>
          <div class="upLoaderRow" v-if="bankAccountType === '4'" >
            <div class="baseRow flex-row justify-between">
              <div class="group2 flex-col"></div>
              <span class="baseText">请上传企业营业执照</span>
            </div>
            <div class="cardRow">
              <div class="cardLi">
                <van-uploader v-model="tradeLicenceList" :max-size="2 * 1024 * 1024" :max-count="1" :after-read="afterRead" @oversize="onOversize"/>
                <p>企业营业执照</p>
              </div>
            </div>
          </div>
          <div class="upLoaderRow" v-if="bankAccountType === '4'" >
            <div class="baseRow flex-row justify-between">
              <div class="group2 flex-col"></div>
              <span class="baseText">请上传开户许可证</span>
            </div>
            <div class="cardRow">
              <div class="cardLi">
                <van-uploader v-model="openAccountLicenceList" :max-size="2 * 1024 * 1024" :max-count="1" :after-read="afterRead" @oversize="onOversize"/>
                <p>开户许可证照片</p>
              </div>
            </div>
          </div>
          <van-row justify="space-around" style="padding: 1em">
            <van-button
              span="5"
              round
              type="primary"
              style="height: 2em; padding: 0 2em"
              native-type="submit"
              >提交资料</van-button
            >
          </van-row>
        </van-form>
      </div>
    </div>
    <nav-bar></nav-bar>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import navBar from "@/components/NavBar";
import sHeader from "@/components/SimpleHeader";
import { Toast } from "vant";
import { getOneJoinPayMch, saveJoinPayMch, updateJoinPayMchCheck, sentImage, altMchSign } from '@/service/joinpayMch';
import { getLoginUser } from "@/common/js/utils";
import dateUtil from "@/utils/dateUtil";

export default {
  components: { sHeader, navBar },
  setup() {
    const user = getLoginUser();
    const idCardExpiryShow = ref(false);
    const idCardExpiryOnConfirm = (value) => {
      idCardExpiryShow.value = false;
      addParams.idCardExpiry = dateUtil.formateDate(value, "yyyy-MM-dd");
      fieldUpdate();
    };
    const licenseExpiryShow = ref(false);
    const licenseExpiryOnConfirm = (value) => {
      licenseExpiryShow.value = false;
      addParams.licenseExpiry = dateUtil.formateDate(value, "yyyy-MM-dd");
      fieldUpdate();
    };
    let addParams = reactive({
      adminId: user.id, // 当前登录账户的id Long 必填
      altMchName: '', // 分账方名称; string 必填
      altMchNo: '', // 分账方账号; string	必填
      altMchShortName: '', // 分账方商户简称;	string	
      altMerchantType: '10', // 分账方商户类型，10:个人，11：个体工商户，12：企业;	integer(int32)	必填

      busiContactName: '', // 业务联系人姓名;	string	必填
      busiContactMobileNo: '', // 业务联系人手机;	string	必填
      legalPerson: '', // 法人;	string	必填
      phoneNo: '', // 电话;	string	必填
      idCardNo: '', // 身份证;	string	必填
      idCardExpiry: '', // 身份证有效期;	string

      bankAccountType: 1, // 账户类型 * 1 借记卡，4 对公账户;	integer(int32)	必填
      bankAccountName: '', // 银行账户名称，分账方结算银行账户名称;	string	必填
      bankAccountNo: '', // 银行账号;	string	必填
      bankChannelNo: '', // 联行号;	string	对公账户;必填
      licenseNo: '', // 营业执照编号;	string	对公账户;必填
      licenseExpiry: '', // 营业执照有效期;	string

      settMode: 1, // 结算方式 * 1 由汇聚自动结算 * 2 由商户平台手工结算（结算接口）;	integer(int32)	默认填1
      settDateType: 1, // 结算周期类型 * 1 工作日，2 自然日，3 月结日;	integer(int32)	默认填1
      riskDay: 1, // 结算周期;	integer(int32)	默认填1
      manageScope: '', // 经营范围;	string	
      manageAddr: '', // 经营地址;	string	

      bizCode: '', // 业务响应码;	string	
      loginName: '', // 分账方登录名，即邮箱;	string	
    });
    let cardPositiveList = ref([]);
    let cardNegativeList = ref([]);
    let tradeLicenceList = ref([]);
    let openAccountLicenceList = ref([]);
    let sentImageForm = reactive({
      cardPositive:	'', // 身份证正面	String	必填
      cardNegative:	'', // 	身份证背面	String	必填
      tradeLicence:	'', // 	营业执照图片	String	Type=0时必填
      openAccountLicence:	'', // 	开户许可证	String	Type=0时必填
      type:	'', // 	账户类型	String	必填 0：对公；1，个人
      status:	'0', // 	第几次提交	String	必填 0，第一次提交；1，第n次提交（重新上传）
    });
    const pageType = ref('1');
    const joinPayMchType = ref(null);
    const joinPayMchStep = ref(null);
    let joinPayMchID = null;
    const approveStatus = ref(null);
    const signStatus = ref(null);
    let isMemoryFormType = false;
    onMounted(async () => { getOneJoinPayMchFun(); });
    // 获取备用提现账号回显
    const getOneJoinPayMchFun = async () => {
      const { data } = await getOneJoinPayMch({ adminId: user.id });
      if (data.code === "00000") {
        if (data.data.type === '2' || data.data.type === '3' || data.data.type === '0') {
          joinPayMchType.value = data.data.type;
          pageType.value = '2';
        }
        if ((data.data.type === null || data.data.type === '1') && data.data.step === '0') {
          pageType.value = '2';
          joinPayMchStep.value = '0';
        }
        if ((data.data.type === null || data.data.type === '1') && data.data.step === '1') {
          pageType.value = '4';
        }
        console.log('pageType', pageType.value);

        joinPayMchID = data.data.id;
        approveStatus.value = data.data.approveStatus;
        signStatus.value = data.data.signStatus;
        addParams.altMchName = data.data.altMchName;
        addParams.altMchNo = data.data.altMchNo;
        addParams.altMchShortName = data.data.altMchShortName;
        addParams.altMerchantType = data.data.altMerchantType ? data.data.altMerchantType.toString() : '';

        addParams.busiContactName = data.data.busiContactName;
        addParams.busiContactMobileNo = data.data.busiContactMobileNo;
        addParams.legalPerson = data.data.legalPerson;
        addParams.phoneNo = data.data.phoneNo;
        addParams.idCardNo = data.data.idCardNo;
        if (data.data.idCardExpiry) {
          addParams.idCardExpiry = dateUtil.formateDate(new Date(data.data.idCardExpiry), "yyyy-MM-dd");
        }

        addParams.bankAccountType = data.data.bankAccountType ? data.data.bankAccountType.toString() : '';
        addParams.bankAccountName = data.data.bankAccountName;
        addParams.bankAccountNo = data.data.bankAccountNo;
        addParams.bankChannelNo = data.data.bankChannelNo;
        addParams.licenseNo = data.data.licenseNo;
        if (data.data.licenseExpiry) {
          addParams.licenseExpiry = dateUtil.formateDate(new Date(data.data.licenseExpiry), "yyyy-MM-dd");
        }

        addParams.settMode = data.data.settMode ? data.data.settMode.toString() : '';
        addParams.settDateType = data.data.settDateType ? data.data.settDateType.toString() : '';
        addParams.riskDay = data.data.riskDay;
        addParams.manageScope = data.data.manageScope;
        addParams.manageAddr = data.data.manageAddr;

        addParams.bizCode = data.data.bizCode;
        addParams.loginName = data.data.loginName;
      } else {
        pageType.value = '1';
        Toast.fail(data.message);
      }
      memoryForm();
      isMemoryFormType = true;
    };
    // 记忆表单
    const memoryForm = () => {
      const formDataString = localStorage.getItem('joinPayMchForm');
      if (formDataString) {
        const formData = JSON.parse(formDataString);
        Object.keys(formData).forEach(key => {
          addParams[key] = formData[key];
        });
      }
    };
    // 提交审批表单
    const saveJoinPayMchFun = async () => {
      const params = Object.assign({}, addParams);
      params.altMerchantType = parseInt(params.altMerchantType);
      params.bankAccountType = parseInt(params.bankAccountType);
      params.settMode = parseInt(params.settMode);
      params.settDateType = parseInt(params.settDateType);
      const { data } = await saveJoinPayMch(addParams);
      if (data.code === "00000") {
        Toast.success("提交成功");
        // 提交成功后删除记忆的表单
        localStorage.removeItem('joinPayMchForm');
        location.reload();
      } else {
        Toast.fail(`提交失败 ${data.message}`);
      }
    };
    // 撤回
    const updateJoinPay = async () => {
      const { data } = await updateJoinPayMchCheck({id: joinPayMchID});
      if (data.code === "00000") {
        Toast.success("撤回成功");
        location.reload();
      } else { Toast.fail(`${data.message}`); }
    }
    // 图片上传表单提交
    const sentImageFun = async () => {
      const params = {
        id: joinPayMchID,
        type: addParams.bankAccountType === '4' ? '0' : '1',
        status: sentImageForm.status,
        tradeLicence: null,
        openAccountLicence: null
      };
      if (cardNegativeList.value.length < 1) { Toast.fail(`请上传身份证人像面`); return; }
      if (cardPositiveList.value.length < 1) { Toast.fail(`请上传身份证国徽面`); return; }
      params.cardPositive = cardPositiveList.value[0].content;
      params.cardNegative = cardNegativeList.value[0].content;
      if (addParams.bankAccountType === '4') {
        if (tradeLicenceList.value.length < 1) { Toast.fail(`请上传企业营业执照`); return; }
        if (openAccountLicenceList.value.length < 1) { Toast.fail(`请上传开户许可证`); return; }
      }
      if (tradeLicenceList.value.length > 0) { params.tradeLicence = tradeLicenceList.value[0].content; }
      if (openAccountLicenceList.value.length > 0) { params.openAccountLicence = openAccountLicenceList.value[0].content; }
      const { data } = await sentImage(params);
      if (data.code === "00000") {
        Toast.success("上传成功");
        location.reload();
      } else { Toast.fail(`${data.message}`); }
    }
    // 图片重新上传触发
    const updateSentImage = () => {
      sentImageForm.status = '1';
      pageType.value = '3';
    }
    // 签约触发
    const altMchSignFun = async () => {
      const { data } = await altMchSign({id: joinPayMchID});
      if (data.code === "00000") {
        Toast.success("签约成功");
        location.reload();
      } else { Toast.fail(`${data.message}`); }
    }
    // 记录表单填写
    const fieldUpdate = () => {
      console.log('fieldUpdate');
      if (isMemoryFormType) {
        localStorage.setItem('joinPayMchForm', JSON.stringify(addParams));
      }
    };
    // 文件上传
    const afterRead = (file) => {
      console.log('afterRead', file);
      console.log('afterRead', file.content);
      console.log(cardPositiveList);
    }
    const onOversize = () => { Toast.fail('图片大小不能超过2M'); }
    return {
      pageType,
      joinPayMchType,
      joinPayMchStep,
      ...toRefs(addParams),
      ...toRefs(sentImageForm),
      cardPositiveList,
      cardNegativeList,
      tradeLicenceList,
      openAccountLicenceList,
      saveJoinPayMchFun,
      updateJoinPay,
      sentImageFun,
      approveStatus,
      signStatus,
      updateSentImage,
      altMchSignFun,
      idCardExpiryShow,
      idCardExpiryOnConfirm,
      licenseExpiryShow,
      licenseExpiryOnConfirm,
      fieldUpdate,
      afterRead,
      onOversize
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
@import "./index.less";
</style>
