<template>
  <div class="panel">
    <h2 class="panel-title">新增店铺</h2>
    <div class="panel-body">
      <div class="row">
        <label class="label required">店铺名称</label>
        <el-input v-model="form.name" placeholder="请输入店铺名称" :maxlength="30" show-word-limit />
      </div>
      <!-- <div class="row">
        <label class="label">主营类目</label>
        <el-input v-model="form.category" placeholder="请输入主营类目" />
      </div> -->
      <div class="row">
        <label class="label">店铺描述</label>
        <div class="textarea-wrapper">
          <el-input
            type="textarea"
            v-model="form.description"
            :rows="4"
            :maxlength="300"
            placeholder="请输入店铺描述"
            show-word-limit
            @input="handleDescriptionInput"
          />
          <!-- <div class="char-count" :class="{ 'char-limit': form.description.length >= 300 }">
            {{ form.description.length }}/300
          </div> -->
        </div>
      </div>
      <div class="row">
        <label class="label required">手续费比例</label>
        <el-input
          v-model="form.feeRate"
          placeholder="比例区间 0.01 - 0.1 之间，最多6位小数"
          @input="handleFeeRateInput"
        />
      </div>
      <div class="row" style="margin-top:-6px;">
        <div></div>
        <div style="color:#909399; font-size:12px; text-align:left;">
          为提升您的店铺曝光，您可为平台交易设置手续费比例，该手续费为商家向平台支付的交易佣金,手续费比例将作为影响店铺排名的关键因素,该比例越高，您的店铺排名就越靠前。
        </div>
      </div>
      <div class="row" style="margin-top:50px;">
        <div class="actions-center">
          <el-button class="btn-wide" type="primary" @click="handleCreate">创建店铺</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAddShop } from "@/api/shops";
export default {
  data() {
    return {
      form: { name: "", description: "", image: "", feeRate: "" },
    };
  },
  mounted() {},
  methods: {
    // 简单的emoji检测：覆盖常见表情平面与符号范围
    hasEmoji(str) {
      if (!str || typeof str !== 'string') return false
      const emojiRegex = /[\u{1F300}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u2600-\u27BF]/u
      return emojiRegex.test(str)
    },
    handleFeeRateInput(value) {
      // 仅允许数字与一个小数点，限制小数位最多6位；保留尾随小数点，便于继续输入
      let v = String(value ?? this.form.feeRate ?? '')
      // 过滤非法字符
      v = v.replace(/[^0-9.]/g, '')
      // 保留第一个小数点，其余移除
      const firstDot = v.indexOf('.')
      if (firstDot !== -1) {
        v = v.slice(0, firstDot + 1) + v.slice(firstDot + 1).replace(/\./g, '')
      }
      const endsWithDot = v.endsWith('.')
      const parts = v.split('.')
      let intPart = parts[0] || ''
      let decPart = parts[1] || ''
      // 小数位最多6位
      if (decPart.length > 6) decPart = decPart.slice(0, 6)
      // 规整前导0（范围本就小于1）
      if (intPart && intPart !== '0') intPart = String(Number(intPart))
      // 允许输入以小数点结尾的临时态（例如 "0."）
      if (endsWithDot && firstDot !== -1) {
        this.form.feeRate = `${intPart || '0'}.`
        return
      }
      // 常规态：有小数部分或仅整数部分
      this.form.feeRate = decPart ? `${intPart || '0'}.${decPart}` : (intPart || '')
    },
    async fetchAddShop() {
      const res = await getAddShop(this.form);
      if (res && res.code==200) {
        this.$message({
          message: '店铺创建成功',
          type: 'success',
          showClose: true
        })      
        this.$router.push('/account/shops')
      }
  
    },
    handleDescriptionInput(value) {
      // 确保不超过300个字符
      if (value && value.length > 300) {
        this.form.description = value.substring(0, 300)
        this.$message({
          message: '店铺描述不能超过300个字符',
          type: 'warning',
          showClose: true
        })
      }
    },
    handleCreate() {
      const isOnlySpaces = (v) => typeof v === 'string' && v.length > 0 && v.trim().length === 0
      if (!this.form.name || isOnlySpaces(this.form.name)) {
        this.$message({
          message: '店铺名称不能为空或全是空格',
          type: 'warning',
          showClose: true
        });
        return;
      }
      if (this.hasEmoji(this.form.name)) {
        this.$message({
          message: '店铺名称不能包含表情符号',
          type: 'warning',
          showClose: true
        });
        return;
      }
      if (this.form.name && this.form.name.length > 30) {
        this.$message({
          message: '店铺名称不能超过30个字符',
          type: 'warning',
          showClose: true
        });
        return;
      }
      if (isOnlySpaces(this.form.description)) {
        this.$message({
          message: '店铺描述不能全是空格',
          type: 'warning',
          showClose: true
        });
        return;
      }
      // 检查店铺描述长度
      if (this.form.description && this.form.description.length > 300) {
        this.$message({
          message: '店铺描述不能超过300个字符',
          type: 'warning',
          showClose: true
        });
        return;
      }
      // 不允许在已有店铺时新建。这里通过路由跳转来源检查或请求前端缓存判断。
      // 更稳妥：可在进入本页前做守卫拦截；此处做一次兜底校验。
      if (this.$route.query && this.$route.query.hasShop === '1') {
        this.$message({
          message: '每个用户仅允许一个店铺，无法新建',
          type: 'warning',
          showClose: true
        });
        this.$router.replace('/account/shops');
        return;
      }

      if (!this.form.name) {
        this.$message.error('店铺名称不能为空')
        return
      }

      // 手续费比例校验：必填、0.01-0.1 且最多6位小数
      const rateRaw = String(this.form.feeRate || '').trim()
      if (!rateRaw) {
        this.$message({
          message: '请填写店铺手续费比例（0.01 - 0.1，最多6位小数）',
          type: 'warning',
          showClose: true
        })
        return
      }
      const rateNum = Number(rateRaw)
      const decOk = rateRaw.includes('.') ? ((rateRaw.split('.')[1] || '').length <= 6) : true
      if (!Number.isFinite(rateNum) || rateNum < 0.01 || rateNum > 0.1 || !decOk) {
        this.$message({
          message: '手续费比例需在 0.01 - 0.1 之间，且小数位不超过6位',
          type: 'warning',
          showClose: true
        })
        return
      }
      this.form.feeRate = rateNum.toString()

      this.fetchAddShop(this.form)
    },
  },
};
</script>

<style scoped>
.panel-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 700;
}
.row {
  display: grid;
  grid-template-columns: 140px 1fr;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}
.label {
  color: #666;
  text-align: right;
  white-space: nowrap; /* 左侧文字不换行 */
  word-break: keep-all;
}
.actions-center {
  grid-column: 1 / -1; /* 跨两列，居中显示 */
  text-align: center;
}
.btn-wide {
  min-width: 200px;
  padding: 10px 28px;
}
.label.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.textarea-wrapper {
  position: relative;
}

.char-count {
  position: absolute;
  bottom: 8px;
  right: 12px;
  font-size: 12px;
  color: #999;
  background: rgba(255, 255, 255, 0.8);
  padding: 2px 6px;
  border-radius: 4px;
  pointer-events: none;
}

.char-count.char-limit {
  color: #f56c6c;
  font-weight: 600;
}
</style>

