<template>
  <div class="bind-page">
    <s-header title="绑定银行卡" :noback="false" :isBorder="false"></s-header>
    <div class="main-content">
      <!-- 步骤条 -->
      <div class="step-container">
        <van-steps :active="currentStep" active-color="#4d6add">
          <van-step>证件信息</van-step>
          <van-step>结算信息</van-step>
          <van-step>信息审核</van-step>
          <van-step>签约</van-step>
        </van-steps>
      </div>

      <!-- 证件信息 -->
      <div v-if="currentStep === 0" class="card-section">
        <van-tabs v-model:active="merchantType" title-active-color="#4d6add">
          <!-- 个人商户 -->
          <van-tab
            title="个人商户"
            :disabled="joinPayMchNo != null && merchantType === 1"
          >
            <div class="upload-card">
              <h3 class="upload-title">
                <span class="title-decoration"></span>
                收款人证件(大陆)
              </h3>
              <div class="upload-group">
                <van-uploader
                  v-model="idCardFront"
                  :max-count="1"
                  class="custom-uploader"
                  name="idCardFront"
                  :after-read="afterRead"
                >
                  <template #default>
                    <div class="upload-item">
                      <van-icon name="photo" size="32" color="#4d6add" />
                      <p>上传人像面</p>
                    </div>
                  </template>
                </van-uploader>
                <van-uploader
                  v-model="idCardBack"
                  :max-count="1"
                  class="custom-uploader"
                  name="idCardBack"
                  :after-read="afterRead"
                >
                  <template #default>
                    <div class="upload-item">
                      <van-icon name="photo" size="32" color="#4d6add" />
                      <p>上传国徽面</p>
                    </div>
                  </template>
                </van-uploader>
              </div>
            </div>
          </van-tab>

          <!-- 企业商户 -->
          <van-tab
            title="企业商户"
            :disabled="joinPayMchNo != null && merchantType === 0"
          >
            <div class="upload-card">
              <h3 class="upload-title">
                <span class="title-decoration"></span>
                法人证件信息(大陆)
              </h3>
              <div class="upload-group">
                <van-uploader
                  v-model="idCardFront"
                  :max-count="1"
                  class="custom-uploader"
                  name="idCardFront"
                  :after-read="afterRead"
                >
                  <template #default>
                    <div class="upload-item">
                      <van-icon name="photo" size="32" color="#4d6add" />
                      <p>上传人像面</p>
                    </div>
                  </template>
                </van-uploader>
                <van-uploader
                  v-model="idCardBack"
                  :max-count="1"
                  class="custom-uploader"
                  name="idCardBack"
                  :after-read="afterRead"
                >
                  <template #default>
                    <div class="upload-item">
                      <van-icon name="photo" size="32" color="#4d6add" />
                      <p>上传国徽面</p>
                    </div>
                  </template>
                </van-uploader>
              </div>

              <h3 class="upload-title" style="margin-top: 20px">
                <span class="title-decoration"></span>
                营业执照
              </h3>
              <van-uploader
                v-model="businessLicense"
                :max-count="1"
                class="custom-uploader"
                name="businessLicense"
                :after-read="afterRead"
              >
                <template #default>
                  <div class="upload-item single">
                    <van-icon name="description" size="32" color="#4d6add" />
                    <p>上传营业执照</p>
                  </div>
                </template>
              </van-uploader>
            </div>
          </van-tab>
        </van-tabs>
      </div>

      <!-- 结算信息 -->
      <div v-if="currentStep === 1" class="card-section">
        <van-tabs v-model:active="merchantType" title-active-color="#4d6add">
          <!-- 个人商户 -->
          <van-tab title="个人商户" :disabled="merchantType === 1">
            <div class="upload-card">
              <h3 class="upload-title">
                <span class="title-decoration"></span>
                银行卡正面
              </h3>
              <van-uploader
                v-model="bankCard"
                :max-count="1"
                class="custom-uploader"
                name="bankCard"
                :after-read="afterRead"
              >
                <template #default>
                  <div class="upload-item single">
                    <van-icon name="card" size="32" color="#4d6add" />
                    <p>上传银行卡正面</p>
                  </div>
                </template>
              </van-uploader>
            </div>
          </van-tab>

          <!-- 企业商户 -->
          <van-tab title="企业商户" :disabled="merchantType === 0">
            <div class="upload-card">
              <h3 class="upload-title">
                <span class="title-decoration"></span>
                开户许可证
              </h3>
              <van-uploader
                v-model="accountLicense"
                :max-count="1"
                class="custom-uploader"
                name="accountLicense"
                :after-read="afterRead"
              >
                <template #default>
                  <div class="upload-item single">
                    <van-icon name="description" size="32" color="#4d6add" />
                    <p>上传开户许可证</p>
                  </div>
                </template>
              </van-uploader>
            </div>
          </van-tab>
        </van-tabs>
      </div>

      <!-- 信息审核步骤 -->
      <div v-if="currentStep === 2" class="review-section">
        <van-collapse v-model="activeCollapse">
          <!-- 基础信息 -->
          <van-collapse-item title="主体信息" name="1">
            <van-cell
              title="商户类型"
              :value="merchantType === 0 ? '个人商户' : '企业商户'"
            />
            <template v-if="merchantType === 0">
              <van-cell title="姓名" :value="formData.name" />
              <van-cell title="身份证号" :value="formData.idNumber" />
              <van-cell title="有效期" :value="formData.validDate" />
              <van-cell title="手机号" :value="formData.phone" />
              <van-cell title="联系人" :value="formData.contactName" />
              <van-cell title="手机号" :value="formData.contactPhone" />
            </template>
            <template v-else>
              <van-cell title="企业名称" :value="formData.companyName" />
              <van-cell title="营业执照号" :value="formData.licenseNo" />
              <van-cell title="注册日期" :value="formData.companyDate" />
              <van-cell title="法人姓名" :value="formData.name" />
              <van-cell title="法人身份证" :value="formData.idNumber" />
              <van-cell title="法人手机号" :value="formData.phone" />
              <van-cell title="有效期" :value="formData.validDate" />
              <van-cell title="联系人" :value="formData.contactName" />
              <van-cell title="联系人手机号" :value="formData.contactPhone" />
            </template>
          </van-collapse-item>

          <!-- 银行信息 -->
          <van-collapse-item title="结算信息" name="2">
            <van-cell
              title="账户类型"
              :value="merchantType === 0 ? '个人账户' : '企业账户'"
            />
            <van-cell
              :title="merchantType === 0 ? '银行卡号' : '对公账号'"
              :value="formData.bankCardNo"
            />
            <van-cell
              v-if="merchantType === 1"
              title="联行号"
              :value="formData.bankChannelNo"
            />
            <van-cell
              title="结算方式"
              :value="formData.settMode === '1' ? '自动结算' : '手动提现'"
            />
            <van-cell title="到账时效" value="D1" />
          </van-collapse-item>
        </van-collapse>
      </div>

      <!-- 签约确认步骤 -->
      <div v-if="currentStep === 3" class="sign-section">
        <div class="upload-card">
          <h3 class="upload-title">
            <span class="title-decoration"></span>
            信息认证状态
          </h3>

          <!-- 信息认证状态 -->
          <div class="audit-status-bar" :class="infoStatusClass">
            <div class="status-content">
              <van-icon :name="infoStatusIcon" class="status-icon" />
              <div class="status-text">
                <p class="main-text">{{ infoStatusMainText }}</p>
                <p class="sub-text">{{ infoStatusSubText }}</p>
              </div>
            </div>
            <van-button
              v-if="infoStatus == 2"
              size="small"
              type="primary"
              plain
              @click="handleInfoReupload"
            >
              修改信息
            </van-button>
          </div>

          <h3 class="upload-title">
            <span class="title-decoration"></span>
            证件审核状态
          </h3>

          <!-- 审核状态栏 -->
          <div class="audit-status-bar" :class="statusClass">
            <div class="status-content">
              <van-icon :name="statusIcon" class="status-icon" />
              <div class="status-text">
                <p class="main-text">{{ statusMainText }}</p>
                <p class="sub-text">{{ statusSubText }}</p>
              </div>
            </div>
            <van-button
              v-if="auditStatus == 2"
              size="small"
              type="primary"
              plain
              @click="handleInfoReupload"
            >
              上传
            </van-button>
          </div>
          <!-- 签约说明 -->
          <div class="sign-notice" v-if="signStatus != 1">
            <van-icon name="warning" color="#FF9500" />
            <span>请确认所有状态通过后，点击下方按钮完成签约</span>
          </div>

          <h3 class="upload-title">
            <span class="title-decoration"></span>
            签约状态
          </h3>

          <!-- 签约状态栏 -->
          <div class="audit-status-bar" :class="signStatusClass">
            <div class="status-content">
              <van-icon :name="signStatusIcon" class="status-icon" />
              <div class="status-text">
                <p class="main-text">{{ signStatusMainText }}</p>
                <p class="sub-text">{{ signStatusSubText }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 其他步骤内容 -->

    <!-- 操作按钮 -->
    <div class="action-section">
      <!-- 条件显示提示语 -->
      <div v-if="currentStep === 0 && merchantType === 1" class="action-notice">
        <van-icon name="warning" class="notice-icon" />
        <span>请确认上传法人证件信息与营业执照主体一致</span>
      </div>
      <div class="action-buttons">
        <van-button
          v-if="currentStep > 0 && currentStep < 3 && auditStatus != 1"
          round
          class="prev-btn"
          @click="currentStep--"
        >
          上一步
        </van-button>
        <van-button
          v-if="currentStep == 2 && auditStatus == 1"
          round
          class="prev-btn"
          @click="currentStep--"
        >
          上一步
        </van-button>
        <van-button
          v-if="currentStep < 3"
          round
          type="primary"
          class="next-btn"
          @click="handleNextStep"
        >
          下一步
        </van-button>
        <van-button
          v-if="currentStep == 3 && signStatus != 1"
          round
          type="primary"
          class="next-btn"
          @click="handleNextStep"
        >
          立即签约
        </van-button>
        <van-button
          v-if="
            currentStep == 3 &&
            auditStatus == 1 &&
            infoStatus == 1 &&
            signStatus == 1
          "
          round
          type="primary"
          class="next-btn"
          @click="updateBankCard"
        >
          修改银行卡
        </van-button>
      </div>
    </div>
    <!-- 信息确认 ActionSheet -->
    <van-action-sheet
      v-model:show="showConfirmSheet"
      title="信息确认"
      :round="false"
      class="custom-actionsheet"
    >
      <!-- 证件信息 -->
      <div class="sheet-content" v-if="currentStep === 0">
        <van-form @submit="confirmInfo(0)">
          <!-- 个人商户表单 -->
          <template v-if="merchantType === 0">
            <!-- 收款人证件信息-->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 16px; color: #333"
                    >收款人证件信息</span
                  >
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.name"
              label="姓名"
              placeholder="请输入姓名"
              required
              :rules="[{ required: true, message: '请输入姓名' }]"
            />
            <van-field
              v-model="formData.idNumber"
              label="身份证号"
              placeholder="请输入身份证号"
              :formatter="formatIdCard"
              required
              :rules="[{ required: true, message: '请输入身份证号' }]"
            />
            <van-field
              v-model="formData.validDate"
              label="有效期限"
              placeholder="请选择有效期"
              readonly
              clickable
              required
              @click="showDatePicker = true"
              :rules="[{ required: true, message: '请选择有效期' }]"
            />
            <van-field
              v-model="formData.phone"
              label="收款人手机号"
              placeholder="收款人手机号"
              :formatter="formatPhone"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入11位手机号',
                  validator: (val) =>
                    /^1[3-9]\d{9}$/.test(val.replace(/\s/g, '')),
                },
              ]"
            />
            <!-- 联系人信息  -->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 16px; color: #333">联系人信息</span>
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.contactName"
              label="联系人姓名"
              placeholder="请输入联系人姓名"
              :disabled="joinPayMchNo != null"
              :rules="[{ required: true, message: '请输入联系人姓名' }]"
              required
            />
            <van-field
              v-model="formData.contactPhone"
              label="联系人手机号"
              placeholder="请输入联系人手机号"
              :formatter="formatPhone"
              :disabled="joinPayMchNo != null"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入11位手机号',
                  validator: (val) =>
                    /^1[3-9]\d{9}$/.test(val.replace(/\s/g, '')),
                },
              ]"
            />
          </template>

          <!-- 企业商户表单 -->
          <template v-else>
            <!-- 法人信息  -->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 0.45rem; color: #333"
                    >法人证件信息</span
                  >
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.name"
              label="法人姓名"
              placeholder="请输入法人姓名"
              required
              :rules="[{ required: true, message: '请输入法人姓名' }]"
            />
            <van-field
              v-model="formData.idNumber"
              label="法人身份证"
              placeholder="请输入法人身份证"
              :rules="[{ required: true, message: '请输入法人身份证' }]"
              :formatter="formatIdCard"
              required
            />
            <van-field
              v-model="formData.validDate"
              label="有效期限"
              placeholder="请选择有效期"
              :rules="[{ required: true, message: '请选择有效期' }]"
              readonly
              clickable
              required
              @click="showDatePicker = true"
            />
            <van-field
              v-model="formData.phone"
              label="法人手机号"
              placeholder="请输入法人手机号"
              :formatter="formatPhone"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入11位手机号',
                  validator: (val) =>
                    /^1[3-9]\d{9}$/.test(val.replace(/\s/g, '')),
                },
              ]"
            />
            <!-- 联系人信息  -->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 0.45rem; color: #333"
                    >联系人信息</span
                  >
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.contactName"
              label="联系人姓名"
              placeholder="请输入联系人姓名"
              :rules="[{ required: true, message: '请输入联系人姓名' }]"
              required
            />
            <van-field
              v-model="formData.contactPhone"
              label="联系人手机号"
              placeholder="请输入联系人手机号"
              :formatter="formatPhone"
              required
              :rules="[
                {
                  required: true,
                  message: '请输入11位手机号',
                  validator: (val) =>
                    /^1[3-9]\d{9}$/.test(val.replace(/\s/g, '')),
                },
              ]"
            />
            <!-- 营业执照信息  -->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 0.45rem; color: #333"
                    >营业执照信息</span
                  >
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.licenseNo"
              label="执照编号"
              placeholder="请输入营业执照编号"
              :rules="[{ required: true, message: '请输入营业执照编号' }]"
              required
            />
            <van-field
              v-model="formData.companyName"
              label="企业名称"
              placeholder="请输入企业全称"
              :rules="[{ required: true, message: '请输入企业全称' }]"
              required
            />
            <van-field
              v-model="formData.companyDate"
              label="注册日期"
              placeholder="请选择注册日期"
              :rules="[{ required: true, message: '请选择注册日期' }]"
              readonly
              clickable
              required
              @click="showCompanyDatePicker = true"
            />
          </template>

          <div class="confirm-buttons">
            <van-button
              round
              block
              type="primary"
              class="confirm-btn"
              native-type="submit"
            >
              确认信息
            </van-button>
          </div>
        </van-form>
      </div>
      <!-- 银行卡信息 -->
      <div class="sheet-content" v-if="currentStep === 1">
        <van-form @submit="confirmInfo(1)">
          <!-- 个人商户表单 -->
          <template v-if="merchantType === 0">
            <!-- 银行卡信息-->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 0.45rem; color: #333"
                    >银行卡信息</span
                  >
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.bankCardNo"
              label="银行账号"
              placeholder="请输入银行账号"
              required
              :rules="[{ required: true, message: '请输入银行账号' }]"
            />
            <van-field label="结算方式" required>
              <template #input>
                <div class="settlement-container">
                  <van-radio-group
                    v-model="formData.settMode"
                    direction="horizontal"
                  >
                    <van-radio name="1" checked-color="#4d6add" icon-size="18px"
                      >自动结算</van-radio
                    >
                    <van-radio name="2" checked-color="#4d6add" icon-size="18px"
                      >手动提现</van-radio
                    >
                  </van-radio-group>
                  <!-- 新增提示语 -->
                  <div class="settlement-tip">
                    <van-icon name="info" color="#999" size="14px" />
                    <span>24小时内到账</span>
                  </div>
                </div>
              </template>
            </van-field>
          </template>

          <!-- 企业商户表单 -->
          <template v-else>
            <!-- 法人信息  -->
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <span class="blue-line"></span>
                  <span style="font-size: 0.45rem; color: #333"
                    >开户许可证信息</span
                  >
                </div>
              </template>
            </van-cell>
            <van-field
              v-model="formData.bankCardNo"
              label="对公账号"
              placeholder="请输入对公账号"
              required
              :rules="[{ required: true, message: '请输入对公账号' }]"
            />
            <van-field
              v-model="formData.bankChannelNo"
              label="联行号"
              placeholder="请输入联行号"
              required
              :rules="[{ required: true, message: '请输入联行号' }]"
            />
            <van-field label="结算方式" required>
              <template #input>
                <div class="settlement-container">
                  <van-radio-group
                    v-model="formData.settMode"
                    direction="horizontal"
                  >
                    <van-radio name="1" checked-color="#4d6add" icon-size="18px"
                      >自动结算</van-radio
                    >
                    <van-radio name="2" checked-color="#4d6add" icon-size="18px"
                      >手动提现</van-radio
                    >
                  </van-radio-group>
                  <!-- 新增提示语 -->
                  <div class="settlement-tip">
                    <van-icon name="info" color="#999" size="14px" />
                    <span>自动结算和手工提现均为次日到账</span>
                  </div>
                </div>
              </template>
            </van-field>
          </template>

          <div class="confirm-buttons">
            <van-button
              round
              block
              type="primary"
              class="confirm-btn"
              native-type="submit"
            >
              确认信息
            </van-button>
          </div>
        </van-form>
      </div>
    </van-action-sheet>
    <!-- 组合选择器弹窗 -->
    <van-popup
      v-model:show="showDatePicker"
      round
      position="bottom"
      class="custom-date-picker"
    >
      <van-date-picker
        v-model="validDate"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="idDateConfirm"
      />
    </van-popup>
    <!-- 公司注册日期选择器弹窗 -->
    <van-popup
      v-model:show="showCompanyDatePicker"
      round
      position="bottom"
      class="custom-date-picker"
    >
      <van-date-picker
        v-model="companyDate"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="companyDateConfirm"
        @cancel="showCompanyDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  showConfirmDialog,
  showToast,
  showFailToast,
  showSuccessToast,
} from "vant";
import { getLoginUser } from "../../common/js/utils";
import sHeader from "../../components/SimpleHeader";
import {
  idCardRecognition,
  createMch,
  getJoinPayMch,
  uploadPhotos,
  updateApproveStatus,
  updateMchApproveStatus,
  updateMchSignStatus,
  altMchSign,
  getPhotos,
} from "../../service/purse/index.js";
import { ref, computed, onMounted } from "vue";
import dateUtil from "../../utils/dateUtil";
import router from "../../router";

export default {
  components: { sHeader },
  setup() {
    const user = getLoginUser();
    const currentStep = ref(0);
    const merchantType = ref(0);
    //
    const activeCollapse = ref(["1", "2"]);
    // 图片信息
    const idCardFront = ref([]);
    const idCardBack = ref([]);
    const businessLicense = ref([]);
    const bankCard = ref([]);
    const accountLicense = ref([]);
    // 企业法人确认
    const legalPersonName = ref('');
    // 确认信息弹窗
    const showConfirmSheet = ref(false);
    // 日期选择
    const showDatePicker = ref(false);
    const showCompanyDatePicker = ref(false);
    const minDate = ref(new Date(2000, 0, 1));
    const maxDate = ref(new Date(2099, 11, 31));
    const companyDate = ref(["2022", "06", "01"]);
    // 身份证有效期限
    const validDate = ref(["2022", "06", "01"]);
    // 信息认证状态（0: 未认证 1: 已认证 2: 认证失败）
    const infoStatus = ref(0);
    // 信息认证计算属性
    const infoStatusClass = computed(() => ({
      "audit-status-bar--warning": infoStatus.value === 0,
      "audit-status-bar--success": infoStatus.value === 1,
      "audit-status-bar--error": infoStatus.value === 2,
    }));

    const infoStatusIcon = computed(
      () =>
        ({
          0: "clock",
          1: "passed",
          2: "warning",
        }[infoStatus.value])
    );

    const infoStatusMainText = computed(
      () =>
        ({
          0: "信息认证中",
          1: "认证成功",
          2: "认证失败",
        }[infoStatus.value])
    );

    const infoStatusSubText = ref("");

    // 证照审核状态（0: 审核中 1: 通过 2: 未通过）
    const auditStatus = ref(0);
    // 计算属性
    const statusClass = computed(() => {
      return {
        "audit-status-bar--success": auditStatus.value === 1,
        "audit-status-bar--warning": auditStatus.value === 0,
        "audit-status-bar--error": auditStatus.value === 2,
      };
    });
    const statusIcon = computed(() => {
      return {
        0: "clock",
        1: "passed",
        2: "warning",
      }[auditStatus.value];
    });

    const statusMainText = computed(() => {
      return {
        0: "资料审核中",
        1: "所有资料已通过审核",
        2: "审核未通过",
      }[auditStatus.value];
    });

    const statusSubText = ref("");

    // 签约状态（0: 未签约 1: 已签约 2: 签约失败）
    const signStatus = ref(0);

    const signStatusIcon = computed(() => {
      return {
        0: "clock",
        1: "passed",
        2: "warning",
      }[signStatus.value];
    });

    const signStatusClass = computed(() => {
      return {
        "audit-status-bar--success": signStatus.value === 1,
        "audit-status-bar--warning": signStatus.value === 0,
        "audit-status-bar--error": signStatus.value === 2,
      };
    });

    const signStatusMainText = computed(() => {
      return {
        0: "未签约",
        1: "签约成功",
        2: "签约失败",
      }[signStatus.value];
    });

    const signStatusSubText = computed(() => {
      return {
        0: "请完成签约流程",
        1: "签约成功，可前往绑定机器",
        2: "请重新上传符合要求的证件",
      }[signStatus.value];
    });

    // 证照上传状态
    const uploadStatus = ref(0);
    // 汇聚ID
    const joinPayMchID = ref(null);
    // 汇聚商户编号
    const joinPayMchNo = ref(null);

    // 信息
    const formData = ref({
      // 收款人/法人信息
      merchantType: 10, // 商户类型,“0”为个人，“1”为企业
      name: "", // 身份证名称
      idNumber: "", // 身份证
      validDate: "", // 身份证有效期限
      phone: "", // 手机号
      // 联系人信息
      contactName: "", // 联系人姓名
      contactPhone: "", // 联系人手机号
      // 营业执照信息
      licenseNo: "", // 营业执照编号
      companyName: "", // 企业名称
      companyDate: "", // 企业注册日期
      // 银行卡信息
      bankName: "", // 银行名称
      bankCardNo: "", // 银行卡号
      bankCardType: "0", // 银行卡类型,“0”为对公卡，“1”为对私卡
      settMode: "1", // 结算方式,“1”为自动结算，“2”为手动提现
      // 开户许可证信息
      bankChannelNo: "", // 联行号
    });
    // 提交参数
    const submitParam = ref({
      adminId: user.id, // 用户ID
      altMchName: "", // 收账方名称
      altMchNo: "", // 收账方账号
      altMerchantType: 10, // 收账方商户类型，10:个人，11：个体工商户，12：企业
      // 收款人/法人信息
      legalPerson: "", // 法人名称
      idCardNo: "", // 身份证
      idCardExpiry: "", // 身份证有效期
      phoneNo: "", // 法人手机号
      // 联系人信息
      busiContactName: "", // 业务联系人姓名
      busiContactMobileNo: "", // 业务联系人手机
      // 银行卡信息
      bankAccountType: 1, // 银行卡类型, 4:对公，1:对私
      bankAccountName: "", // 银行账户名称
      bankAccountNo: "", // 银行账号
      bankChannelNo: "", // 联行号
      settMode: 1, // 结算方式,“1”为自动结算，“2”为手动提现
      settDateType: 1, // 结算周期类型 * 1 工作日，2 自然日，3 月结日;	integer(int32)	默认填1
      riskDay: 1, // 结算周期;	integer(int32)	默认填1
      // 营业执照信息
      licenseNo: "", // 营业执照编号
      licenseExpiry: "", // 营业执照有效期
      bindingSteps: 0, // 绑定步骤
    });

    // 上传证照
    const afterRead = async (file, type) => {
      try {
        const fileData = new FormData();
        fileData.append("file", file.file);
        fileData.append("adminId", user.id);
        fileData.append("imageType", type.name);
        const { data } = await idCardRecognition(fileData);
        if (data.code === "00000") {
          console.log(data.data);
          switch (type.name) {
            // 身份证人像面
            case "idCardFront":
              console.log(idCardFront.value);
              formData.value.name = data.data.name;
              formData.value.idNumber = data.data.idCard;
              break;
            // 身份证国徽面
            case "idCardBack":
              if (data.data.idCardEndDate) {
                validDate.value = data.data.idCardEndDate.split(".");
                formData.value.validDate = validDate.value.join("-");
              } else {
                // 长期身份证
                validDate.value = data.data.idCardStartDate.split(".");
                formData.value.validDate = validDate.value.join("-");
              }
              break;
            // 营业执照
            case "businessLicense":
              formData.value.licenseNo = data.data.businessLicenseNo;
              formData.value.companyName = data.data.businessLicenseName;
              formData.value.companyDate = dateUtil.formatDate(
                data.data.businessLicenseValidDate
              );
              companyDate.value = formData.value.companyDate.split("-");
              legalPersonName.value = data.data.legalPerson;
              break;
            // 银行卡正面
            case "bankCard":
              formData.value.bankCardNo = data.data.bankCardNo;
              break;
            // 开户许可证
            case "accountLicense":
              formData.value.bankCardNo = data.data.accountNo;
              break;
          }
        }
      } catch (error) {
        console.log(error);
      }
    };

    // 确认日期选择
    const idDateConfirm = () => {
      formData.value.validDate = validDate.value.join("-");
      showDatePicker.value = false;
    };

    const companyDateConfirm = () => {
      formData.value.companyDate = companyDate.value.join("-");
      showCompanyDatePicker.value = false;
    };

    // 确认信息
    const confirmInfo = (value) => {
      console.log(formData.value);
      showConfirmDialog({
        message: "确认信息无误？",
      })
        .then(async () => {
          if (value === 0) {
            // 证件信息
            if (merchantType.value === 0) {
              // 个人
              submitParam.value.altMchName = formData.value.name;
              submitParam.value.altMerchantType = 10;
              submitParam.value.legalPerson = formData.value.name;
              submitParam.value.idCardNo = formData.value.idNumber.replace(
                /\s/g,
                ""
              );
              submitParam.value.idCardExpiry = formData.value.validDate;
              submitParam.value.phoneNo = formData.value.phone.replace(
                /\s/g,
                ""
              );
              submitParam.value.busiContactName = formData.value.contactName;
              submitParam.value.busiContactMobileNo =
                formData.value.contactPhone.replace(/\s/g, "");
            } else {
              // 企业
              submitParam.value.altMerchantType = 12;
              if (legalPersonName.value != formData.value.name) {
                showToast("法人姓名与营业执照主体不一致！");
                return;
              }
              submitParam.value.legalPerson = formData.value.name;
              submitParam.value.idCardNo = formData.value.idNumber.replace(
                /\s/g,
                ""
              );
              submitParam.value.idCardExpiry = formData.value.validDate;
              submitParam.value.phoneNo = formData.value.phone.replace(
                /\s/g,
                ""
              );
              submitParam.value.busiContactName = formData.value.contactName;
              submitParam.value.busiContactMobileNo =
                formData.value.contactPhone.replace(/\s/g, "");
              submitParam.value.altMchName = formData.value.companyName;
              submitParam.value.licenseNo = formData.value.licenseNo;
              submitParam.value.licenseExpiry = formData.value.companyDate;
            }
            submitParam.value.bindingSteps = 0;
          }
          if (value === 1) {
            // 结算信息
            if (merchantType.value === 0) {
              // 个人
              submitParam.value.bankAccountType = 1;
              submitParam.value.bankAccountName = formData.value.name;
              submitParam.value.bankAccountNo = formData.value.bankCardNo;
            } else {
              // 企业
              submitParam.value.bankAccountType = 4;
              submitParam.value.bankAccountName = formData.value.companyName;
              submitParam.value.bankAccountNo = formData.value.bankCardNo;
              submitParam.value.bankChannelNo = formData.value.bankChannelNo;
            }
            submitParam.value.settMode = formData.value.settMode == "1" ? 1 : 2;
            submitParam.value.bindingSteps = 1;
          }
          try {
            const { data } = await createMch(submitParam.value);
            if (data.code === "00000") {
              currentStep.value++;
            } else {
              showToast(data.message);
            }
          } catch (error) {
            console.log(error);
          }
          console.log("提交参数", submitParam.value);
          showConfirmSheet.value = false;
        })
        .catch(() => {
          return;
        });
    };

    // 回显数据
    const getMchInfo = async () => {
      try {
        const { data } = await getJoinPayMch({ adminId: user.id });
        if (data.code === "00000") {
          joinPayMchID.value = data.data.id;
          if (data.data.altMchNo != null && data.data.altMchNo != "") {
            joinPayMchNo.value = data.data.altMchNo;
          }
          formData.value.merchantType = data.data.altMerchantType;
          if (formData.value.merchantType === 12) {
            merchantType.value = 1;
          }
          formData.value.name = data.data.legalPerson;
          formData.value.idNumber = data.data.idCardNo;
          formData.value.validDate = data.data.idCardExpiry;
          formData.value.phone = data.data.phoneNo;

          formData.value.contactName = data.data.busiContactName;
          formData.value.contactPhone = data.data.busiContactMobileNo;

          formData.value.licenseNo = data.data.licenseNo;
          formData.value.companyName = data.data.bankAccountName;
          formData.value.companyDate = data.data.licenseExpiry;

          formData.value.bankName = data.data.bankAccountName;
          formData.value.bankCardNo = data.data.bankAccountNo;
          formData.value.bankChannelNo = data.data.bankChannelNo;
          formData.value.settMode = data.data.settMode == 1 ? "1" : "2";

          // 步骤
          currentStep.value = data.data.bindingSteps;
          // 认证状态
          switch (data.data.status) {
            case "0":
              // 认证中
              infoStatus.value = 0;
              infoStatusSubText.value = "预计3分钟内完成认证";
              break;
            case "1":
              // 认证成功
              infoStatus.value = 1;
              infoStatusSubText.value = "认证信息已验证通过";
              break;
            case "2":
              // 认证失败
              infoStatus.value = 2;
              infoStatusSubText.value = data.data.bizMsg;
              break;
          }
          // 图片上传状态
          switch (data.data.step) {
            case "0":
              // 未上传
              uploadStatus.value = 0;
              break;
            case "1":
              // 已上传
              uploadStatus.value = 1;
              break;
          }
          // 图片审核状态
          switch (data.data.approveStatus) {
            case "审核中":
              auditStatus.value = 0;
              statusSubText.value = "预计3分钟内完成审核";
              changeApproveStatus();
              break;
            case "审核通过":
              auditStatus.value = 1;
              statusSubText.value = "审核通过";
              break;
            case "审核不通过":
              auditStatus.value = 2;
              statusSubText.value = data.data.approveNote;
              changeApproveStatus();
              break;
          }
          // 签约状态
          switch (data.data.signStatus) {
            case "签约成功":
              // 未签约
              signStatus.value = 1;
              break;
            default:
              // 已签约
              break;
          }
          console.log("回显数据", formData.value);
        }
      } catch (error) {
        console.log(error);
      }
    };

    // 获取图片
    const getUserLicense = async () => {
      try {
        const { data } = await getPhotos({
          adminId: user.id,
        });
        if (data.code === "00000") {
          console.log("图片", data.data);
          if (data.data.idCardFront) {
            idCardFront.value = [
              {
                url: "data:image/jpeg;base64," + data.data.idCardFront,
                isImage: true,
              },
            ];
          }
          if (data.data.idCardBack) {
            idCardBack.value = [
              {
                url: "data:image/jpeg;base64," + data.data.idCardBack,
                isImage: true,
              },
            ];
          }
          if (data.data.bankCard) {
            bankCard.value = [
              {
                url: "data:image/jpeg;base64," + data.data.bankCard,
                isImage: true,
              },
            ];
          }
          if (data.data.businessLicense) {
            businessLicense.value = [
              {
                url: "data:image/jpeg;base64," + data.data.businessLicense,
                isImage: true,
              },
            ];
          }
          if (data.data.accountLicense) {
            accountLicense.value = [
              {
                url: "data:image/jpeg;base64," + data.data.accountLicense,
                isImage: true,
              },
            ];
          }
        }
      } catch (error) {
        console.log(error);
      }
    };

    onMounted(async () => {
      await getMchInfo();
      await getUserLicense();
      if (currentStep.value === 3) {
        changeApproveStatus();
        changeMchApproveStatus();
        changeSignStatus();
      }
    });

    const handleNextStep = () => {
      if (currentStep.value === 0) {
        // 先检查是否上传证件照
        if (merchantType.value === 0) {
          if (idCardFront.value.length === 0 || idCardBack.value.length === 0) {
            showToast("请先上传相关证照");
            return;
          }
        } else {
          if (businessLicense.value.length === 0) {
            showToast("请先上传相关证照");
            return;
          }
        }
        showConfirmSheet.value = true;
      }
      if (currentStep.value === 1) {
        // 先检查是否银行卡或者开户开户许可证
        if (merchantType.value === 0) {
          if (bankCard.value.length === 0) {
            showToast("请先上传银行卡");
            return;
          }
        } else {
          if (accountLicense.value.length === 0) {
            showToast("请先上传开户许可证");
            return;
          }
        }
        showConfirmSheet.value = true;
      }
      if (currentStep.value === 2) {
        showConfirmDialog({
          message: "请再次确认信息无误？",
        })
          .then(async () => {
            // 初次提交
            submitParam.value.bindingSteps = 2;
            try {
              const { data } = await createMch(submitParam.value);
              if (data.code === "00000") {
                // 提交成功，看图片是否上传
                const params = {
                  id: joinPayMchID.value,
                  adminId: user.id,
                  altMerchantType: formData.value.merchantType,
                  status: "0",
                };
                if (uploadStatus.value === 1 && auditStatus.value === 1) {
                  // 上传了，调用修改接口
                  params.status  = "1";
                }
                try {
                  const { data } = await uploadPhotos(params);
                  if (data.code === "00000") {
                    // 上传成功
                    uploadStatus.value = 1;
                    auditStatus.value = 0;
                    statusSubText.value = "预计3分钟内完成审核";
                  } else {
                    showToast(data.message);
                  }
                } catch (error) {
                  console.log(error);
                }
                infoStatus.value = 0;
                infoStatusSubText.value = "预计3分钟内完成认证";
                currentStep.value++;
              } else {
                showToast(data.message);
              }
            } catch (error) {
              console.log(error);
            }
          })
          .catch(() => {
            return;
          });
      }
      if (currentStep.value === 3) {
        if (infoStatus.value != 1) {
          showToast("请确认认证通过");
          return;
        }
        if (auditStatus.value != 1) {
          showToast("请确认证件审核通过");
          return;
        }
        showConfirmDialog({
          message: "确认签约？",
        })
          .then(async () => {
            // 签约
            try {
              const { data } = await altMchSign({ id: joinPayMchID.value });
              if (data.code === "00000") {
                showSuccessToast("签约成功");
                setTimeout(() => {
                  router.go(0);
                }, 1000);
              } else {
                showFailToast(data.message);
              }
            } catch (error) {
              console.error("请求发生错误:", error);
            }
          })
          .catch(() => {
            return;
          });
      }
    };

    // 更新图片审核情况
    const changeApproveStatus = async () => {
      const { data } = await updateApproveStatus({ id: joinPayMchID.value });
      if (data.code === "00000") {
        if (data.data === "P1000") {
          auditStatus.value = 1;
          statusSubText.value = "审核通过";
        }
      }
    };

    // 更新商户认证状态
    const changeMchApproveStatus = async () => {
      const { data } = await updateMchApproveStatus({ id: joinPayMchID.value });
      if (data.code === "00000") {
        if (data.data === "P1000") {
          auditStatus.value = 1;
          statusSubText.value = "审核通过";
        }
      }
    };

    // 更新签约状态
    const changeSignStatus = async () => {
      const { data } = await updateMchSignStatus({ id: joinPayMchID.value });
      if (data.code === "00000") {
        if (data.data === "P1000") {
          auditStatus.value = 1;
          statusSubText.value = "审核通过";
        }
      }
    };

    // 跳转修改认证信息
    const handleInfoReupload = () => {
      currentStep.value = 0;
    };

    // 修改银行卡
    const updateBankCard = () => {
      currentStep.value = 1;
    };

    const handlePrevStep = () => {
      if (currentStep.value > 0) currentStep.value--;
    };

    // 格式化身份证号码
    const formatIdCard = (value) => {
      // 步骤1：过滤非法字符（保留数字和X）
      let val = value.replace(/[^\dXx]/g, "");

      // 步骤2：自动大写转换
      val = val.toUpperCase();

      // 步骤3：智能分段（前6位+8位+4位）
      const parts = [];
      if (val.length > 6) {
        parts.push(val.substr(0, 6));
        val = val.substr(6);
      }
      if (val.length > 8) {
        parts.push(val.substr(0, 8));
        val = val.substr(8);
      }
      parts.push(val);

      // 步骤4：组合分段并限制最大长度
      return parts.join(" ").substr(0, 21);
    };

    // 格式化手机
    const formatPhone = (value) => {
      // 1. 去除非数字字符并截取前11位
      const phone = value.replace(/\D/g, "").slice(0, 11);

      // 2. 按 3-4-4 格式添加空格
      return phone.replace(/(\d{3})(\d{0,4})(\d{0,4})/, (_, $1, $2, $3) => {
        let formatted = $1;
        if ($2) formatted += ` ${$2}`;
        if ($3) formatted += ` ${$3}`;
        return formatted;
      });
    };

    return {
      // 响应式数据
      currentStep,
      merchantType,
      idCardFront,
      idCardBack,
      businessLicense,
      bankCard,
      accountLicense,
      formData,
      minDate,
      maxDate,
      companyDate,
      validDate,
      activeCollapse,
      auditStatus,
      statusClass,
      statusIcon,
      statusMainText,
      statusSubText,
      infoStatusClass,
      infoStatusIcon,
      infoStatusMainText,
      infoStatusSubText,
      infoStatus,
      signStatus,
      signStatusClass,
      signStatusIcon,
      signStatusMainText,
      signStatusSubText,

      joinPayMchNo,

      // 方法
      handleNextStep,
      handlePrevStep,
      afterRead,
      formatIdCard,
      formatPhone,
      idDateConfirm,
      confirmInfo,
      companyDateConfirm,
      handleInfoReupload,
      updateBankCard,

      // 弹窗
      showConfirmSheet,
      showDatePicker,
      showCompanyDatePicker,
    };
  },
};
</script>

<style lang="less" scoped>
.bind-page {
  background: #f8f9ff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  overflow-y: auto;
}

.main-content::-webkit-scrollbar {
  width: 6px;
  background: #f1f1f1;
}

.main-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.step-container {
  background: white;
  padding: 15px;
  margin: 10px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(77, 106, 221, 0.05);

  :deep(.van-step__title) {
    font-size: 0.35rem;
  }
}

.card-section {
  margin: 10px;
}

.upload-card {
  background: white;
  border-radius: 0 0 12px 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(77, 106, 221, 0.08);

  .upload-title {
    // color: #4d6add;
    font-size: 16px;
    // margin-bottom: 15px;
    position: relative;
    padding-left: 12px;
    /* 留出装饰条位置 */

    .title-decoration {
      position: absolute;
      left: 0;
      top: 55%;
      transform: translateY(-50%);
      width: 3px;
      height: 16px;
      background: #4d6add;
      border-radius: 2px;
    }
  }
}

.upload-group {
  display: grid;
  grid-template-columns: 1.2fr 1fr;
  gap: 10px;
  margin-bottom: 15px;
}

.upload-item {
  border: 2px dashed #e0e3ff;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s;
  width: 3rem;

  p {
    color: #666;
    margin-top: 8px;
    font-size: 12px;
  }

  &.single {
    grid-column: span 2;
  }

  &:active {
    border-color: #4d6add;
    background: rgba(77, 106, 221, 0.05);
  }
}

.custom-uploader :deep(.van-uploader__preview-image) {
  width: 4rem !important;
  height: 2.8rem !important;
  border-radius: 6px;
}

.custom-uploader :deep(.van-uploader__preview) {
  width: 4rem !important;
  height: 100% !important;
  margin: 0 !important;
}

/* 信息审核样式 */
.review-section {
  padding: 12px;

  .van-collapse-item__content {
    padding: 0;
  }

  .van-cell {
    background: #f8f9ff;
    margin: 4px 0;
    border-radius: 6px;
  }
}

.sign-section {
  margin: 10px;

  .audit-status-bar {
    background: #f8f9ff;
    border-radius: 8px;
    padding: 16px;
    margin: 20px 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid transparent;

    .status-content {
      display: flex;
      align-items: center;
      gap: 12px;

      .status-icon {
        font-size: 22px;
      }

      .status-text {
        line-height: 1.4;

        .main-text {
          color: #333;
          font-weight: 500;
          font-size: 14px;
        }

        .sub-text {
          color: #666;
          font-size: 12px;
        }
      }
    }

    // 不同状态样式
    &--success {
      border-color: #38b48d;
      background: #e8faf0;

      .status-icon {
        color: #38b48d;
      }
    }

    &--warning {
      border-color: #ff9500;
      background: #fff4e8;

      .status-icon {
        color: #ff9500;
      }
    }

    &--error {
      border-color: #ff4d4f;
      background: #ffecec;

      .status-icon {
        color: #ff4d4f;
      }
    }
  }

  .sign-notice {
    margin-top: 20px;
    padding: 12px;
    background: #fffbe8;
    border-radius: 6px;
    color: #ff9500;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 8px;

    .van-icon {
      flex-shrink: 0;
    }
  }
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  padding: 8px;

  .preview-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);

    .van-image {
      width: 100%;
      height: 120px;
    }

    .file-name {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 4px;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      font-size: 12px;
      text-align: center;
    }
  }
}

/* 固定底部容器 */
.action-section {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 12px 16px;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

/* 提示语样式 */
.action-notice {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #fffbe8;
  border-radius: 6px;
  color: #ed6a0c;
  font-size: 13px;
  line-height: 1.5;
  animation: slideUp 0.3s ease;
}

.notice-icon {
  margin-right: 6px;
  font-size: 16px;
  flex-shrink: 0;
}

/* 按钮容器 */
.action-buttons {
  display: flex;
  gap: 10px;

  .prev-btn {
    flex: 2;
    border-color: #4d6add;
    color: #4d6add;
    margin: 0 10px;
  }

  .next-btn {
    flex: 2;
    background: #4d6add;
    margin: 0 10px;
  }

  :deep(.van-button__text) {
    font-size: 16px;
  }
}

/* 主要内容区域需要添加底部padding防遮挡 */
// .main-content {
//   // padding-bottom: 10px;
//   /* 根据实际高度调整 */
// }

/* 动画效果 */
@keyframes slideUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 自定义 ActionSheet 样式 */
:deep(.van-action-sheet) {
  border-radius: 16px 16px 0 0;
  overflow: visible;

  .van-action-sheet__header {
    font-size: 18px;
    color: #4d6add;
    font-weight: 500;
    padding: 18px 16px;
    background: linear-gradient(to bottom, #f8f9ff, white 60%);
  }
}

.sheet-content {
  padding: 0 16px 20px;
  max-height: 70vh;
  // overflow-y: auto;

  .van-cell {
    background: #f8f9ff;
    margin: 8px 0;
    border-radius: 8px;

    &::after {
      display: none;
    }

    &__title {
      flex: none;
      width: 80px;
    }
  }

  /* 自定义标题样式 */
  .custom-title {
    display: flex;
    align-items: center;
    padding: 5px 0;
  }

  .blue-line {
    display: inline-block;
    width: 4px;
    height: 16px;
    background: #4d6add;
    margin-right: 8px;
    border-radius: 2px;
  }

  .van-field {
    margin: 12px 0;
    background: #f8f9ff;
    border-radius: 8px;
    padding: 8px 16px;

    :deep(.van-field__label) {
      width: 80px;
      color: #666;
    }

    :deep(.van-field__control) {
      color: #333;
      font-weight: 500;
    }
  }

  /* 结算方式容器 */
  .settlement-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }

  /* 提示语样式 */
  .settlement-tip {
    display: flex;
    align-items: center;
    color: #999;
    font-size: 12px;
    /* 对齐单选按钮 */
    line-height: 1.4;

    .van-icon {
      margin-right: 4px;
    }
  }
}

.confirm-buttons {
  padding: 15px 0;
  .confirm-btn {
    background: #4d6add;
    border: none;
    font-size: 16px;

    &:active {
      opacity: 0.9;
    }
  }
}

.custom-date-picker {
  width: 100%;
}

/* 调整列宽 */
.year-column {
  width: 35% !important;
}

.month-column {
  width: 30% !important;
}

.day-column {
  width: 35% !important;
}

/* 长期选项样式 */
.van-picker-column__item--longterm {
  color: #1989fa;
  font-weight: bold;
}

/* 适配移动端 */
@media (max-width: 480px) {
  .upload-item {
    padding: 15px;
  }

  .upload-group {
    gap: 8px;
  }

  .sheet-content {
    padding: 0 12px 20px;

    .van-cell,
    .van-field {
      margin: 6px 0;
    }
  }

  .settlement-tip {
    font-size: 11px;
  }

  :deep(.van-action-sheet__header) {
    padding: 14px 12px;
    font-size: 16px;
  }
}
</style>
