<template>
  <div class="app-container customer-control">
    <div class="customer-box">
      <el-form ref="formRef" :model="formInline" :rules="rules" class="demo-form-inline" :label-width="'auto'">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model="formInline.goodName" clearable show-word-limit maxlength="30" style="width: 800px" />
        </el-form-item>

        <!-- 商品分类 -->
        <el-form-item label="商品分类" required>
          <div style="display: flex; gap: 16px;">
            <el-form-item prop="categoryId1">
              <el-select v-model="formInline.categoryId1" placeholder="请选择" class="my-el-select"
                @change="changeCategory1($event)">
                <el-option v-for="item in categoryList1" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item prop="categoryId2">
              <el-select v-model="formInline.categoryId2" placeholder="请选择" class="my-el-select"
                @change="changeCategory2($event)">
                <el-option v-for="item in categoryList2" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item prop="categoryId3">
              <el-select v-model="formInline.categoryId3" placeholder="请选择" class="my-el-select"
                @change="changeCategory3($event)">
                <el-option v-for="item in categoryList3" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </div>
        </el-form-item>
        <!-- 公共品牌 -->
        <el-form-item label="公共品牌" prop="brandId" v-show="formInline.goodCategorySelectType == 1">
          <el-input v-model="formInline.brandId" clearable placeholder="请输入公共品牌" style="width: 800px" />
        </el-form-item>
        <!-- 溯源编码 -->
        <el-form-item label="溯源编码" prop="traceCode" v-show="formInline.goodCategorySelectType == 1">
          <el-input v-model="formInline.traceCode" clearable placeholder="请输入溯源编码" style="width: 800px" />
        </el-form-item>
        <!-- 商品图片 -->
        <el-form-item label="商品图片" prop="goodUrl" required>
          <div>
            <myUploadImage v-model="formInline.goodUrl"></myUploadImage>
          </div>
        </el-form-item>
        <!-- 规格样式 -->
        <el-form-item label="规格样式" prop="specStyle" required>
          <el-radio-group v-model="formInline.specStyle" style="margin-top: -3px;">
            <el-radio value="1" size="large">单规格</el-radio>
            <el-radio value="2" size="large">多规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="formInline.specStyle == 1">
          <!-- 销售价格 -->
          <el-form-item label="销售价格" prop="salePrice" required>
            <el-input-number v-model="formInline.salePrice" :min="0" :precision="2" :controls="false" />
            <span class="unit">元</span>
          </el-form-item>

          <!-- 库存数量 -->
          <el-form-item label="库存数量" prop="stock" required>
            <el-input-number v-model="formInline.stock" :min="0" :controls="false" />
          </el-form-item>

          <!-- 净含量 -->
          <el-form-item label="净含量" prop="netContent" required>
            <el-input-number v-model="formInline.netContent" :min="0" :controls="false" />
            <el-select v-model="formInline.netContentUnit" style="width: 80px; margin-left: 10px">
              <el-option label="kg" value="kg" />
              <el-option label="g" value="g" />
              <el-option label="ml" value="ml" />
            </el-select>
          </el-form-item>
        </div>
        <!-- 多规格 -->
        <div v-else>
多规格
        </div>
        

        <!-- 商品属性 -->
        <el-form-item label="商品属性" prop="attribute" required>
          <div v-for="(item, index) in formInline.attribute" :key="index" class="attr-item">
            <el-input v-model="item.name" :value="item.name" class="attr-input" placeholder="请输入属性名称" />
            <el-icon size="20px" v-if="index !== 0" @click="deleteAttr(index)" style="cursor: pointer;">
              <Delete />
            </el-icon>
          </div>
          <el-button icon="plus" type="primary" plain style="margin: 0" @click="addAttr">添加属性</el-button>
        </el-form-item>
        <!-- 属性内容 -->
        <el-form-item label="属性内容" prop="attribute" required>
          <div class="attr-box">
            <div class="attr-row">
              <div class="attr-input color-gray">属性名称</div>
              <div class="attr-input color-gray">属性内容</div>
            </div>
            <div v-for="(item, index) in formInline.attribute" :key="index" class="attr-row">
              <div class="attr-input">{{ item.name }}</div>
              <el-input v-model="item.value" class="attr-input" />
            </div>
          </div>
        </el-form-item>
        <!-- 发货地址 -->
        <el-form-item label="发货地址" required>
          <div style="display: flex; gap: 16px;">
            <el-form-item prop="selectedAddress">
              <!-- 省市区级联选择器 -->
              <el-cascader v-model="formInline.selectedAddress" :options="addressOptions" :props="cascaderProps"
                placeholder="请选择省市区" clearable />
            </el-form-item>
            <el-form-item prop="detailAddress">
              <!-- 详细地址输入框 -->
              <el-input v-model="formInline.detailAddress" placeholder="详细地址（如街道、门牌号等）" style="width: 220px;" />
            </el-form-item>
          </div>
        </el-form-item>
        <!-- 保障服务 -->
        <el-form-item label="保障服务" prop="safeguard" required style="margin-bottom: 2px;">
          <el-checkbox v-model="isSafeguardSelected" size="large" style="margin-top: -3px;">
            <div style="color: #333;" v-for="(item, index) in formInline.safeguard.options" :key="index">{{ item.text }}
            </div>
          </el-checkbox>
        </el-form-item>
        <!-- 优惠折扣 -->
        <el-form-item label="优惠折扣" style="margin-bottom: 10px;">
          <div style="width: 100%;">
            <el-checkbox v-model="isDiscountSettings" size="large" style="margin-top: -3px;">
              <div style="color: #333;" v-for="(item, index) in formInline.discountSettings.options" :key="index">{{
                item.text }}</div>
            </el-checkbox>
          </div>
          <div style="width: 100%;">
            <el-checkbox v-model="isDiscountRebate" size="large" style="margin-top: -3px;">
              <div style="color: #333;" v-for="(item, index) in formInline.discountSettings.options" :key="index">{{
                item.text }}</div>
            </el-checkbox>
          </div>
        </el-form-item>
        <!-- 商品详情 -->
        <el-form-item label="商品详情" prop="detailUrl">
          <div>
            <myUploadImage v-model="formInline.detailUrl" :isShowSubscript="false"></myUploadImage>
          </div>
        </el-form-item>
        <!-- 商品视频 -->
        <el-form-item label="商品视频" prop="videoUrl">
          <div>
            <myUploadVideo v-model="formInline.videoUrl"></myUploadVideo>
          </div>
        </el-form-item>

      </el-form>
      <el-button type="primary" @click="onSave" style="margin: 10px 0 0 80px;width: 150px;">确认新增</el-button>
    </div>
  </div>
</template>
<script setup>
import { ca } from "element-plus/es/locales.mjs";
import { ref, reactive, nextTick, onMounted } from "vue";
import myUploadImage from "@/components/myUploadImage.vue";
import myUploadVideo from "@/components/myUploadVideo.vue";
import { getGoodType } from "@/api/goods/info";

const formRef = ref(null)
const formInline = reactive({
  goodName: "高质量水稻",
  categoryId: "", //一级,
  categoryId1: "", //一级,
  categoryId2: "", //二级
  categoryId3: "", //三级
  goodUrl: "", //逗号分割的多个图片地址字符串
  goodCategorySelectType: 2, // 商品分类一级选项
  brandId: "", //品牌
  traceCode: "", //溯源码

  specStyle: "1",//规格样式
  salePrice: 0,//销售价格-单规格
  stock: 6500,//库存数量-单规格
  netContent: 0,//净含量-单规格
  netContentUnit: "kg",//净含量单位
  netWeight: [
    {
      "goodSpecs": "含氮20%",
      "goodPrice": 135,
      "goodStock": 10000,
      "netContent": "50",
      "unit": "kg"
    }
  ], //规格，格式建议数组
  attribute: [
    {
      name: '品牌', //属性
      value: '童涵春堂', //内容
    },
    {
      name: '型号', //属性
      value: '种子种苗', //内容
    },
  ],
  selectedAddress: [], //选中的省市区编码数组
  areaAddress: '云南省,昆明市,五华区', //区域地址
  detailAddress: "", //详细地址
  sendAddress: "云南省昆明市", //提交的组合地址
  isCheckbox: true,
  safeguard: {
    isSelected: 1, //0未选中 1选中
    options: [
      { text: '该商品，支持【七天无理由退货】服务' },
    ]
  }, //保障服务
  discountSettings: {
    isSelected: 0, //0未选中 1选中
    options: [
      { text: '支持【满100减10元】优惠活动' },
      { text: '支持【满200减20元】优惠活动' },
    ]
  }, //优惠设置
  discountRebate: {
    isSelected: 0, //0未选中 1选中
    options: [
      { text: '支持【满两件-打8折】优惠活动' },
      { text: '支持【单件-打905折】优惠活动' },
    ]
  }, //优惠折扣
  detailUrl: "",
  brandId: "44552",
  traceCode: "45788",
  videoUrl: "",
});
const rules = reactive({
  goodName: [
    {
      required: true,
      message: '请输入商品名称',
      trigger: 'blur'
    },
  ],
  categoryId1: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  categoryId2: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  categoryId3: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  goodUrl: [
    {
      validator: (rule, value, callback) => {
        if (value === "" || value.trim() === "") {
          callback(new Error('请至少上传一张商品图片'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  specStyle: [
    { required: true, message: '请选择规格样式', trigger: 'change' }
  ],
  salePrice: formInline.specStyle === '1' ? [
    {
      validator: (rule, value, callback) => {
        if (!value || Number(value) <= 0) {
          callback(new Error('请输入销售价格'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    },
  ] : [],
  stock: formInline.specStyle === '1' ? [
    {
      validator: (rule, value, callback) => {
        if (!value || Number(value) <= 0) {
          callback(new Error('请输入库存数量'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    },
  ] : [],
  netContent: formInline.specStyle === '1' ? [
    {
      validator: (rule, value, callback) => {
        if (!value || Number(value) <= 0) {
          callback(new Error('请输入净含量'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    },
  ] : [],
  attribute: [
    {
      validator: (rule, value, callback) => {
        // 检查是否至少有一个属性
        if (!value || value.length === 0) {
          return callback(new Error('至少需要添加一个属性'))
        }

        // 检查每个属性名称是否已填写
        const emptyNames = value.filter(item => !item.name?.trim())
        if (emptyNames.length > 0) {
          return callback(new Error('请填写所有属性名称和内容'))
        }

        callback()
      },
      trigger: 'blur'
    }
  ],
  selectedAddress: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length !== 3) {
          callback(new Error('请选择完整的省市区'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
})

const addAttr = () => {
  formInline.attribute.push({
    name: '',
    value: '',
  })
}
const deleteAttr = (index) => {
  formInline.attribute.splice(index, 1)
}

// 选中的省市区编码数组（如：['云南省', '昆明市', '呈贡区']）
const selectedAddress = ref([]);
const detailAddress = ref('');
// 级联选择器配置
const cascaderProps = ref({
  value: 'name',  // 选项值字段名
  label: 'name',  // 选项标签字段名
  children: 'children' // 子选项字段名
});
// 省市区数据（示例）
const addressOptions = ref([
  {
    name: '云南省',
    children: [
      {
        name: '昆明市',
        children: [
          { name: '五华区' },
          { name: '盘龙区' },
          { name: '呈贡区' }
        ]
      },
      {
        name: '曲靖市',
        children: [
          { name: '麒麟区' },
          { name: '沾益区' }
        ]
      }
    ]
  },
  {
    name: '广东省',
    children: [
      {
        name: '广州市',
        children: [
          { name: '天河区' },
          { name: '越秀区' }
        ]
      }
    ]
  }
  // 其他省份数据...
]);

// 保障服务
const isSafeguardSelected = computed({
  get: () => formInline.safeguard.isSelected === 1,
  set: (val) => {
    formInline.safeguard.isSelected = val ? 1 : 0
  }
})
// 优惠设置
const isDiscountSettings = computed({
  get: () => formInline.discountSettings.isSelected === 1,
  set: (val) => {
    formInline.discountSettings.isSelected = val ? 1 : 0
  }
})
// 优惠折扣
const isDiscountRebate = computed({
  get: () => formInline.discountRebate.isSelected === 1,
  set: (val) => {
    formInline.discountRebate.isSelected = val ? 1 : 0
  }
})

// 文件上传前的校验
// const beforeUpload = (file) => {
//   const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
//   const isLt2M = file.size / 1024 / 1024 < 2

//   if (!isImage) {
//     ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
//     return false
//   }
//   if (!isLt2M) {
//     ElMessage.error('图片大小不能超过2MB!')
//     return false
//   }
//   return true
// }
// 文件变化时触发验证
// const handleChange = () => {
//   console.log('文件变化时触发验证')
//   nextTick(() => {
//     console.log(formInline.images)
//     formRef.value.validateField('images')
//   })
// }
// 移除文件时触发验证
// const handleRemove = (file) => {
//   console.log('移除文件时触发验证')
//   console.log(file)
//   console.log(formInline.images)
//   formInline.images = formInline.images.filter(item => item.uid !== file.uid)
//   formRef.value.validateField('images')
// }
// 超出限制提示
// const handleExceed = () => {
//   ElMessage.warning('最多只能上传5张图片!')
// }

const categoryList1 = ref([]);
const categoryList2 = ref([]);
const categoryList3 = ref([]);

const getGoodTypeList = async () => {
  try {
    let response = await getGoodType();
    console.log(response);
    if (response.code == 200) {
      categoryList1.value = response.data;
    }
  } catch (error) {
    console.log(error);
  }
};
const changeCategory1 = (id) => {
  console.log(id);
  formInline.categoryId1 = id;
  formInline.categoryId2 = "";
  categoryList2.value = categoryList1.value.filter((item) => item.id == id)[0].children;
  formInline.categoryId3 = "";
  formInline.categoryId = "";
  categoryList3.value = [];
  if (id == 70) {
    // 选择产出品
    formInline.goodCategorySelectType = 1;
  } else {
    // 选择投入品
    formInline.goodCategorySelectType = 2;
  }
};
const changeCategory2 = (id) => {
  console.log(id);
  formInline.categoryId2 = id;
  categoryList3.value = categoryList2.value.filter((item) => item.id == id)[0].children;
  formInline.categoryId3 = "";
  formInline.categoryId = "";
};
const changeCategory3 = (id) => {
  console.log(id);
  formInline.categoryId3 = id;
  formInline.categoryId = id;
};

const onSave = async () => {
  console.log(formInline);
  // formRef.validate(valid => {
  //   if (!valid) return
  //   console.log('验证通过!', formRef.value)
  // })
  try {
    await formRef.value.validate()
    console.log('验证通过!', formRef.value)
    // 整理提交的参数

    // 调用接口提交

  } catch (error) {
    console.log('验证失败', error)
  }
};

const getGoodTypeList2 = async () => {
  const res = await getGoodType({
    pageNum: 1,
    pageSize: 100,
  });
  if (res.code === 200) {
    goodTypeList.value = res.data.list;
  }
};

onMounted(() => {
  getGoodTypeList();
});
</script>
<style lang="scss" scoped></style>
