<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="商户名称" prop="merchantName">
          <el-input v-model="queryParams.merchantName" placeholder="商户名称/所属单位" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="认证状态" prop="certStatus">
          <el-select v-model="queryParams.certStatus" placeholder="全部" clearable style="width: 120px">
            <el-option label="正常" value="0" />
            <el-option label="已冻结" value="1" />
            <el-option label="已注销" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['agri:merchant:add']">添加商户</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="merchantList">
        <el-table-column label="商户所属单位" align="center" prop="unitName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="商户类型" align="center" prop="merchantType" width="90">
          <template slot-scope="scope">{{ scope.row.merchantType === '2' ? '企业' : '个人' }}</template>
        </el-table-column>
        <el-table-column label="商户名称" align="center" prop="merchantName" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.merchantName || '待完善' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contactName" width="100">
          <template slot-scope="scope"><span>{{ scope.row.contactName || '—' }}</span></template>
        </el-table-column>
        <el-table-column label="联系人手机" align="center" prop="contactPhone" width="120">
          <template slot-scope="scope"><span>{{ scope.row.contactPhone || '—' }}</span></template>
        </el-table-column>
        <el-table-column label="已绑定店铺" align="center" prop="shopCount" width="100" />
        <el-table-column label="认证状态" align="center" prop="certStatus" width="90">
          <template slot-scope="scope">
            <el-tag size="small" :type="certStatusTag(scope.row.certStatus)">{{ certStatusLabel(scope.row.certStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="认证时间" align="center" prop="certTime" width="160">
          <template slot-scope="scope"><span>{{ parseTime(scope.row.certTime) }}</span></template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:merchant:query']">详情</el-button>
            <el-button v-if="scope.row.canEdit" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:merchant:edit']">编辑</el-button>
            <el-button v-if="scope.row.canDelete" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:merchant:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="860px" append-to-body top="5vh" @close="cancel">
      <el-form ref="form" :model="form" :rules="formRules" label-width="130px">
        <el-tabs v-model="activeTab">
          <!-- 主体资质 -->
          <el-tab-pane label="主体资质" name="subject">
            <el-form-item v-if="!form.merchantId" label="主体类型" prop="merchantType">
              <el-radio-group v-model="form.merchantType" @change="handleTypeChange">
                <el-radio label="1">个人</el-radio>
                <el-radio label="2">企业</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-else label="主体类型">
              <span>{{ form.merchantType === '2' ? '企业' : '个人' }}</span>
            </el-form-item>

            <!-- 个人主体 -->
            <template v-if="form.merchantType === '1'">
              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="姓名" prop="personName"><el-input v-model="form.personName" maxlength="64" /></el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件类型" prop="idCardType">
                    <el-radio-group v-model="form.idCardType">
                      <el-radio label="1">大陆身份证</el-radio>
                      <el-radio label="2">来往内地通行证</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件号码" prop="idCardNo">
                    <el-input v-model="form.idCardNo" maxlength="18" :disabled="!!form.merchantId" placeholder="选填" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出生日期" prop="birthDate">
                    <el-date-picker v-model="form.birthDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                      <el-radio label="0">男</el-radio>
                      <el-radio label="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="证件有效期" prop="idValidType">
                    <el-radio-group v-model="form.idValidType">
                      <el-radio label="1">区间有效</el-radio>
                      <el-radio label="2">长期有效</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col v-if="form.idValidType === '1'" :span="24">
                  <el-form-item label="有效区间" prop="idValidRange">
                    <el-date-picker v-model="form.idValidRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col v-if="form.idValidType === '2'" :span="12">
                  <el-form-item label="起始日期" prop="idValidStart">
                    <el-date-picker v-model="form.idValidStart" type="date" value-format="yyyy-MM-dd" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="居住地址" prop="residenceAddress"><el-input v-model="form.residenceAddress" maxlength="255" /></el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件照正面" prop="idCardFront">
                    <image-upload v-model="form.idCardFront" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件照反面" prop="idCardBack">
                    <image-upload v-model="form.idCardBack" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>

            <!-- 企业主体 -->
            <template v-else>
              <p class="form-section-title">法定代表人信息</p>
              <el-row :gutter="16">
                <el-col :span="12"><el-form-item label="姓名" prop="legalName"><el-input v-model="form.legalName" maxlength="64" /></el-form-item></el-col>
                <el-col :span="12">
                  <el-form-item label="证件类型" prop="legalIdCardType">
                    <el-radio-group v-model="form.legalIdCardType">
                      <el-radio label="1">大陆身份证</el-radio>
                      <el-radio label="2">来往内地通行证</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12"><el-form-item label="证件号码" prop="legalIdCardNo"><el-input v-model="form.legalIdCardNo" maxlength="18" placeholder="选填" /></el-form-item></el-col>
                <el-col :span="12">
                  <el-form-item label="出生日期" prop="legalBirthDate">
                    <el-date-picker v-model="form.legalBirthDate" type="date" value-format="yyyy-MM-dd" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="legalGender">
                    <el-radio-group v-model="form.legalGender">
                      <el-radio label="0">男</el-radio>
                      <el-radio label="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="证件有效期" prop="legalIdValidType">
                    <el-radio-group v-model="form.legalIdValidType">
                      <el-radio label="1">区间有效</el-radio>
                      <el-radio label="2">长期有效</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col v-if="form.legalIdValidType === '1'" :span="24">
                  <el-form-item label="有效区间" prop="legalIdValidRange">
                    <el-date-picker v-model="form.legalIdValidRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col v-if="form.legalIdValidType === '2'" :span="12">
                  <el-form-item label="起始日期" prop="legalIdValidStart">
                    <el-date-picker v-model="form.legalIdValidStart" type="date" value-format="yyyy-MM-dd" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="24"><el-form-item label="居住地址" prop="legalResidence"><el-input v-model="form.legalResidence" maxlength="255" placeholder="选填" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="对公银行账号" prop="corpBankAccount"><el-input v-model="form.corpBankAccount" maxlength="64" placeholder="选填" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="证件照正面" prop="legalIdCardFront"><image-upload v-model="form.legalIdCardFront" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="证件照反面" prop="legalIdCardBack"><image-upload v-model="form.legalIdCardBack" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="补充证照" prop="legalExtraPhoto"><image-upload v-model="form.legalExtraPhoto" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" /></el-form-item></el-col>
              </el-row>
              <p class="form-section-title">企业信息</p>
              <el-row :gutter="16">
                <el-col :span="12"><el-form-item label="企业名称" prop="companyName"><el-input v-model="form.companyName" maxlength="128" /></el-form-item></el-col>
                <el-col :span="12">
                  <el-form-item label="统一社会信用代码" prop="creditCode">
                    <el-input v-model="form.creditCode" maxlength="18" :disabled="!!form.merchantId" placeholder="选填" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="注册地区" prop="regRegionCascader">
                    <el-cascader
                      v-model="form.regRegionCascader"
                      :options="regionTree"
                      :props="regionCascaderProps"
                      clearable
                      filterable
                      placeholder="请选择省/市/区县"
                      style="width: 100%"
                      @change="handleRegRegionChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24"><el-form-item label="注册详细地址" prop="companyDetailAddress"><el-input v-model="form.companyDetailAddress" maxlength="255" placeholder="选填，街道门牌号" /></el-form-item></el-col>
                <el-col :span="24"><el-form-item label="经营范围" prop="businessScope"><el-input v-model="form.businessScope" type="textarea" :rows="2" maxlength="1000" /></el-form-item></el-col>
                <el-col :span="24">
                  <el-form-item label="营业期限" prop="licenseValidType">
                    <el-radio-group v-model="form.licenseValidType">
                      <el-radio label="1">区间有效</el-radio>
                      <el-radio label="2">长期有效</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col v-if="form.licenseValidType === '1'" :span="24">
                  <el-form-item label="营业区间" prop="licenseValidRange">
                    <el-date-picker v-model="form.licenseValidRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col v-if="form.licenseValidType === '2'" :span="12">
                  <el-form-item label="起始日期" prop="licenseValidStart">
                    <el-date-picker v-model="form.licenseValidStart" type="date" value-format="yyyy-MM-dd" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-tab-pane>

          <!-- 经营信息（仅编辑） -->
          <el-tab-pane v-if="form.merchantId" label="商户经营信息" name="biz">
            <el-row :gutter="16">
              <el-col :span="12"><el-form-item label="商户名称" prop="merchantName"><el-input v-model="form.merchantName" maxlength="128" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="客服电话" prop="servicePhone"><el-input v-model="form.servicePhone" maxlength="20" /></el-form-item></el-col>
              <el-col :span="24">
                <el-form-item label="经营地区" prop="bizRegionCascader">
                  <el-cascader
                    v-model="form.bizRegionCascader"
                    :options="regionTree"
                    :props="regionCascaderProps"
                    clearable
                    filterable
                    placeholder="请选择省/市/区县"
                    style="width: 100%"
                    @change="handleBizRegionChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24"><el-form-item label="经营详细地址" prop="bizDetailAddress"><el-input v-model="form.bizDetailAddress" maxlength="255" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="联系人姓名" prop="contactName"><el-input v-model="form.contactName" maxlength="64" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="联系人手机" prop="contactPhone"><el-input v-model="form.contactPhone" maxlength="20" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="联系人邮箱" prop="contactEmail"><el-input v-model="form.contactEmail" maxlength="128" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="开户银行" prop="bankName"><el-input v-model="form.bankName" maxlength="128" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="支行名称" prop="bankBranch"><el-input v-model="form.bankBranch" maxlength="128" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="银行账号" prop="bankAccount"><el-input v-model="form.bankAccount" maxlength="64" /></el-form-item></el-col>
              <el-col v-if="form.merchantType === '2'" :span="12">
                <el-form-item label="营业执照电子版" prop="businessLicense">
                  <image-upload v-model="form.businessLicense" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
                </el-form-item>
              </el-col>
              <el-col v-if="form.merchantType === '2'" :span="12">
                <el-form-item label="开户许可证" prop="accountPermit">
                  <image-upload v-model="form.accountPermit" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 绑定经营账号（仅新增） -->
          <el-tab-pane v-if="!form.merchantId" label="绑定经营账号" name="bind">
            <el-alert
              v-if="form.bindType === 'SYS_USER'"
              title="绑定后将使用用户名称作为登录名、用户昵称作为管理员姓名；须为 role_key=merchant 的平台账号。"
              type="info"
              :closable="false"
              show-icon
              class="bind-tip"
            />
            <el-alert
              v-if="form.bindType === 'MEMBER'"
              title="绑定后将追加 merchant 角色；登录名=会员名称、管理员姓名=会员昵称，密码复制会员账号密码。"
              type="info"
              :closable="false"
              show-icon
              class="bind-tip"
            />
            <el-form-item label="绑定类型" prop="bindType">
              <el-radio-group v-model="form.bindType" @change="handleBindTypeChange">
                <el-radio label="SYS_USER">平台管理员</el-radio>
                <el-radio label="MEMBER">会员</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.bindType === 'SYS_USER'" label="选择管理员" prop="bindUserId">
              <el-select v-model="form.bindUserId" filterable remote reserve-keyword placeholder="输入用户名/手机号搜索" :remote-method="searchAdminUser" :loading="bindSearchLoading" style="width: 100%">
                <el-option v-for="item in adminUserList" :key="item.userId" :label="formatAdminOption(item)" :value="item.userId" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.bindType === 'MEMBER'" label="选择会员" prop="bindMemberId">
              <el-select v-model="form.bindMemberId" filterable remote reserve-keyword placeholder="输入会员名称/手机号搜索" :remote-method="searchMember" :loading="bindSearchLoading" style="width: 100%">
                <el-option v-for="item in memberList" :key="item.memberId" :label="formatMemberOption(item)" :value="item.memberId" />
              </el-select>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情抽屉 -->
    <merchant-detail :visible.sync="detailOpen" :merchant-id="currentMerchantId" @success="getList" />
  </div>
</template>

<script>
import { listMerchant, getMerchant, addMerchant, updateMerchant, delMerchant, deleteMerchantCheck, adminUserOptions, memberOptions } from "@/api/agri/merchant"
import regionCascaderMixin from "@/mixins/regionCascader"
import MerchantDetail from "./detail"

const REGION_CASCADER_FIELDS = [
  { codeKey: "regRegionCode", cascaderKey: "regRegionCascader" },
  { codeKey: "bizRegionCode", cascaderKey: "bizRegionCascader" }
]

export default {
  name: "AgriMerchant",
  components: { MerchantDetail },
  mixins: [regionCascaderMixin],
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      merchantList: [],
      title: "",
      open: false,
      detailOpen: false,
      currentMerchantId: null,
      activeTab: "subject",
      bindSearchLoading: false,
      adminUserList: [],
      memberList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merchantName: undefined,
        certStatus: undefined
      },
      form: {}
    }
  },
  computed: {
    /** 表单校验：新增个人仅姓名必填；新增企业仅法人姓名+企业名称必填；绑定仅新增时校验 */
    formRules() {
      const rules = {
        merchantType: [{ required: true, message: "请选择主体类型", trigger: "change" }]
      }
      const isAdd = !this.form.merchantId
      if (this.form.merchantType === "1") {
        rules.personName = [{ required: true, message: "请输入姓名", trigger: "blur" }]
      } else {
        rules.legalName = [{ required: true, message: "请输入法人姓名", trigger: "blur" }]
        rules.companyName = [{ required: true, message: "请输入企业名称", trigger: "blur" }]
      }
      if (isAdd) {
        rules.bindType = [{ required: true, message: "请选择绑定类型", trigger: "change" }]
        if (this.form.bindType === "SYS_USER") {
          rules.bindUserId = [{ required: true, message: "请选择平台管理员", trigger: "change" }]
        } else if (this.form.bindType === "MEMBER") {
          rules.bindMemberId = [{ required: true, message: "请选择会员", trigger: "change" }]
        }
      }
      return rules
    }
  },
  created() {
    this.getList()
    this.loadRegionTree()
  },
  methods: {
    /** 查询商户列表 */
    getList() {
      this.loading = true
      listMerchant(this.queryParams).then(response => {
        this.merchantList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    certStatusLabel(status) {
      const map = { "0": "正常", "1": "已冻结", "2": "已注销" }
      return map[status] || "—"
    },
    certStatusTag(status) {
      const map = { "0": "success", "1": "warning", "2": "danger" }
      return map[status] || "info"
    },
    /** 重置表单 */
    reset() {
      this.form = {
        merchantId: undefined,
        merchantType: "1",
        personName: undefined,
        idCardType: "1",
        idCardNo: undefined,
        birthDate: undefined,
        gender: "0",
        idValidType: "1",
        idValidRange: [],
        idValidStart: undefined,
        idValidEnd: undefined,
        residenceAddress: undefined,
        idCardFront: undefined,
        idCardBack: undefined,
        legalName: undefined,
        legalIdCardType: "1",
        legalIdCardNo: undefined,
        legalBirthDate: undefined,
        legalGender: "0",
        legalIdValidType: "1",
        legalIdValidRange: [],
        legalIdValidStart: undefined,
        legalIdValidEnd: undefined,
        legalResidence: undefined,
        legalIdCardFront: undefined,
        legalIdCardBack: undefined,
        legalExtraPhoto: undefined,
        corpBankAccount: undefined,
        companyName: undefined,
        creditCode: undefined,
        regRegionCode: undefined,
        regRegionName: undefined,
        regRegionCascader: [],
        regAddress: undefined,
        companyDetailAddress: undefined,
        businessScope: undefined,
        licenseValidType: "1",
        licenseValidRange: [],
        licenseValidStart: undefined,
        licenseValidEnd: undefined,
        bindType: "SYS_USER",
        bindUserId: undefined,
        bindMemberId: undefined,
        bizRegionCascader: []
      }
      this.activeTab = "subject"
      this.adminUserList = []
      this.memberList = []
      this.resetForm("form")
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.reset()
      this.loadRegionTree()
      this.open = true
      this.title = "添加商户"
    },
    /** 打开编辑并组装日期区间、省市区回显 */
    handleUpdate(row) {
      this.reset()
      this.loadRegionTree().then(() => {
        return getMerchant(row.merchantId)
      }).then(response => {
        const data = response.data || {}
        this.form = { ...data, regRegionCascader: [], bizRegionCascader: [] }
        if (data.idValidType === "1" && data.idValidStart && data.idValidEnd) {
          this.form.idValidRange = [data.idValidStart, data.idValidEnd]
        }
        if (data.legalIdValidType === "1" && data.legalIdValidStart && data.legalIdValidEnd) {
          this.form.legalIdValidRange = [data.legalIdValidStart, data.legalIdValidEnd]
        }
        if (data.licenseValidType === "1" && data.licenseValidStart && data.licenseValidEnd) {
          this.form.licenseValidRange = [data.licenseValidStart, data.licenseValidEnd]
        }
        this.syncRegionCascaderFromForm(REGION_CASCADER_FIELDS)
        this.activeTab = "subject"
        this.open = true
        this.title = "编辑商户"
      })
    },
    handleDetail(row) {
      this.currentMerchantId = row.merchantId
      this.detailOpen = true
    },
    handleTypeChange() {
      this.activeTab = "subject"
    },
    handleBindTypeChange() {
      this.form.bindUserId = undefined
      this.form.bindMemberId = undefined
      this.adminUserList = []
      this.memberList = []
    },
    /** 企业注册地区变更：写入 regRegionCode / regRegionName */
    handleRegRegionChange(codes) {
      this.applyRegionSelection(codes, "reg")
    },
    /** 经营地区变更：写入 bizRegionCode / bizRegionName */
    handleBizRegionChange(codes) {
      this.applyRegionSelection(codes, "biz")
    },
    formatAdminOption(item) {
      const parts = [item.nickName || item.userName, item.userName]
      if (item.phonenumber) {
        parts.push(item.phonenumber)
      }
      return parts.filter(Boolean).join(" / ")
    },
    /** 会员下拉展示：会员名称 / 昵称 / 脱敏手机 */
    formatMemberOption(item) {
      const parts = [item.memberCode, item.nickName].filter(Boolean)
      if (item.mobile) {
        parts.push(item.mobile)
      }
      return parts.join(" / ")
    },
    /** 远程搜索平台管理员 */
    searchAdminUser(keyword) {
      if (!keyword) {
        this.adminUserList = []
        return
      }
      this.bindSearchLoading = true
      adminUserOptions(keyword).then(response => {
        this.adminUserList = response.data || []
        this.bindSearchLoading = false
      }).catch(() => {
        this.bindSearchLoading = false
      })
    },
    /** 远程搜索会员 */
    searchMember(keyword) {
      if (!keyword) {
        this.memberList = []
        return
      }
      this.bindSearchLoading = true
      memberOptions(keyword).then(response => {
        this.memberList = response.data || []
        this.bindSearchLoading = false
      }).catch(() => {
        this.bindSearchLoading = false
      })
    },
    /** 提交前拆分日期区间字段 */
    buildSubmitPayload() {
      const payload = { ...this.form }
      if (payload.idValidRange && payload.idValidRange.length === 2) {
        payload.idValidStart = payload.idValidRange[0]
        payload.idValidEnd = payload.idValidRange[1]
      }
      if (payload.legalIdValidRange && payload.legalIdValidRange.length === 2) {
        payload.legalIdValidStart = payload.legalIdValidRange[0]
        payload.legalIdValidEnd = payload.legalIdValidRange[1]
      }
      if (payload.licenseValidRange && payload.licenseValidRange.length === 2) {
        payload.licenseValidStart = payload.licenseValidRange[0]
        payload.licenseValidEnd = payload.licenseValidRange[1]
      }
      delete payload.idValidRange
      delete payload.legalIdValidRange
      delete payload.licenseValidRange
      delete payload.regRegionCascader
      delete payload.bizRegionCascader
      // 新增时不传绑定无关字段；会员绑定不传 sysUserInitPassword（后端忽略）
      if (!payload.merchantId) {
        delete payload.sysUserInitPassword
        if (payload.bindType === "SYS_USER") {
          delete payload.bindMemberId
        } else {
          delete payload.bindUserId
        }
      } else {
        delete payload.bindType
        delete payload.bindUserId
        delete payload.bindMemberId
      }
      return payload
    },
    /** 提交添加或编辑 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = this.buildSubmitPayload()
        const submitFn = payload.merchantId ? updateMerchant : addMerchant
        submitFn(payload).then(response => {
          let msg = payload.merchantId ? "修改成功" : "新增成功"
          if (response.data && response.data.bizCompleteChanged) {
            msg = "保存成功，已可开设店铺"
          }
          if (!payload.merchantId) {
            msg = "请尽快在编辑中完善商户经营信息后再开设店铺"
          }
          if (response.data && response.data.warnExpired) {
            this.$modal.msgWarning("证件或营业期限已过期，请注意风险")
          }
          this.$modal.msgSuccess(msg)
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除商户（先预检） */
    handleDelete(row) {
      deleteMerchantCheck(row.merchantId).then(response => {
        const data = response.data || {}
        if (data.canDelete === false) {
          const reasons = (data.reasons || []).join("；")
          this.$modal.msgWarning(reasons || "当前不可删除")
          return
        }
        this.$modal.confirm("删除后不可恢复，是否继续？").then(() => {
          return delMerchant(row.merchantId)
        }).then(() => {
          this.$modal.msgSuccess("删除成功")
          this.getList()
        }).catch(() => {})
      })
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.form-section-title {
  font-size: 13px;
  color: #606266;
  margin: 8px 0 12px;
  padding-left: 8px;
  border-left: 2px solid #DCDFE6;
}
.bind-tip {
  margin-bottom: 16px;
}
</style>
