<template>
  <div class="industry-qual-page">
    <h1 class="page-title">行业资质</h1>

    <section class="form-block">
      <h2 class="section-head">
        <span class="section-bar" aria-hidden="true" />
        行业资质
        <span class="section-intro">请填写商家的所属行业、特殊资质等信息</span>
      </h2>

      <el-form
        ref="formRef"
        class="industry-form"
        :model="form"
        :rules="rules"
        label-width="160px"
        require-asterisk-position="right"
        label-position="right"
      >
        <el-form-item label="所属行业" prop="industry">
          <el-select
            v-model="form.industry"
            placeholder="请选择"
            filterable
            clearable
            style="max-width: 480px"
            @change="onIndustryChange"
          >
            <el-option v-for="o in industryOptions" :key="o.value" :label="o.label" :value="o.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="结算费率">
          <span class="settlement-rate-text">{{ settlementRateText }}</span>
        </el-form-item>

        <!-- <el-form-item label="优惠费率活动（选填）" prop="discountActivity">
          <div class="field-stack">
            <el-select
              v-model="form.discountActivity"
              placeholder="请选择"
              clearable
              style="max-width: 480px"
            >
              <el-option
                v-for="o in discountActivityOptions"
                :key="o.value"
                :label="o.label"
                :value="o.value"
              />
            </el-select>
            <p class="field-tip">
              部分行业可报名优惠费率活动，活动介绍请查看
              <el-link type="primary" :underline="false" @click="openDiscountDetail">查看详情</el-link>
            </p>
          </div>
        </el-form-item> -->
      </el-form>
    </section>

    <div class="footer-actions">
      <el-button @click="onBack"> 返回 </el-button>
      <el-button type="primary" class="btn-next" :loading="submitLoading" @click="onSubmit"> 确定 </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { localGet, localSet } from "@/utils/index";

const BUSINESS_DATA_CACHE_KEY = "businessData";

const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const route = useRoute();
const router = useRouter();

/** 演示选项，可对接字典/接口 */
const industryOptions = [
  { label: "餐饮", value: "716" },
  { label: "零售", value: "catering_retail_retail" },
  { label: "生活服务", value: "life_service" },
  { label: "电商平台", value: "ecommerce" }
];

const discountActivityOptions = [
  { label: "活动一：新商户费率优惠", value: "act_1" },
  { label: "活动二：行业专项优惠", value: "act_2" }
];

/** 按行业展示结算费率（演示：默认与示意图一致） */
const industryRateMap: Record<string, string> = {
  "716": "0.6%",
  catering_retail_catering: "0.6%",
  catering_retail_retail: "0.6%",
  life_service: "0.6%",
  ecommerce: "0.6%"
};

const form = reactive({
  industry: "716",
  discountActivity: "" as string
});

const settlementRateText = computed(() => {
  if (!form.industry) return "—";
  return industryRateMap[form.industry] ?? "0.6%";
});

const rules: FormRules = {
  industry: [{ required: true, message: "请选择所属行业", trigger: "change" }]
};

function onIndustryChange() {
  formRef.value?.validateField("industry").catch(() => {});
}

function openDiscountDetail() {
  ElMessage.info("优惠费率活动说明（可对接文档或外链）");
}

function onBack() {
  router.push({ path: "/businessInfo/manageInfo", query: { ...route.query } });
}

function onSaveDraft() {
  ElMessage.success("草稿已保存（可对接接口）");
}

function mergeSettlementIntoBusinessDataCache() {
  const prev = localGet(BUSINESS_DATA_CACHE_KEY);
  const base = prev && typeof prev === "object" && !Array.isArray(prev) ? { ...(prev as Record<string, unknown>) } : {};
  const prevSt =
    base.settlement_info && typeof base.settlement_info === "object" && !Array.isArray(base.settlement_info)
      ? { ...(base.settlement_info as Record<string, unknown>) }
      : {};

  const selected = industryOptions.find(o => o.value === form.industry);
  const industryLabel = (selected?.label ?? "").trim();
  const settlementId = selected != null ? String(selected.value).trim() : "";

  base.settlement_info = {
    ...prevSt,
    qualification_type: industryLabel,
    settlement_id: settlementId
  };
  localSet(BUSINESS_DATA_CACHE_KEY, base);
}

async function onSubmit() {
  if (!formRef.value) return;
  submitLoading.value = true;
  try {
    await formRef.value.validate();
    mergeSettlementIntoBusinessDataCache();
    await router.push({
      path: "/businessInfo/accountInfo",
      query: { ...route.query }
    });
  } catch {
    ElMessage.warning("请完善必填信息");
  } finally {
    submitLoading.value = false;
  }
}
</script>

<style scoped lang="scss">
$wechat-green: #07c160;
.industry-qual-page {
  box-sizing: border-box;
  min-height: 100%;
  padding: 24px 32px 40px;
  margin: 0 auto;
  background: #ffffff;
}
.page-title {
  margin: 0 0 24px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}
.form-block {
  margin-bottom: 24px;
}
.section-head {
  display: flex;
  flex-wrap: wrap;
  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: $wechat-green;
  border-radius: 2px;
}
.section-intro {
  margin-left: 12px;
  font-size: 13px;
  font-weight: 400;
  line-height: 1.65;
  color: #909399;
}
.industry-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
}
.settlement-rate-text {
  font-size: 14px;
  color: #303133;
}
.field-stack {
  width: 100%;
}
.field-tip {
  margin: 8px 0 0;
  font-size: 12px;
  line-height: 1.65;
  color: #909399;
}
.footer-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 24px;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}
.footer-center {
  display: flex;
  flex: 1;
  justify-content: center;
}
.btn-next {
  min-width: 100px;
  background: $wechat-green;
  border-color: $wechat-green;
  &:hover {
    background: #06ad56;
    border-color: #06ad56;
  }
}
</style>
