<template>
  <div class="zfb-step-page">
    <header class="step-header">
      <el-steps :active="zfbStepActive" align-center finish-status="success" class="zfb-steps">
        <el-step title="第一步 完善商家信息" />
        <el-step title="第二步 完善结算信息" />
        <el-step title="第三步 提交审核" />
      </el-steps>
    </header>

    <div class="page-layout">
      <div class="main-column">
        <el-form
          ref="formRef"
          class="zfb-form"
          :model="form"
          :rules="rules"
          label-width="200px"
          require-asterisk-position="right"
          label-position="right"
        >
          <section id="zfb-settlement" class="form-block anchor-section">
            <h2 class="section-head">
              <span class="section-bar" aria-hidden="true" />
              结算信息
            </h2>

            <el-form-item label="请选择结算方式" prop="settlementMethod">
              <el-radio-group v-model="form.settlementMethod" class="radio-stack">
                <el-radio value="alipay"> 结算到支付宝 </el-radio>
                <el-radio value="bank"> 结算到银行卡 </el-radio>
              </el-radio-group>
            </el-form-item>

            <template v-if="form.settlementMethod === 'alipay'">
              <el-form-item label="支付宝账号" prop="alipayAccount">
                <el-input v-model="form.alipayAccount" placeholder="请输入支付宝账号" clearable style="max-width: 480px" />
                <el-alert class="settlement-tip-alert" type="info" :closable="false" show-icon>
                  注：账号主体名称需与营业执照同名
                </el-alert>
              </el-form-item>
            </template>

            <template v-if="form.settlementMethod === 'bank'">
              <el-form-item label="开户名称" prop="bankAccountName" required>
                <el-input v-model="form.bankAccountName" clearable maxlength="64" style="max-width: 480px" />
              </el-form-item>
              <el-form-item label="银行卡号" prop="bankCardNo" required>
                <el-input
                  v-model="form.bankCardNo"
                  placeholder="暂时只支持借记卡"
                  clearable
                  maxlength="24"
                  style="max-width: 480px"
                />
              </el-form-item>
              <el-form-item label="联行号" prop="cnapsCode">
                <el-input v-model="form.cnapsCode" placeholder="非必填" clearable maxlength="32" style="max-width: 480px" />
              </el-form-item>
              <el-form-item prop="bankBranch">
                <template #label>
                  <span class="bank-branch-required-label">开户银行</span>
                </template>
                <div class="bank-select-row">
                  <el-select
                    v-model="form.depositBankCode"
                    placeholder="请选择开户银行"
                    clearable
                    filterable
                    class="bank-select-cell"
                    @change="onDepositBankChange"
                  >
                    <el-option v-for="b in depositBankOptions" :key="b.value" :label="b.label" :value="b.value" />
                  </el-select>
                  <el-cascader
                    v-model="form.branchRegion"
                    :options="invoiceRegionCascaderOptions"
                    :props="{ emitPath: true }"
                    placeholder="请选择省 / 市"
                    clearable
                    filterable
                    class="bank-select-cell bank-region-cascader"
                    @change="onBranchRegionChange"
                  />
                  <el-input
                    v-model="form.branchName"
                    placeholder="请输入支行名称"
                    clearable
                    maxlength="80"
                    class="bank-select-cell bank-branch-input"
                    :disabled="!branchRegionCitySelected"
                    @blur="touchBankBranchValidate"
                    @clear="touchBankBranchValidate"
                  />
                </div>
              </el-form-item>
              <el-form-item label="账号使用类型" prop="accountUsageType" required>
                <el-radio-group v-model="form.accountUsageType" class="radio-stack" disabled>
                  <el-radio value="public"> 对公 </el-radio>
                  <el-radio value="private"> 对私 </el-radio>
                </el-radio-group>
              </el-form-item>
            </template>

            <!-- <el-form-item label="是否开票" prop="needInvoicing">
              <el-radio-group v-model="form.needInvoicing" class="radio-stack">
                <el-radio value="yes">是</el-radio>
                <el-radio value="no">否</el-radio>
              </el-radio-group>
            </el-form-item> -->

            <!-- <template v-if="form.needInvoicing === 'yes'">
              <div id="zfb-invoice" class="invoice-extra-wrap anchor-section">
                <div class="invoice-section-divider" />

                <el-form-item label="纳税人种类" prop="taxpayerType" required>
                  <el-radio-group v-model="form.taxpayerType" class="radio-stack">
                    <el-radio value="general">一般纳税人</el-radio>
                    <el-radio value="small_scale">小规模纳税人</el-radio>
                  </el-radio-group>
                </el-form-item>

                <div class="invoice-section-divider" />
                <h3 class="invoice-subsection-title">开票信息</h3>

                <el-form-item label="发票抬头" prop="invoiceTitle" required>
                  <el-input v-model="form.invoiceTitle" clearable maxlength="128" style="max-width: 480px" />
                </el-form-item>
                <el-form-item label="纳税人识别号" prop="taxpayerIdNo" required>
                  <el-input v-model="form.taxpayerIdNo" clearable maxlength="32" style="max-width: 480px" />
                </el-form-item>
                <el-form-item label="纳税人资格开始时间" prop="qualificationStartDate" required>
                  <el-date-picker
                    v-model="form.qualificationStartDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 320px; max-width: 100%"
                    clearable
                    @change="touchQualificationDateValidate"
                  />
                </el-form-item>
                <template v-if="form.taxpayerType === 'general'">
                  <el-form-item label="开票地址" prop="invoiceAddress" required>
                    <el-input v-model="form.invoiceAddress" clearable maxlength="200" style="max-width: 480px" />
                  </el-form-item>
                  <el-form-item label="开票电话" prop="invoicePhone" required>
                    <el-input v-model="form.invoicePhone" clearable maxlength="20" style="max-width: 480px" />
                  </el-form-item>
                  <el-form-item label="银行卡号" prop="invoiceBankCardNo" required>
                    <el-input v-model="form.invoiceBankCardNo" clearable maxlength="24" style="max-width: 480px" />
                  </el-form-item>
                  <el-form-item label="开户银行" prop="invoiceOpeningBank" required>
                    <el-input v-model="form.invoiceOpeningBank" clearable maxlength="64" style="max-width: 480px" />
                  </el-form-item>
                </template>

                <div id="zfb-invoice-mail" class="invoice-section-divider" />
                <h3 class="invoice-subsection-title">发票寄送信息</h3>

                <el-form-item label="发票寄送地址" prop="invoiceMailSuite" required>
                  <div class="mail-address-stack">
                    <el-cascader
                      v-model="form.invoiceMailRegion"
                      :options="invoiceRegionCascaderOptions"
                      :placeholder="
                        form.taxpayerType === 'small_scale' ? '请输入具体门牌号等' : '请选择省 / 市'
                      "
                      filterable
                      clearable
                      class="mail-cascader"
                      @change="touchInvoiceMailSuiteValidate"
                    />
                    <el-input
                      v-model="form.invoiceMailAddressDetail"
                      placeholder="请输入具体门牌号等"
                      clearable
                      maxlength="200"
                      class="mail-detail-input"
                      @blur="touchInvoiceMailSuiteValidate"
                    />
                  </div>
                </el-form-item>
                <el-form-item label="收件人姓名" prop="invoiceRecipientName" required>
                  <el-input v-model="form.invoiceRecipientName" clearable maxlength="32" style="max-width: 480px" />
                </el-form-item>
                <el-form-item label="收件人手机号" prop="invoiceRecipientPhone" required>
                  <el-input v-model="form.invoiceRecipientPhone" clearable maxlength="11" style="max-width: 480px" />
                </el-form-item>
              </div>
            </template> -->
          </section>
        </el-form>

        <div class="footer-actions">
          <el-button type="primary" class="btn-primary-zfb" :loading="submitLoading" @click="onConfirmSubmit">
            确认提交
          </el-button>
        </div>
      </div>

      <aside class="anchor-column">
        <el-affix :offset="88">
          <div class="anchor-card">
            <el-anchor :offset="72" direction="vertical">
              <el-anchor-link href="#zfb-settlement" title="结算信息" />
              <el-anchor-link v-if="form.needInvoicing === 'yes'" href="#zfb-invoice" title="开票信息" />
              <el-anchor-link v-if="form.needInvoicing === 'yes'" href="#zfb-invoice-mail" title="发票寄送" />
            </el-anchor>
          </div>
        </el-affix>
      </aside>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { localGet, localSet } from "@/utils/index";
import { getAlipayZftCreate } from "@/api/modules/businessInfo";
import cityJson from "@/assets/json/city.json";

type CityJsonEntry = { name: string; adCode: string; cityCode: string };
type CityJsonRoot = { cityList: { letter: string; list: CityJsonEntry[] }[] };

const PROVINCE_ROWS: [string, string][] = [
  ["11", "北京市"],
  ["12", "天津市"],
  ["13", "河北省"],
  ["14", "山西省"],
  ["15", "内蒙古自治区"],
  ["21", "辽宁省"],
  ["22", "吉林省"],
  ["23", "黑龙江省"],
  ["31", "上海市"],
  ["32", "江苏省"],
  ["33", "浙江省"],
  ["34", "安徽省"],
  ["35", "福建省"],
  ["36", "江西省"],
  ["37", "山东省"],
  ["41", "河南省"],
  ["42", "湖北省"],
  ["43", "湖南省"],
  ["44", "广东省"],
  ["45", "广西壮族自治区"],
  ["46", "海南省"],
  ["50", "重庆市"],
  ["51", "四川省"],
  ["52", "贵州省"],
  ["53", "云南省"],
  ["54", "西藏自治区"],
  ["61", "陕西省"],
  ["62", "甘肃省"],
  ["63", "青海省"],
  ["64", "宁夏回族自治区"],
  ["65", "新疆维吾尔自治区"],
  ["71", "台湾省"],
  ["81", "香港特别行政区"],
  ["82", "澳门特别行政区"]
];
const PROVINCE_BY_PREFIX = Object.fromEntries(PROVINCE_ROWS) as Record<string, string>;
const PROVINCE_PREFIX_ORDER = PROVINCE_ROWS.map(([k]) => k);

function buildProvinceCityOptions(): {
  label: string;
  value: string;
  cities: { label: string; value: string }[];
}[] {
  const root = cityJson as CityJsonRoot;
  const flat = root.cityList.flatMap(g => g.list);
  const bucket = new Map<string, Map<string, CityJsonEntry>>();
  for (const c of flat) {
    const digits = String(c.adCode ?? "").replace(/\D/g, "");
    const code = digits.length >= 6 ? digits.slice(-6) : digits.padStart(6, "0");
    if (code.length !== 6) continue;
    const prefix = code.slice(0, 2);
    if (!PROVINCE_BY_PREFIX[prefix]) continue;
    if (!bucket.has(prefix)) bucket.set(prefix, new Map());
    bucket.get(prefix)!.set(c.adCode, c);
  }
  const out = [...bucket.entries()].map(([prefix, cityMap]) => ({
    value: prefix,
    label: PROVINCE_BY_PREFIX[prefix],
    cities: [...cityMap.values()]
      .sort((a, b) => a.name.localeCompare(b.name, "zh-CN"))
      .map(ci => ({ label: ci.name, value: ci.adCode }))
  }));
  out.sort((a, b) => {
    const ia = PROVINCE_PREFIX_ORDER.indexOf(a.value);
    const ib = PROVINCE_PREFIX_ORDER.indexOf(b.value);
    return (ia === -1 ? 999 : ia) - (ib === -1 ? 999 : ib);
  });
  return out;
}

const provinceCityOptions = buildProvinceCityOptions();

const invoiceRegionCascaderOptions = computed(() =>
  provinceCityOptions.map(p => ({
    value: p.value,
    label: p.label,
    children: p.cities.map(c => ({ value: c.value, label: c.label }))
  }))
);

const depositBankOptions = [
  { label: "工商银行", value: "ICBC" },
  { label: "农业银行", value: "ABC" },
  { label: "中国银行", value: "BOC" },
  { label: "建设银行", value: "CCB" },
  { label: "交通银行", value: "COMM" },
  { label: "邮储银行", value: "PSBC" },
  { label: "招商银行", value: "CMB" },
  { label: "浦发银行", value: "SPDB" },
  { label: "兴业银行", value: "CIB" },
  { label: "民生银行", value: "CMBC" },
  { label: "华夏银行", value: "HXB" },
  { label: "广发银行", value: "GDB" },
  { label: "平安银行", value: "PAB" },
  { label: "中信银行", value: "CITIC" },
  { label: "光大银行", value: "CEB" },
  { label: "上海银行", value: "BOSH" },
  { label: "北京银行", value: "BRCB" },
  { label: "其他银行", value: "OTHER" }
];

const formRef = ref<FormInstance>();
const submitLoading = ref(false);

/** 第二步：索引为 1 */
const zfbStepActive = ref(1);

const form = reactive({
  settlementMethod: "alipay" as "alipay" | "bank",
  alipayAccount: "",
  bankAccountName: "",
  bankCardNo: "",
  cnapsCode: "",
  /** 联表校验占位，不绑定输入 */
  bankBranch: "",
  depositBankCode: "",
  /** 支行地区 [省前缀, 市 adCode]，与第一步店铺地址级联一致 */
  branchRegion: [] as string[],
  branchName: "",
  accountUsageType: "public" as "public" | "private",
  needInvoicing: "no" as "yes" | "no",
  taxpayerType: "general" as "general" | "small_scale",
  invoiceTitle: "",
  taxpayerIdNo: "",
  qualificationStartDate: "" as string,
  invoiceAddress: "",
  invoicePhone: "",
  invoiceBankCardNo: "",
  invoiceOpeningBank: "",
  /** 级联 [省前缀, 市 adCode] */
  invoiceMailRegion: [] as string[],
  invoiceMailAddressDetail: "",
  /** 发票寄送地址联校占位 */
  invoiceMailSuite: "",
  invoiceRecipientName: "",
  invoiceRecipientPhone: ""
});

/** 已选省、市后可填写支行名称 */
const branchRegionCitySelected = computed(
  () => Array.isArray(form.branchRegion) && form.branchRegion.length >= 2 && !!String(form.branchRegion[1] || "").trim()
);

function touchBankBranchValidate() {
  nextTick(() => formRef.value?.validateField("bankBranch"));
}

function onDepositBankChange() {
  form.branchRegion = [];
  form.branchName = "";
  touchBankBranchValidate();
}

function onBranchRegionChange() {
  form.branchName = "";
  touchBankBranchValidate();
}

function touchInvoiceMailSuiteValidate() {
  nextTick(() => formRef.value?.validateField("invoiceMailSuite"));
}

function touchQualificationDateValidate() {
  nextTick(() => formRef.value?.validateField("qualificationStartDate"));
}

const rules: FormRules = {
  settlementMethod: [{ required: true, message: "请选择结算方式", trigger: "change" }],
  alipayAccount: [
    {
      validator: (_r, _v, cb) => {
        if (form.settlementMethod !== "alipay") return cb();
        if (!String(form.alipayAccount || "").trim()) cb(new Error("请输入支付宝账号"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  bankAccountName: [
    {
      validator: (_r, _v, cb) => {
        if (form.settlementMethod !== "bank") return cb();
        if (!String(form.bankAccountName || "").trim()) cb(new Error("请输入开户名称"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  bankCardNo: [
    {
      validator: (_r, _v, cb) => {
        if (form.settlementMethod !== "bank") return cb();
        const v = String(form.bankCardNo || "")
          .replace(/\s+/g, "")
          .trim();
        if (!v) cb(new Error("请输入银行卡号"));
        else if (!/^\d{16,24}$/.test(v)) cb(new Error("请输入正确的借记卡卡号（16～24 位数字）"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  cnapsCode: [
    {
      validator: (_r, _v, cb) => {
        if (form.settlementMethod !== "bank") return cb();
        const v = String(form.cnapsCode || "").trim();
        if (!v) return cb();
        if (!/^\d{8,14}$/.test(v)) cb(new Error("联行号格式不正确"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  bankBranch: [
    {
      validator: (_r, _v, cb) => {
        if (form.settlementMethod !== "bank") return cb();
        if (!form.depositBankCode) cb(new Error("请选择开户银行"));
        else if (!Array.isArray(form.branchRegion) || form.branchRegion.length < 2) {
          cb(new Error("请选择支行地区（省、市）"));
        } else if (!String(form.branchName || "").trim()) cb(new Error("请输入支行名称"));
        else cb();
      },
      trigger: "change"
    }
  ],
  accountUsageType: [
    {
      validator: (_r, _v, cb) => {
        if (form.settlementMethod !== "bank") return cb();
        if (form.accountUsageType !== "public" && form.accountUsageType !== "private") {
          cb(new Error("请选择账号使用类型"));
        } else cb();
      },
      trigger: "change"
    }
  ],
  needInvoicing: [{ required: true, message: "请选择是否开票", trigger: "change" }],
  taxpayerType: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        if (form.taxpayerType !== "general" && form.taxpayerType !== "small_scale") {
          cb(new Error("请选择纳税人种类"));
        } else cb();
      },
      trigger: "change"
    }
  ],
  invoiceTitle: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        if (!String(form.invoiceTitle || "").trim()) cb(new Error("请输入发票抬头"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  taxpayerIdNo: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        const v = String(form.taxpayerIdNo || "")
          .trim()
          .toUpperCase();
        if (!v) cb(new Error("请输入纳税人识别号"));
        else if (v.length < 15 || v.length > 20) cb(new Error("纳税人识别号长度应为 15～20 位"));
        else if (!/^[0-9A-Z]+$/.test(v)) cb(new Error("纳税人识别号仅含数字与字母"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  qualificationStartDate: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        if (!String(form.qualificationStartDate || "").trim()) cb(new Error("请选择纳税人资格开始时间"));
        else cb();
      },
      trigger: "change"
    }
  ],
  invoiceAddress: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes" || form.taxpayerType !== "general") return cb();
        if (!String(form.invoiceAddress || "").trim()) cb(new Error("请输入开票地址"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  invoicePhone: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes" || form.taxpayerType !== "general") return cb();
        const v = String(form.invoicePhone || "").trim();
        if (!v) cb(new Error("请输入开票电话"));
        else if (!/^[\d\-+\s]{5,20}$/.test(v)) cb(new Error("请输入有效的开票电话"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  invoiceBankCardNo: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes" || form.taxpayerType !== "general") return cb();
        const v = String(form.invoiceBankCardNo || "")
          .replace(/\s+/g, "")
          .trim();
        if (!v) cb(new Error("请输入银行卡号"));
        else if (!/^\d{16,24}$/.test(v)) cb(new Error("请输入正确的银行卡号（16～24 位数字）"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  invoiceOpeningBank: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes" || form.taxpayerType !== "general") return cb();
        if (!String(form.invoiceOpeningBank || "").trim()) cb(new Error("请输入开户银行"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  invoiceMailSuite: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        const reg = form.invoiceMailRegion;
        if (!Array.isArray(reg) || reg.length < 2 || !String(reg[0] || "").trim() || !String(reg[1] || "").trim()) {
          cb(new Error("请选择发票寄送省/市"));
        } else if (!String(form.invoiceMailAddressDetail || "").trim()) {
          cb(new Error("请输入具体门牌号等"));
        } else cb();
      },
      trigger: "change"
    }
  ],
  invoiceRecipientName: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        if (!String(form.invoiceRecipientName || "").trim()) cb(new Error("请输入收件人姓名"));
        else cb();
      },
      trigger: "blur"
    }
  ],
  invoiceRecipientPhone: [
    {
      validator: (_r, _v, cb) => {
        if (form.needInvoicing !== "yes") return cb();
        const v = String(form.invoiceRecipientPhone || "").trim();
        if (!v) cb(new Error("请输入收件人手机号"));
        else if (!/^1\d{10}$/.test(v)) cb(new Error("请输入正确的手机号"));
        else cb();
      },
      trigger: "blur"
    }
  ]
};

const ALIPAY_JSON_KEY = "alipayJson";

/** 结算到银行卡时写入 alipayJson.bizCards[]（与直付通字段约定一致） */
type AlipayBizCardPayload = {
  accountHolderName: string;
  accountNo: string;
  accountInstProvince: string;
  accountInstCity: string;
  accountBranchName: string;
  /** 对公 01，对私 02 */
  usageType: string;
  accountType: "DC";
  accountInstName: string;
  /** 开户行缩写，与 depositBankCode 一致（如 ICBC） */
  accountInstId: string;
};

/** 由支行地区级联 [省前缀, 市 adCode] 解析省名、市名 */
function resolveBranchRegionProvinceCity(): { province: string; city: string } {
  const reg = form.branchRegion;
  if (!Array.isArray(reg) || reg.length < 2) return { province: "", city: "" };
  const prov = provinceCityOptions.find(p => p.value === reg[0]);
  const cityAd = String(reg[1] || "").trim();
  const city = prov?.cities.find(c => c.value === cityAd);
  return {
    province: prov?.label ?? "",
    city: city?.label ?? ""
  };
}

function buildBizCardsForPayload(): AlipayBizCardPayload[] {
  if (form.settlementMethod !== "bank") return [];
  const bankMeta = depositBankOptions.find(b => b.value === form.depositBankCode);
  const { province, city } = resolveBranchRegionProvinceCity();
  const usageType = form.accountUsageType === "public" ? "01" : "02";
  return [
    {
      accountHolderName: String(form.bankAccountName || "").trim(),
      accountNo: String(form.bankCardNo || "")
        .replace(/\s+/g, "")
        .trim(),
      accountInstProvince: province,
      accountInstCity: city,
      accountBranchName: String(form.branchName || "").trim(),
      usageType,
      accountType: "DC",
      accountInstName: bankMeta?.label ?? "",
      accountInstId: String(form.depositBankCode || "").trim()
    }
  ];
}

async function onConfirmSubmit() {
  if (!formRef.value) return;
  submitLoading.value = true;
  try {
    await formRef.value.validate();
  } catch {
    ElMessage.warning("请完善必填信息");
    submitLoading.value = false;
    return;
  }
  try {
    const alipayJson = localGet(ALIPAY_JSON_KEY) as Record<string, unknown> | null | undefined;
    if (!alipayJson || typeof alipayJson !== "object" || Array.isArray(alipayJson)) {
      ElMessage.warning("缺少步骤一提交数据，请先完成主体信息并点击下一步");
      return;
    }
    const payload: Record<string, unknown> = { ...alipayJson };
    const alipayLogonId =
      form.settlementMethod === "alipay" ? String(form.alipayAccount || "").trim() : String(payload.alipayLogonId ?? "").trim();
    payload.alipayLogonId = alipayLogonId;

    if (form.settlementMethod === "bank") {
      payload.bizCards = buildBizCardsForPayload();
    } else {
      delete payload.bizCards;
    }

    localSet(ALIPAY_JSON_KEY, payload);
    await getAlipayZftCreate(payload);
    ElMessage.success("提交成功");
  } catch {
    ElMessage.error("提交失败，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
}

const invoiceFieldProps = [
  "taxpayerType",
  "invoiceTitle",
  "taxpayerIdNo",
  "qualificationStartDate",
  "invoiceAddress",
  "invoicePhone",
  "invoiceBankCardNo",
  "invoiceOpeningBank",
  "invoiceMailSuite",
  "invoiceRecipientName",
  "invoiceRecipientPhone"
] as const;

watch(
  () => form.settlementMethod,
  v => {
    if (v === "bank") form.accountUsageType = "public";
    nextTick(() => {
      formRef.value?.clearValidate([
        "alipayAccount",
        "bankAccountName",
        "bankCardNo",
        "cnapsCode",
        "bankBranch",
        "accountUsageType"
      ]);
    });
  }
);

watch(
  () => form.needInvoicing,
  v => {
    nextTick(() => {
      if (v !== "yes") {
        formRef.value?.clearValidate([...invoiceFieldProps]);
      }
    });
  }
);

const generalTaxpayerInvoiceExtraProps = ["invoiceAddress", "invoicePhone", "invoiceBankCardNo", "invoiceOpeningBank"] as const;

watch(
  () => form.taxpayerType,
  () => {
    if (form.needInvoicing !== "yes") return;
    nextTick(() => {
      formRef.value?.clearValidate([...generalTaxpayerInvoiceExtraProps]);
    });
  }
);

onMounted(() => {
  formRef.value?.clearValidate();
});
</script>

<style scoped lang="scss">
$zfb-blue: #1677ff;
.zfb-step-page {
  box-sizing: border-box;
  min-height: 100%;
  padding: 24px 32px 48px;
  background: #ffffff;
}
.step-header {
  max-width: 960px;
  margin: 0 auto 32px;
}
.zfb-steps {
  :deep(.el-step__head.is-process) {
    color: $zfb-blue;
    border-color: $zfb-blue;
  }
  :deep(.el-step__head.is-finish) {
    color: $zfb-blue;
    border-color: $zfb-blue;
  }
  :deep(.el-step__title.is-process) {
    font-weight: 600;
    color: $zfb-blue;
  }
  :deep(.el-step__title.is-finish) {
    font-weight: 500;
    color: #606266;
  }
  :deep(.el-step__title.is-wait) {
    color: #c0c4cc;
  }
}
.page-layout {
  display: flex;
  gap: 32px;
  align-items: flex-start;
  max-width: 1100px;
  margin: 0 auto;
}
.main-column {
  flex: 1;
  min-width: 0;
}
.anchor-column {
  flex-shrink: 0;
  width: 160px;
}
.anchor-card {
  padding: 16px 12px;
}
.anchor-title {
  margin-bottom: 12px;
  font-size: 13px;
  font-weight: 600;
  color: #303133;
}
.zfb-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
}

/* 开户银行 prop 为联校占位 bankBranch，不能用 el-form-item required，否则恒校验失败 */
.bank-branch-required-label::after {
  margin-left: 4px;
  color: var(--el-color-danger);
  content: "*";
}
.form-block {
  padding-bottom: 8px;
  margin-bottom: 8px;
  scroll-margin-top: 72px;
}
.section-head {
  display: flex;
  align-items: center;
  margin: 0 0 20px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.section-bar {
  display: inline-block;
  flex-shrink: 0;
  width: 4px;
  height: 16px;
  margin-right: 8px;
  background: $zfb-blue;
  border-radius: 2px;
}
.radio-stack {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 20px;
  align-items: flex-start;
}
.settlement-tip-alert {
  max-width: 480px;
  margin-top: 12px;
  color: #1677ff;
  background: rgb(22 119 255 / 10%);
  border: 1px solid #1677ff;
}
:deep(.el-alert__description) {
  color: #333333 !important;
}
.bank-select-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  max-width: 100%;
}
.bank-select-cell {
  width: 200px;
  min-width: 160px;
}
.bank-region-cascader {
  width: 260px;
  min-width: 220px;
}
.bank-branch-input {
  width: 280px;
  min-width: 200px;
}
.invoice-extra-wrap {
  padding-top: 8px;
  margin-top: 8px;
}
.invoice-section-divider {
  height: 1px;
  margin: 24px 0 20px;
  background: #ebeef5;
}
.invoice-subsection-title {
  margin: 0 0 16px;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}
.mail-address-stack {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
  max-width: 480px;
}
.mail-cascader {
  width: 100%;
}
.mail-detail-input {
  width: 100%;
}
.footer-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: center;
  padding-top: 24px;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}
.btn-primary-zfb {
  min-width: 120px;
  background: $zfb-blue;
  border-color: $zfb-blue;
  &:hover {
    background: #4096ff;
    border-color: #4096ff;
  }
}
:deep(.anchor-card .el-anchor) {
  background: transparent;
  border-left: 1px solid #ebeef5;
}
:deep(.anchor-card .el-anchor__link) {
  padding: 6px 0;
  font-size: 13px;
}
</style>
