<template>
  <el-drawer
    :title="'商户详情 · ' + (detail.unitName || detail.merchantName || '')"
    :visible.sync="localVisible"
    direction="rtl"
    size="72%"
    append-to-body
    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="商户类型">{{ merchantTypeLabel(detail.merchantType) }}</el-descriptions-item>
        <el-descriptions-item label="商户所属单位">{{ detail.unitName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="商户名称">{{ detail.merchantName || '待完善' }}</el-descriptions-item>
        <el-descriptions-item label="认证状态">
          <el-tag size="small" :type="certStatusTag(detail.certStatus)">{{ certStatusLabel(detail.certStatus) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="认证时间">{{ parseTime(detail.certTime) || '—' }}</el-descriptions-item>
        <el-descriptions-item label="已绑定店铺">{{ detail.shopCount != null ? detail.shopCount : '—' }}</el-descriptions-item>
        <el-descriptions-item label="经营信息完整">
          <el-tag size="small" :type="detail.bizComplete === '1' ? 'success' : 'warning'">{{ detail.bizComplete === '1' ? '已完整' : '待完善' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="detail.bizComplete !== '1' && detail.pendingBizFields && detail.pendingBizFields.length" label="待完善项" :span="2">
          {{ detail.pendingBizFields.join('、') }}
        </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="姓名">{{ detail.personName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件类型">{{ idCardTypeLabel(detail.idCardType) }}</el-descriptions-item>
          <el-descriptions-item label="证件号码">{{ detail.idCardNo || '—' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ detail.birthDate || '—' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ genderLabel(detail.gender) }}</el-descriptions-item>
          <el-descriptions-item label="证件有效期" :span="2">{{ validPeriodText(detail.idValidType, detail.idValidStart, detail.idValidEnd) }}</el-descriptions-item>
          <el-descriptions-item label="居住地址" :span="2">{{ detail.residenceAddress || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件照正面">
            <image-preview v-if="detail.idCardFront" :src="detail.idCardFront" :width="80" :height="50" />
          </el-descriptions-item>
          <el-descriptions-item label="证件照反面">
            <image-preview v-if="detail.idCardBack" :src="detail.idCardBack" :width="80" :height="50" />
          </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="姓名">{{ detail.legalName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件类型">{{ idCardTypeLabel(detail.legalIdCardType) }}</el-descriptions-item>
          <el-descriptions-item label="证件号码">{{ detail.legalIdCardNo || '—' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ detail.legalBirthDate || '—' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ genderLabel(detail.legalGender) }}</el-descriptions-item>
          <el-descriptions-item label="证件有效期" :span="2">{{ validPeriodText(detail.legalIdValidType, detail.legalIdValidStart, detail.legalIdValidEnd) }}</el-descriptions-item>
          <el-descriptions-item label="居住地址" :span="2">{{ detail.legalResidence || '—' }}</el-descriptions-item>
          <el-descriptions-item label="对公银行账号">{{ detail.corpBankAccount || '—' }}</el-descriptions-item>
          <el-descriptions-item label="证件照正面">
            <image-preview v-if="detail.legalIdCardFront" :src="detail.legalIdCardFront" :width="80" :height="50" />
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="证件照反面">
            <image-preview v-if="detail.legalIdCardBack" :src="detail.legalIdCardBack" :width="80" :height="50" />
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="补充证照">
            <image-preview v-if="detail.legalExtraPhoto" :src="detail.legalExtraPhoto" :width="80" :height="50" />
            <span v-else>—</span>
          </el-descriptions-item>
        </el-descriptions>
        <p class="sub-title">企业信息</p>
        <el-descriptions :column="2" border size="small" class="mb16">
          <el-descriptions-item label="企业名称">{{ detail.companyName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="统一社会信用代码">{{ detail.creditCode || '—' }}</el-descriptions-item>
          <el-descriptions-item label="注册地区">{{ detail.regRegionName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="注册地区编码">{{ detail.regRegionCode || '—' }}</el-descriptions-item>
          <el-descriptions-item label="注册详细地址">{{ detail.companyDetailAddress || '—' }}</el-descriptions-item>
          <el-descriptions-item label="经营范围" :span="2">{{ detail.businessScope || '—' }}</el-descriptions-item>
          <el-descriptions-item label="营业期限" :span="2">{{ validPeriodText(detail.licenseValidType, detail.licenseValidStart, detail.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="商户名称">{{ detail.merchantName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="客服电话">{{ detail.servicePhone || '—' }}</el-descriptions-item>
        <el-descriptions-item label="经营地址">{{ detail.bizRegionName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="经营地区编码">{{ detail.bizRegionCode || '—' }}</el-descriptions-item>
        <el-descriptions-item label="经营详细地址" :span="2">{{ detail.bizDetailAddress || '—' }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ detail.contactName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="联系人手机">{{ detail.contactPhone || '—' }}</el-descriptions-item>
        <el-descriptions-item label="联系人邮箱">{{ detail.contactEmail || '—' }}</el-descriptions-item>
        <el-descriptions-item label="开户银行">{{ detail.bankName || '—' }}</el-descriptions-item>
        <el-descriptions-item label="支行名称">{{ detail.bankBranch || '—' }}</el-descriptions-item>
        <el-descriptions-item label="银行账号">{{ detail.bankAccount || '—' }}</el-descriptions-item>
        <el-descriptions-item v-if="detail.merchantType === '2'" label="营业执照">
          <image-preview v-if="detail.businessLicense" :src="detail.businessLicense" :width="80" :height="50" />
          <span v-else>—</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="detail.merchantType === '2'" label="开户许可证">
          <image-preview v-if="detail.accountPermit" :src="detail.accountPermit" :width="80" :height="50" />
          <span v-else>—</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 关联店铺 -->
      <h4 class="section-header">关联店铺</h4>
      <el-table v-if="detail.shops && detail.shops.length" border size="small" :data="detail.shops" class="mb16">
        <el-table-column label="店铺名称" prop="shopName" />
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.shopStatus === '0' ? 'success' : 'info'">{{ scope.row.shopStatus === '0' ? '开业' : '停业' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-button v-if="detail.shopListUrl" type="text" icon="el-icon-link" @click="goShopList">查看全部店铺</el-button>

      <!-- 认证状态调整（仅详情页可改） -->
      <div v-if="detail.allowedCertStatuses && detail.allowedCertStatuses.length" class="action-bar">
        <span class="action-label">调整认证状态：</span>
        <el-button
          v-for="item in detail.allowedCertStatuses"
          :key="item.value"
          size="small"
          :type="item.value === '0' ? 'success' : item.value === '1' ? 'warning' : 'danger'"
          plain
          @click="handleCertChange(item)"
          v-hasPermi="['agri:merchant:cert']"
        >{{ item.label }}</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getMerchant, updateMerchantCertStatus } from "@/api/agri/merchant"

export default {
  name: "MerchantDetail",
  props: {
    visible: { type: Boolean, default: false },
    merchantId: { type: [Number, String], default: null }
  },
  data() {
    return {
      localVisible: false,
      loading: false,
      detail: {}
    }
  },
  watch: {
    visible(val) {
      this.localVisible = val
      if (val && this.merchantId) {
        this.loadDetail()
      }
    },
    localVisible(val) {
      this.$emit("update:visible", val)
    }
  },
  methods: {
    /** 加载商户详情 */
    loadDetail() {
      this.loading = true
      getMerchant(this.merchantId).then(response => {
        this.detail = response.data || {}
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    merchantTypeLabel(type) {
      return type === "2" ? "企业" : type === "1" ? "个人" : "—"
    },
    certStatusLabel(status) {
      const map = { "0": "正常", "1": "已冻结", "2": "已注销" }
      return map[status] || "—"
    },
    certStatusTag(status) {
      const map = { "0": "success", "1": "warning", "2": "danger" }
      return map[status] || "info"
    },
    genderLabel(gender) {
      const map = { "0": "男", "1": "女", "2": "未知" }
      return map[gender] || "—"
    },
    idCardTypeLabel(type) {
      const map = { "1": "大陆身份证", "2": "来往内地通行证" }
      return map[type] || "—"
    },
    validPeriodText(type, start, end) {
      if (type === "2") {
        return "长期有效" + (start ? "（自 " + start + "）" : "")
      }
      if (start && end) {
        return start + " 至 " + end
      }
      return "—"
    },
    /** 跳转店铺列表 */
    goShopList() {
      const name = this.detail.merchantName || this.detail.unitName
      this.$router.push({ path: "/org/shop", query: { merchantName: name } })
    },
    /** 修改认证状态（两步确认） */
    handleCertChange(item) {
      const msg = item.confirmMessage || ("确认调整为「" + item.label + "」？")
      this.$modal.confirm(msg).then(() => {
        return updateMerchantCertStatus(this.merchantId, {
          certStatus: item.value,
          confirm: true
        })
      }).then(() => {
        this.$modal.msgSuccess("认证状态已更新")
        this.loadDetail()
        this.$emit("success")
      }).catch(() => {})
    }
  }
}
</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;
}
.action-bar {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}
.action-label {
  margin-right: 8px;
  color: #606266;
  font-size: 14px;
}
</style>
