<template>
    <div class="app-container">
      <div class="main-panel">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="商品基本信息" name="base">
            <div class="content">
              <el-form ref="baseFormRef" :model="baseForm" :rules="baseRules">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="商品名称" prop="name">
                      <el-input
                        class="input"
                        v-model="baseForm.name"
                        placeholder="请输入商品名称"
                        maxlength="25"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="商品分类" prop="cateId">
                      <el-select
                        class="input"
                        v-model="baseForm.cateId"
                        placeholder="请选择商品分类"
                      >
                        <el-option
                          v-for="item in cateOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                          :disabled="item.status!== 'A'"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="商品图片" prop="images">
                      <el-upload
                        class="form__head-icon-upload"
                        :action="uploadAction"
                        :before-upload="beforeUpload"
                        accept="image/*"
                        :class="{ hide: hideUpload }"
                        list-type="picture-card"
                        :file-list="uploadFiles"
                        :limit="10"
                        :auto-upload="true"
                        :headers="uploadHeader"
                        :on-success="handleUploadSuccess"
                        :on-remove="handleRemove"
                      >
                        <i class="el-icon-plus"></i>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="展示排序" prop="sort">
                      <el-input-number v-model="baseForm.sort" :min="0" />
                      <div class="form-tips">提示：数值越小排名越靠前</div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="商品状态">
                      <el-radio-group v-model="baseForm.status">
                        <el-radio key="A" label="上架" value="A"></el-radio>
                        <el-radio key="N" label="下架" value="N"></el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品扩展信息" name="extend">
            <div class="content">
              <el-form ref="extendFormRef" :model="extendForm" :rules="extendRules">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="规格类型" prop="isSingleSpec">
                      <el-radio-group v-model="extendForm.isSingleSpec">
                        <el-radio key="Y" label="单一规格" value="Y"></el-radio>
                        <el-radio key="N" label="多种规格" value="N"></el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="extendForm.isSingleSpec === 'N'">
                  <el-col :span="24">
                    <el-form-item label="商品规格" prop="goodsSpec">
                      <Sku
                        ref="Sku"
                        :skuData="skuData"
                        :goodsId="baseForm.goodsId"
                        :uploadDomain="uploadDomain"
                        @skuChange="skuChange"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="baseForm.type ==='service'">
                  <el-col :span="24">
                    <el-form-item label="服务时长" prop="serviceTime">
                      <el-input
                        v-model="extendForm.serviceTime"
                        class="min-input"
                        placeholder="请输入服务时长"
                        maxlength="50"
                      />
                      <div class="form-tips">请输入服务时长，如 1 小时等</div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="baseForm.type === 'coupon'">
                  <el-col :span="24">
                    <el-form-item label="优惠券 ID" prop="couponIds">
                      <el-input
                        v-model="extendForm.couponIds"
                        class="input"
                        rows="2"
                        type="textarea"
                        placeholder="请输入优惠券 ID"
                        maxlength="1000"
                      />
                      <div class="form-tips">请输入有效的优惠券 ID，多个用逗号分隔</div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="extendForm.isSingleSpec === 'Y'">
                  <el-col :span="24">
                    <el-form-item label="库存数量" prop="stock">
                      <el-input
                        v-model="extendForm.stock"
                        class="min-input"
                        placeholder="请输入库存数量"
                        maxlength="50"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="extendForm.isSingleSpec === 'Y'">
                  <el-col :span="24">
                    <el-form-item label="商品价格" prop="price">
                      <el-input
                        v-model="extendForm.price"
                        class="min-input"
                        placeholder="请输入商品价格"
                        maxlength="50"
                      />
                      <div class="form-tips">单位：元</div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="extendForm.isSingleSpec === 'Y' && baseForm.type === 'product'">
                  <el-col :span="24">
                    <el-form-item label="商品重量" prop="weight">
                      <el-input
                        v-model="extendForm.weight"
                        class="min-input"
                        placeholder="请输入商品重量"
                        maxlength="10"
                      />
                      <div class="form-tips">提示：输入数字，单位 kg</div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="商品描述" name="detail">
            <div class="content" style="width: 375px; margin-left: 80px">
              <el-form ref="detailFormRef" :model="detailForm" :rules="detailRules">
                <editor v-model="detailForm.description" :min-height="550" />
              </el-form>
            </div>
          </el-tab-pane> -->
        </el-tabs>
        <div slot="footer" class="footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import Sku from './Sku.vue';
  
  // 模拟获取 token
  const getToken = () => 'mockedToken';
  
  // 初始化数据
  const storeId = ref(0);
  const loading = ref(false);
  const activeTab = ref('base');
  const storeOptions = ref([]);
  const cateOptions = ref([
    { id: 1, name: '分类 1', status: 'A' },
    { id: 2, name: '分类 2', status: 'A' }
  ]);
  const typeOptions = ref([
    { key: 'product', name: '商品' },
    { key: 'service', name: '服务' },
    { key: 'coupon', name: '优惠券' }
  ]);
  const skuData = ref({ attrList: [], skuList: [], initSkuList: [] });
  
  const baseForm = ref({
    type: 'product',
    goodsId: '',
    name: '',
    storeId: 0,
    cateId: '',
    goodsNo: '',
    images: [],
    status: 'A',
    sort: 0
  });
  
  const extendForm = ref({
    goodsId: '',
    canUsePoint: 'Y',
    isMemberDiscount: 'Y',
    isSingleSpec: 'Y',
    serviceTime: 0,
    couponIds: '',
    stock: '',
    price: '',
    linePrice: '',
    salePoint: '',
    initSale: '',
    weight: '',
    skuData: null
  });
  
  const detailForm = ref({ goodsId: '', description: '' });
  
  const uploadAction = ref('/backendApi/file/upload');
  const uploadHeader = ref({ 'Access-Token': getToken() });
  const uploadDomain = ref('');
  const hideUpload = ref(false);
  const uploadFiles = ref([]);
  
  const baseRules = ref({
    name: [
      { required: true, message: '商品名称为必填项', trigger: 'blur' },
      { min: 2, max: 30, message: '商品名称长度需在 2 - 30 个字符之间', trigger: 'blur' }
    ],
    cateId: [
      { required: true, message: '请选择商品分类', trigger: 'blur' }
    ],
    images: [
      { required: true, message: '请上传商品图片', trigger: 'blur' }
    ]
  });
  
  const extendRules = ref({
    couponIds: [
      { required: true, message: '优惠券 ID 为必填项', trigger: 'blur' },
      { min: 1, max: 1000, message: '优惠券 ID 长度需在 1 - 1000 个字符之间', trigger: 'blur' }
    ],
    isSingleSpec: [
      { required: true, message: '请选择规格类型', trigger: 'blur' }
    ],
    price: [
      { required: true, message: '商品价格为必填项', trigger: 'blur' },
      {
        pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
        message: '商品价格需为正数',
        trigger: 'blur'
      }
    ],
    stock: [
      { required: true, message: '库存数量为必填项', trigger: 'blur' },
      { pattern: /^[0-9]{1,10}$/, message: '库存数量需为正整数', trigger: 'blur' }
    ],
    weight: [
      {
        pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
        message: '商品重量需为非负数',
        trigger: 'blur'
      }
    ]
  });
  
  const detailRules = ref({
    description: [
      { required: true, message: '商品描述为必填项', trigger: 'blur' }
    ]
  });
  
  const baseFormRef = ref(null);
  const extendFormRef = ref(null);
  const detailFormRef = ref(null);
  
  // 模拟获取商品信息
  const getGoodsInfo = (goodsId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockResponse = {
          data: {
            goods: {
              id: 1,
              type: 'product',
              name: '示例商品',
              goodsNo: '123456',
              cateId: 1,
              storeId: 0,
              sort: 0,
              status: 'A',
              canUsePoint: 'Y',
              isMemberDiscount: 'Y',
              isSingleSpec: 'Y',
              stock: '10',
              price: '9.99',
              linePrice: '19.99',
              initSale: '0',
              salePoint: '优质商品',
              weight: '1.5',
              serviceTime: '',
              couponIds: '',
              description: '这是示例商品的描述'
            },
            imagePath: 'https://example.com/images/',
            images: ['image1.jpg'],
            specData: [],
            skuData: [],
            cateList: [
              { id: 1, name: '分类 1', status: 'A' },
              { id: 2, name: '分类 2', status: 'A' }
            ],
            storeList: [],
            typeList: [
              { key: 'product', name: '商品' },
              { key: 'service', name: '服务' },
              { key: 'coupon', name: '优惠券' }
            ]
          }
        };
  
        const goodsInfo = mockResponse.data.goods;
        const imagePath = mockResponse.data.imagePath;
        uploadDomain.value = imagePath;
  
        baseForm.value.goodsId = goodsInfo.id + '';
        baseForm.value.type = goodsInfo.type;
        baseForm.value.name = goodsInfo.name;
        baseForm.value.goodsNo = goodsInfo.goodsNo;
        baseForm.value.cateId = goodsInfo.cateId;
        baseForm.value.storeId = goodsInfo.storeId;
        baseForm.value.sort = goodsInfo.sort;
        baseForm.value.status = goodsInfo.status;
        baseForm.value.images = mockResponse.data.images;
        uploadFiles.value = mockResponse.data.images.map(url => ({ url: imagePath + url }));
  
        extendForm.value.goodsId = goodsInfo.id;
        extendForm.value.canUsePoint = goodsInfo.canUsePoint;
        extendForm.value.isMemberDiscount = goodsInfo.isMemberDiscount;
        extendForm.value.isSingleSpec = goodsInfo.isSingleSpec;
        extendForm.value.stock = goodsInfo.stock;
        extendForm.value.price = goodsInfo.price;
        extendForm.value.linePrice = goodsInfo.linePrice;
        extendForm.value.initSale = goodsInfo.initSale;
        extendForm.value.salePoint = goodsInfo.salePoint;
        extendForm.value.weight = goodsInfo.weight;
        extendForm.value.serviceTime = goodsInfo.serviceTime;
        extendForm.value.couponIds = goodsInfo.couponIds;
  
        skuData.value.attrList = mockResponse.data.specData;
        skuData.value.skuList = mockResponse.data.skuData;
        skuData.value.initSkuList = mockResponse.data.skuData;
  
        detailForm.value.goodsId = goodsInfo.id;
        detailForm.value.description = goodsInfo.description;
  
        cateOptions.value = mockResponse.data.cateList;
        storeOptions.value = mockResponse.data.storeList;
        typeOptions.value = mockResponse.data.typeList;
  
        resolve();
      }, 500);
    });
  };
  
  const props = defineProps({
    detailId:{
        type:String,
        default:0,
    }
  })
  onMounted(async () => {
    const goodsId = 1;
    await getGoodsInfo(goodsId);
  });
  
  const handleTabClick = () => {};
  
  const cancel = () => {
    // 这里可添加返回上一页或其他取消操作的逻辑
    console.log('取消操作');
  };
  
  const skuChange = (newSkuData) => {
    skuData.value = newSkuData;
  };
  
  const submitForm = async () => {
    if (activeTab.value === 'base') {
      baseFormRef.value.validate(async (valid) => {
        if (valid) {
          // 模拟保存基础信息
          ElMessage.success('商品基本信息保存成功');
          await getGoodsInfo(baseForm.value.goodsId);
        } else {
          ElMessage.error('商品基本信息表单验证失败，请检查');
        }
      });
    } else if (activeTab.value === 'extend') {
      if (!extendForm.value.goodsId) {
        ElMessage.error('请先提交商品基本信息');
        activeTab.value = 'base';
        return;
      }
  
      if (skuData.value.skuList && skuData.value.skuList.length > 0) {
        let isValidSkuNo = true;
        let isValidStock = true;
        let isValidPrice = true;
  
        skuData.value.skuList.forEach((item) => {
          if (!item.skuNo || item.skuNo.length < 1) {
            isValidSkuNo = false;
          }
          if (item.stock < 0) {
            isValidStock = false;
          }
          if (item.price < 0) {
            isValidPrice = false;
          }
        });
  
        if (!isValidSkuNo) {
          ElMessageBox.alert('SKU 编号不合法，请检查');
          return;
        }
        if (!isValidStock) {
          ElMessageBox.alert('库存数量不能为负数，请检查');
          return;
        }
        if (!isValidPrice) {
          ElMessageBox.alert('商品价格不能为负数，请检查');
          return;
        }
      }
  
      extendForm.value.skuData = skuData.value.skuList;
      extendForm.value.specData = skuData.value.attrList;
  
      extendFormRef.value.validate(async (valid) => {
        if (valid) {
          // 模拟保存扩展信息
          ElMessage.success('商品扩展信息保存成功');
          await getGoodsInfo(extendForm.value.goodsId);
        } else {
          ElMessage.error('商品扩展信息表单验证失败，请检查');
        }
      });
    } else {
      if (!detailForm.value.goodsId) {
        ElMessage.error('请先提交商品基本信息');
        activeTab.value = 'base';
        return;
      }
  
      detailFormRef.value.validate(async (valid) => {
        if (valid) {
          // 模拟保存详情信息
          ElMessage.success('商品描述信息保存成功');
          await getGoodsInfo(detailForm.value.goodsId);
        } else {
          ElMessage.error('商品描述信息表单验证失败，请检查');
        }
      });
    }
  };
  
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt20M = file.size / 1024 / 1024 < 20;
  
    if (!isImage) {
      ElMessage.error('仅支持上传图片文件');
    }
    if (!isLt20M) {
      ElMessage.error('文件大小不能超过 20MB');
    }
  
    return isImage && isLt20M;
  };
  
  const handleUploadSuccess = (response) => {
    baseForm.value.images.push(response.data.url);
  };
  
  const handleRemove = (file) => {
    const newImages = baseForm.value.images.filter(item => file.url.indexOf(item) === -1);
    baseForm.value.images = newImages;
  };
  
  const createGoodsSn = () => {
    let sn = (Math.random() + 1) * 100000000000000;
    baseForm.value.goodsNo = sn.toFixed(0);
  };
  </script>
  
  <style scoped lang="scss">
  .main-panel {
    padding-top: 5px;
    .content {
      margin-top: 30px;
      margin-left: 20px;
    }
    .footer {
      margin-top: 20px;
    }
    .create-sn {
      font-size: 12px;
      color: blue;
      cursor: pointer;
      width: 100px;
    }
  }
  </style>    