<template>
  <el-drawer
    :title="drawerTitle"
    :visible.sync="localVisible"
    direction="rtl"
    size="72%"
    append-to-body
    :before-close="handleClose"
    custom-class="detail-drawer"
  >
    <div v-loading="loading" class="drawer-content">
      <!-- 基础信息 -->
      <h4 class="section-header">基础信息</h4>
      <el-descriptions :column="2" border size="small" class="mb16">
        <el-descriptions-item label="申请编号">{{ detail.applyNo || '—' }}</el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag size="small" :type="applyStatusTag(detail.applyStatus)">{{ applyStatusLabel(detail.applyStatus) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="主体类型">{{ merchantTypeLabel(detail.merchantType) }}</el-descriptions-item>
        <el-descriptions-item label="申请会员名称">{{ detail.memberCode || '—' }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ parseTime(detail.applyTime) || '—' }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ detail.auditBy || '—' }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ parseTime(detail.auditTime) || '—' }}</el-descriptions-item>
        <el-descriptions-item v-if="detail.applyStatus === '2'" label="拒绝原因" :span="2">
          <span class="reject-reason">{{ detail.rejectReason || '—' }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 主体资质 -->
      <h4 class="section-header">主体资质</h4>
      <template v-if="detail.merchantType === '1'">
        <el-descriptions :column="2" border size="small" class="mb16">
          <el-descriptions-item label="姓名">{{ subject.personName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件号码">{{ subject.idCardNo || '—' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ subject.birthDate || '—' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ genderLabel(subject.gender) }}</el-descriptions-item>
          <el-descriptions-item label="证件有效期" :span="2">{{ validPeriodText(subject.idValidType, subject.idValidStart, subject.idValidEnd) }}</el-descriptions-item>
          <el-descriptions-item label="居住地址" :span="2">{{ subject.residenceAddress || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件照正面">
            <image-preview v-if="subject.idCardFront" :src="subject.idCardFront" :width="80" :height="50" />
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="证件照反面">
            <image-preview v-if="subject.idCardBack" :src="subject.idCardBack" :width="80" :height="50" />
            <span v-else>—</span>
          </el-descriptions-item>
        </el-descriptions>
      </template>
      <template v-else>
        <p class="sub-title">法定代表人信息</p>
        <el-descriptions :column="2" border size="small" class="mb16">
          <el-descriptions-item label="姓名">{{ subject.legalName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件号码">{{ subject.legalIdCardNo || '—' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ subject.legalBirthDate || '—' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ genderLabel(subject.legalGender) }}</el-descriptions-item>
          <el-descriptions-item label="证件有效期" :span="2">{{ validPeriodText(subject.legalIdValidType, subject.legalIdValidStart, subject.legalIdValidEnd) }}</el-descriptions-item>
          <el-descriptions-item label="居住地址" :span="2">{{ subject.legalResidence || '—' }}</el-descriptions-item>
        </el-descriptions>
        <p class="sub-title">企业信息</p>
        <el-descriptions :column="2" border size="small" class="mb16">
          <el-descriptions-item label="企业名称">{{ subject.companyName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="统一社会信用代码">{{ subject.creditCode || '—' }}</el-descriptions-item>
          <el-descriptions-item label="注册地址">{{ subject.regAddress || '—' }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ subject.companyDetailAddress || '—' }}</el-descriptions-item>
          <el-descriptions-item label="经营范围" :span="2">{{ subject.businessScope || '—' }}</el-descriptions-item>
          <el-descriptions-item label="营业期限" :span="2">{{ validPeriodText(subject.licenseValidType, subject.licenseValidStart, subject.licenseValidEnd) }}</el-descriptions-item>
        </el-descriptions>
      </template>

      <!-- 商户经营信息 -->
      <h4 class="section-header">商户经营信息</h4>
      <el-descriptions :column="2" border size="small" class="mb16">
        <el-descriptions-item label="商户名称">{{ biz.merchantName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="客服电话">{{ biz.servicePhone || '—' }}</el-descriptions-item>
        <el-descriptions-item label="经营地址">{{ biz.bizRegionName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{ biz.bizDetailAddress || '—' }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ biz.contactName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="联系人手机">{{ biz.contactPhone || '—' }}</el-descriptions-item>
        <el-descriptions-item label="联系人邮箱">{{ biz.contactEmail || '—' }}</el-descriptions-item>
        <el-descriptions-item label="开户银行">{{ biz.bankName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="支行名称">{{ biz.bankBranch || '—' }}</el-descriptions-item>
        <el-descriptions-item label="银行账号">{{ biz.bankAccount || '—' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 店铺信息 -->
      <h4 class="section-header">首家店铺信息</h4>
      <el-descriptions :column="2" border size="small" class="mb16">
        <el-descriptions-item label="店铺名称">{{ shop.shopName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="商家电话">{{ shop.shopPhone || '—' }}</el-descriptions-item>
        <el-descriptions-item label="店铺头像">
          <image-preview v-if="shop.shopAvatar" :src="shop.shopAvatar" :width="60" :height="60" />
          <span v-else>—</span>
        </el-descriptions-item>
        <el-descriptions-item label="店铺描述">{{ shop.shopDesc || '—' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 审核操作区（仅待审核） -->
      <div v-if="detail.canApprove || detail.canReject" class="action-bar">
        <el-button type="success" @click="handleApprove" v-hasPermi="['agri:merchantEntryApply:audit']">审核通过</el-button>
        <el-button type="danger" plain @click="rejectOpen = true" v-hasPermi="['agri:merchantEntryApply:audit']">审核驳回</el-button>
      </div>
    </div>

    <!-- 驳回原因弹窗 -->
    <el-dialog title="审核驳回" :visible.sync="rejectOpen" width="480px" append-to-body>
      <el-form ref="rejectForm" :model="rejectForm" :rules="rejectRules" label-width="90px">
        <el-form-item label="拒绝原因" prop="rejectReason">
          <el-input v-model="rejectForm.rejectReason" type="textarea" :rows="4" maxlength="200" show-word-limit placeholder="请填写驳回原因，申请人可见" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitReject">确 定</el-button>
        <el-button @click="rejectOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-drawer>
</template>

<script>
import { getMerchantEntryApply, approveMerchantEntryApply, rejectMerchantEntryApply } from "@/api/agri/merchantEntryApply"

export default {
  name: "MerchantEntryApplyDetail",
  props: {
    visible: { type: Boolean, default: false },
    applyId: { type: [Number, String], default: null }
  },
  data() {
    return {
      localVisible: false,
      loading: false,
      detail: {},
      subject: {},
      biz: {},
      shop: {},
      rejectOpen: false,
      rejectForm: { rejectReason: "" },
      rejectRules: {
        rejectReason: [{ required: true, message: "请填写拒绝原因", trigger: "blur" }]
      }
    }
  },
  computed: {
    drawerTitle() {
      return "入驻申请详情" + (this.detail.applyNo ? " · " + this.detail.applyNo : "")
    }
  },
  watch: {
    visible(val) {
      this.localVisible = val
      if (val && this.applyId) {
        this.loadDetail()
      }
    },
    localVisible(val) {
      this.$emit("update:visible", val)
      if (!val) {
        this.detail = {}
        this.subject = {}
        this.biz = {}
        this.shop = {}
      }
    }
  },
  methods: {
    /** 加载申请详情 */
    loadDetail() {
      this.loading = true
      getMerchantEntryApply(this.applyId).then(response => {
        const data = response.data || {}
        this.detail = data
        this.subject = data.subject || data.formJson?.subject || {}
        this.biz = data.biz || data.formJson?.biz || {}
        this.shop = data.shop || data.formJson?.shop || {}
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 申请状态文案 */
    applyStatusLabel(status) {
      const map = { "0": "待审核", "1": "审核通过", "2": "审核未通过" }
      return map[status] || "—"
    },
    /** 申请状态标签颜色 */
    applyStatusTag(status) {
      const map = { "0": "warning", "1": "success", "2": "danger" }
      return map[status] || "info"
    },
    /** 商户类型文案 */
    merchantTypeLabel(type) {
      return type === "2" ? "企业" : type === "1" ? "个人" : "—"
    },
    /** 性别文案 */
    genderLabel(gender) {
      const map = { "0": "男", "1": "女", "2": "未知" }
      return map[gender] || "—"
    },
    /** 证件/营业期限展示 */
    validPeriodText(type, start, end) {
      if (type === "2") {
        return "长期有效" + (start ? "（自 " + start + "）" : "")
      }
      if (start && end) {
        return start + " 至 " + end
      }
      return "—"
    },
    /** 关闭抽屉 */
    handleClose(done) {
      done()
    },
    /** 审核通过（两步确认） */
    handleApprove() {
      this.$modal.confirm("确认审核通过？通过后将自动创建商户与首家店铺。").then(() => {
        return approveMerchantEntryApply(this.applyId, { confirmed: true })
      }).then(response => {
        this.$modal.msgSuccess("审核通过")
        this.localVisible = false
        this.$emit("success", response.data)
      }).catch(() => {})
    },
    /** 提交驳回 */
    submitReject() {
      this.$refs["rejectForm"].validate(valid => {
        if (!valid) {
          return
        }
        rejectMerchantEntryApply({
          applyId: this.applyId,
          rejectReason: this.rejectForm.rejectReason
        }).then(() => {
          this.$modal.msgSuccess("已驳回")
          this.rejectOpen = false
          this.localVisible = false
          this.$emit("success")
        })
      })
    }
  }
}
</script>

<style scoped>
.drawer-content {
  padding: 0 20px 20px;
}
.section-header {
  margin: 16px 0 10px;
  font-size: 15px;
  color: #303133;
  border-left: 3px solid #409EFF;
  padding-left: 8px;
}
.sub-title {
  font-size: 13px;
  color: #606266;
  margin: 8px 0;
}
.mb16 {
  margin-bottom: 16px;
}
.reject-reason {
  color: #F56C6C;
}
.action-bar {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}
</style>
