<template>
  <div class="app-container">
    <!-- 店铺资料 -->
    <el-card shadow="never" class="profile-card" v-loading="profileLoading">
      <div slot="header" class="card-header">
        <span class="card-title">店铺资料</span>
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleEdit"
          v-hasPermi="['agri:seller:shop:edit']"
        >编辑</el-button>
      </div>
      <el-descriptions :column="2" border size="medium">
        <el-descriptions-item label="店铺头像">
          <image-preview v-if="profile.shopAvatar" :src="profile.shopAvatar" :width="64" :height="64" />
          <span v-else>—</span>
        </el-descriptions-item>
        <el-descriptions-item label="店铺名称">{{ displayText(profile.shopName) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ profile.createTime ? parseTime(profile.createTime) : '—' }}</el-descriptions-item>
        <el-descriptions-item label="店铺状态">
          <el-tag v-if="profile.shopStatus === '0'" type="success" size="small">开业</el-tag>
          <el-tag v-else-if="profile.shopStatus === '1'" type="info" size="small">停业</el-tag>
          <span v-else>—</span>
        </el-descriptions-item>
        <el-descriptions-item label="所属商户">{{ displayText(profile.merchantName) }}</el-descriptions-item>
        <el-descriptions-item label="客服电话">{{ displayText(profile.shopPhone) }}</el-descriptions-item>
        <el-descriptions-item label="负责人姓名">{{ displayText(profile.contactName) }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ displayText(profile.contactPhone) }}</el-descriptions-item>
        <el-descriptions-item label="店铺简介" :span="2">{{ displayText(profile.shopDesc) }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <br/>

    <!-- 员工概览 -->
    <el-card shadow="never" class="stats-card" v-loading="statsLoading">
      <div slot="header" class="card-header">
        <span class="card-title">员工概览</span>
        <el-button
          type="primary"
          plain
          icon="el-icon-user"
          size="mini"
          @click="goEmployeeManage"
          v-hasPermi="['agri:seller:employee:list']"
        >前往员工管理</el-button>
      </div>
      <el-row :gutter="24" class="stats-row">
        <el-col :xs="12" :sm="6">
          <div class="stat-block">
            <div class="stat-value">{{ employeeStats.totalCount != null ? employeeStats.totalCount : '—' }}</div>
            <div class="stat-label">已有员工数</div>
            <div class="stat-tip">含正常与停用，不含经营账号</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-block">
            <div class="stat-value">{{ employeeStats.disabledCount != null ? employeeStats.disabledCount : '—' }}</div>
            <div class="stat-label">停用员工数</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-block">
            <div class="stat-value">
              <template v-if="employeeStats.usedCount != null && employeeStats.maxCount != null">
                {{ employeeStats.usedCount }} / {{ employeeStats.maxCount }}
              </template>
              <span v-else>—</span>
            </div>
            <div class="stat-label">商户员工配额</div>
            <div class="stat-tip">已用 / 平台上限（各店合计）</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-block stat-block-muted">
            <div class="stat-label">配额说明</div>
            <div class="stat-desc">子管理员上限由平台「店铺设置」配置，本页只读展示；明细维护请前往员工管理。</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 编辑店铺资料弹窗 -->
    <el-dialog title="编辑店铺资料" :visible.sync="open" width="560px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" maxlength="128" show-word-limit />
        </el-form-item>
        <el-form-item label="店铺头像" prop="shopAvatar">
          <image-upload v-model="form.shopAvatar" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
        </el-form-item>
        <el-form-item label="店铺简介" prop="shopDesc">
          <el-input v-model="form.shopDesc" type="textarea" :rows="3" placeholder="选填" maxlength="1000" show-word-limit />
        </el-form-item>
        <el-form-item label="客服电话" prop="shopPhone">
          <el-input v-model="form.shopPhone" placeholder="选填，手机或固话" maxlength="20" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSellerShopProfile, updateSellerShopProfile, getSellerShopEmployeeStats } from "@/api/agri/seller/shop"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

export default {
  name: "AgriSellerShop",
  data() {
    /** 客服电话：选填；有值时校验格式（与平台店铺管理一致） */
    const validateShopPhone = (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback()
        return
      }
      if (!/^[0-9\-+()\s]{5,20}$/.test(String(value).trim())) {
        callback(new Error("请输入正确的电话格式"))
        return
      }
      callback()
    }
    return {
      profileLoading: false,
      statsLoading: false,
      open: false,
      profile: {},
      employeeStats: {},
      form: {},
      rules: {
        shopName: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
        shopAvatar: [{ required: true, message: "请上传店铺头像", trigger: "change" }],
        shopDesc: [{ max: 1000, message: "店铺简介过长", trigger: "blur" }],
        shopPhone: [{ validator: validateShopPhone, trigger: "blur" }]
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /** 初始化：加载店铺上下文后并行拉资料与员工统计 */
    initPage() {
      this.loadShopContext().then(() => {
        this.loadPageData()
      }).catch(() => {
        this.loadPageData()
      })
    },
    /** 加载商家端当前店铺上下文 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 并行加载店铺资料与员工概览 */
    loadPageData() {
      this.loadProfile()
      this.loadEmployeeStats()
    },
    /** 查询当前店铺资料 */
    loadProfile() {
      this.profileLoading = true
      getSellerShopProfile().then(response => {
        this.profile = response.data || {}
        this.profileLoading = false
      }).catch(() => {
        this.profileLoading = false
      })
    },
    /** 查询员工概览 */
    loadEmployeeStats() {
      this.statsLoading = true
      getSellerShopEmployeeStats().then(response => {
        this.employeeStats = response.data || {}
        this.statsLoading = false
      }).catch(() => {
        this.statsLoading = false
      })
    },
    /** 空值展示占位 */
    displayText(value) {
      if (value === null || value === undefined || String(value).trim() === "") {
        return "—"
      }
      return value
    },
    /** 打开编辑弹窗 */
    handleEdit() {
      this.reset()
      this.form = {
        shopName: this.profile.shopName || "",
        shopAvatar: this.profile.shopAvatar || "",
        shopDesc: this.profile.shopDesc || "",
        shopPhone: this.profile.shopPhone || ""
      }
      this.open = true
    },
    /** 提交编辑 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          shopName: this.form.shopName.trim(),
          shopAvatar: this.form.shopAvatar,
          shopDesc: this.form.shopDesc ? this.form.shopDesc.trim() : undefined,
          shopPhone: this.form.shopPhone && String(this.form.shopPhone).trim()
            ? this.form.shopPhone.trim()
            : undefined
        }
        updateSellerShopProfile(payload).then(() => {
          this.$modal.msgSuccess("保存成功")
          this.open = false
          this.loadProfile()
        })
      })
    },
    /** 关闭编辑弹窗 */
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        shopName: undefined,
        shopAvatar: undefined,
        shopDesc: undefined,
        shopPhone: undefined
      }
      this.resetForm("form")
    },
    /** 跳转员工管理（同一当前店铺上下文） */
    goEmployeeManage() {
      this.$router.push({ path: "/account/seller/employee" })
    }
  }
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-weight: 600;
  font-size: 15px;
}
.stats-row {
  margin-top: 4px;
}
.stat-block {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 120px;
  background: #fafafa;
}
.stat-block-muted {
  background: #fff;
}
.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
  margin-bottom: 8px;
}
.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}
.stat-tip,
.stat-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
</style>
