<template>
  <div class="product-new">
    <el-card class="product-form-card">
      <div slot="header" class="card-header">
        <h2>新增商品</h2>
        <p class="subtitle">创建新的商品信息</p>
      </div>
      
      <el-form 
        ref="productForm" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        class="product-form"
      >
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入商品名称，如：Nexa-M2-Miner"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>

        <!-- 商品类型 -->
        <el-form-item label="商品类型" prop="type" class="align-like-input">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">矿机</el-radio>
            <!-- <el-radio :label="1">算力</el-radio> -->
          </el-radio-group>
        </el-form-item>

        <!-- 矿机挖矿币种 -->
        <el-form-item label="挖矿币种" prop="coin">
          <el-select 
            v-model="form.coin" 
            placeholder="请选择挖矿币种"
            style="width: 100%"
          >
            <el-option
              v-for="coin in coinOptions"
              :key="coin.value"
              :label="coin.label"
              :value="coin.value"
            />
          </el-select>
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <!-- 商品图片（非必填） -->
        <!-- <el-form-item label="商品图片" prop="image">
          <el-input 
            v-model="form.image" 
            placeholder="请输入商品图片路径"
          />
        </el-form-item> -->

        <!-- 单机算力 -->
        <!-- <el-form-item label="单机算力" prop="power">
          <el-input
            v-model.number="form.power"
            type="number"
            placeholder="请输入单机算力"
          >
            <el-select
              slot="append"
              v-model="form.unit"
              placeholder="单位"
              style="width: 110px"
            >
              <el-option label="GH/S" value="GH/S" />
              <el-option label="TH/S" value="TH/S" />
              <el-option label="PH/S" value="PH/S" />
            </el-select>
          </el-input>
        </el-form-item> -->


        <!-- 功耗 -->
        <!-- <el-form-item label="功耗" prop="powerDissipation">
          <el-input
            v-model.number="form.powerDissipation"
            type="number"
            placeholder="请输入功耗"
          >
            <template slot="append">kw/h</template>
          </el-input>
        </el-form-item> -->

        <!-- 电费 -->
        <!-- <el-form-item label="电费" prop="electricityBill">
          <el-input
            v-model.number="form.electricityBill"
            type="number"
            placeholder="请输入电费"
          >
            <template slot="append">$/度</template>
          </el-input>
        </el-form-item> -->

        <!-- 收益率 -->
        <!-- <el-form-item label="收益率" prop="incomeRate">
          <el-input
            v-model.number="form.incomeRate"
            type="number"
            placeholder="请输入收益率"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item> -->

        <!-- 上下架状态 -->
        <el-form-item label="商品状态" prop="state" class="align-like-input">
          <el-radio-group v-model="form.state">
            <el-radio :label="0">上架</el-radio>
            <el-radio :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="actions-row">
          <div class="form-actions">
            <el-button type="primary" size="medium" @click="handleSubmit" :loading="submitting">创建商品</el-button>
            <el-button size="medium" @click="handleReset">重置</el-button>
            <el-button size="medium" @click="handleCancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { coinList } from '@/utils/coinList'
import { createProduct } from '../../api/products'

export default {
  name: 'AccountProductNew',
  data() {
    const notOnlySpaces = (rule, value, callback) => {
      if (typeof value === 'string' && value.trim().length === 0) {
        callback(new Error('内容不能全是空格'))
        return
      }
      callback()
    }
    /**
     * 检测字符串是否包含表情符号
     * @param {string} text - 待检测文本
     * @returns {boolean} 是否包含表情符号
     */
    const containsEmoji = (text) => {
      if (typeof text !== 'string' || text.length === 0) {
        return false
      }
      // 覆盖常见 Emoji 范围、旗帜、杂项符号、交通、补充符号、ZWJ、变体选择符与组合字符等
      const emojiPattern = /[\u{1F300}-\u{1FAFF}]|[\u{1F1E6}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{FE0F}]|[\u{200D}]|[\u{20E3}]/u
      return emojiPattern.test(text)
    }

    /**
     * 不允许包含表情符号的名称校验器
     * @param {object} rule - 校验规则对象
     * @param {string} value - 输入值
     * @param {Function} callback - 回调
     * @returns {void}
     */
    const noEmoji = (rule, value, callback) => {
      if (typeof value === 'string' && containsEmoji(value)) {
        callback(new Error('商品名称不能包含表情符号'))
        return
      }
      callback()
    }
    return {
      submitting: false,
      form: {
        name: '',
        type: 0,
        coin: '',
        description: '',//商品描述
        image: '',
        // power: null,
        // unit: 'GH/S',
        // powerDissipation: null,
        // electricityBill: null,//电费
        // incomeRate: null,//收益率
        state: 0,
        shopId: null
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { validator: notOnlySpaces, trigger: 'blur' },
          { validator: noEmoji, trigger: 'blur' },
          { min: 1, max: 30, message: '商品名称长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择商品类型', trigger: 'change' }
        ],
        coin: [
          { required: true, message: '请选择挖矿币种', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
          { validator: notOnlySpaces, trigger: 'blur' },
          { min: 1, max: 100, message: '商品描述长度在 1 到 100 个字符', trigger: 'blur' }
        ],
          image: [],
          // power: [
        //   { required: true, message: '请输入单机算力', trigger: 'blur' },
        //   { type: 'number', min: 0.01, message: '算力必须大于0', trigger: 'blur' }
        // ],
        // unit: [ { required: true, message: '请选择算力单位', trigger: 'change' } ],
        // powerDissipation: [
        //   { required: true, message: '请输入功耗', trigger: 'blur' },
        //   { type: 'number', min: 0.01, message: '功耗必须大于0', trigger: 'blur' }
        // ],
        // electricityBill: [
        //   { required: true, message: '请输入电费', trigger: 'blur' },
        //   { type: 'number', min: 0.01, message: '电费必须大于0', trigger: 'blur' }
        // ],
        // incomeRate: [
        //   { required: true, message: '请输入收益率', trigger: 'blur' },
        //   { type: 'number', min: 0.0001, max: 1, message: '收益率必须在0.0001到1之间', trigger: 'blur' }
        // ],
        state: [
          { required: true, message: '请选择商品状态', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    coinOptions() {
      return coinList || [
        { value: 'nexa', label: 'NEXA' },
        { value: 'rxd', label: 'RXD' },
        { value: 'dgbo', label: 'DGBO' },
        { value: 'dgbq', label: 'DGBQ' },
        { value: 'dgbs', label: 'DGBS' },
        { value: 'alph', label: 'ALPH' },
        { value: 'enx', label: 'ENX' },
        { value: 'grs', label: 'GRS' },
        { value: 'mona', label: 'MONA' }
      ]
    }
  },
  created() {
    // 从路由参数获取店铺ID
    const shopId = this.$route.query.shopId
    if (shopId) {
      this.form.shopId = Number(shopId)
    }
  },
  methods: {
    async fetchAddProduct(params) {
      const res = await createProduct(params)
      if (res && (res.code === 0 || res.code === 200)) {
        
        this.$message({
          message: '商品创建成功',
          type: 'success',
          showClose: true
        })
        this.$router.push('/account/products')
      }else {
          this.$message({
            message: res && res.msg ? res.msg : '创建失败',
            type: 'error',
            showClose: true
          })
        }
    },
    /**
     * 提交表单
     */
    async handleSubmit() {
      try {
        // 表单验证
        const valid = await this.$refs.productForm.validate()
        if (!valid) {
          return
        }

        // 检查是否有店铺ID
        if (!this.form.shopId) {
          this.$message({
            message: '缺少店铺ID，请从我的店铺页面进入',
            type: 'error',
            showClose: true
          })
          return
        }

        this.submitting = true
        
        this.fetchAddProduct(this.form)
     
        
      } catch (error) {
        console.error('创建商品失败:', error)
       
      } finally {
        this.submitting = false
      }
    },

    /**
     * 重置表单
     */
    handleReset() {
      this.$refs.productForm.resetFields()
      // 保持店铺ID
      const shopId = this.$route.query.shopId
      if (shopId) {
        this.form.shopId = Number(shopId)
      }
    },

    /**
     * 取消操作
     */
    handleCancel() {
      this.$router.push('/account/shops')
    }
  }
}
</script>

<style scoped>
.product-new {
  padding: 20px;
  max-width: 60vw;
  margin: 0 auto;
}

.product-form-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.product-form {
  margin-top: 20px;
}

/* 单选组左对齐，和输入框对齐 */
.product-form .el-form-item .el-radio-group {
  display: inline-flex;
  align-items: center;
  gap: 24px;
  padding-left: 0;
  margin-left: 0;
}

/* 让单选组整体与输入框内容左边缘对齐（考虑到Element默认label-width=120px，
   输入框内部有一定内边距，这里为内容区域添加与输入框相同的内边距） */
.product-form .align-like-input .el-form-item__content {
  padding-left: 15px; /* 与 el-input 默认内边距对齐 */
}

.unit-text {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

/* 操作按钮：居中对齐，等宽美观 */
.actions-row .el-form-item__content {
    text-align: center;
}

.form-actions {
  /* display: grid; */
  grid-auto-flow: column;
  text-align: center;
}

.form-actions .el-button {
  min-width: auto; /* 自适应文字宽度 */
  white-space: nowrap;
  padding: 8px 20px !important;
  min-width: 160px;
}

/* 隐藏数字输入框的上下箭头（各浏览器兼容） */
::v-deep input[type='number']::-webkit-outer-spin-button,
::v-deep input[type='number']::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
::v-deep input[type='number'] {
  -moz-appearance: textfield;
  appearance: textfield;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-new {
    padding: 15px;
  }
  
  .product-form-card {
    margin: 0 10px;
  }
  
  .el-form-item {
    margin-bottom: 18px;
  }
}

::v-deep .el-form-item__content{
    text-align: left;
}
</style> 