<script setup>
import { ref, watch, nextTick, computed, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import useUserStore from '@/stores/modules/user';
import config from "@/config";
import {
  categoryListApi,
  productCreateApi,
  productDetailApi,
  productUpdateApi,
} from "@/api/shop";

const drawer = ref(false);
const table = {
  store_name: "",
  image: [],
  slider_image: [],
  attrValue: [
    {
      bar_code: "",
      price: "",
      stock: "",
      cost: "",
      ot_price: "",
      wholesale_price: "0",
      extension_one: "",
      extension_two: "",
    },
  ],
  content: {
    image: [],
  },
  unit_name: "",
  delivery_way: ["1"],
};
const formData = ref(table);

const userStore = useUserStore();

const emit = defineEmits(["reload"]);

const dialogImgVisible = ref(false);
const dialogImageUrl = ref("");

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogImgVisible.value = true;
};

const showType = ref("add");
const show = (type, data) => {
  formData.value = table;
  showType.value = type;
  if (type == "add") {
    drawer.value = true;
  } else if (type == "edit") {
    drawer.value = true;
    getProductDetail(data.product_id);
  }
};

const getProductDetail = (id) => {
  productDetailApi(userStore.userInfo.service.mer_id, id).then((res) => {
    res.data.image = [
      {
        url: res.data.image,
        uid: res.data.image,
      },
    ];
    res.data.content.image = res.data.content.image.map((item) => {
      return {
        url: item,
        uid: res.data.image,
      };
    });
    res.data.slider_image = res.data.slider_image.map((item) => {
      return {
        url: item,
        uid: res.data.image,
      };
    });
    formData.value = res.data;
    console.log(formData.value);
  });
};

const categoryList = ref([]);
const getCategoryList = () => {
  categoryListApi(userStore.userInfo.service.mer_id).then((res) => {
    categoryList.value = res.data;
  });
};
getCategoryList();

const uploadImage = (res) => {
  formData.value.image = res.data.path;
};
const uploadSliderImage = (res) => {
  console.log(formData.value.slider_image);
};
const handleRemove = (file) => {
  console.log(file);
};

const formRef = ref(null);
const submit = () => {
  let data = JSON.parse(JSON.stringify(formData.value));
  console.log(data.cate_id);
  if (data.cate_id && typeof data.cate_id == "object" && data.cate_id.length > 0)
    data.cate_id = data.cate_id[data.cate_id.length - 1] || '';
else data.cate_id = data.cate_id || '';
  if (data.image == "") return ElMessage.error("请上传商品封面图");
//   if (data.content.image.length == 0)
//     return ElMessage.error("请上传商品详情图");
  if (data.slider_image.length == 0) return ElMessage.error("请上传商品轮播图");
  data.content.image = data.content.image.map((item) => {
    return item?.response?.data?.path ? item?.response?.data?.path : item.url;
  });
  data.image = data.image[0]?.response?.data?.path
    ? data.image[0]?.response?.data?.path
    : data.image[0].url;
  data.slider_image = data.slider_image.map((item) => {
    return item?.response?.data?.path ? item?.response?.data?.path : item.url;
  });
  if (data.store_name == "") return ElMessage.error("请输入商品名称");
  if (data.cate_id == "") return ElMessage.error("请选择平台分类");
  if (data.attrValue[0].bar_code == "")
    return ElMessage.error("请输入商品条码");
  if (data.attrValue[0].stock<=0) return ElMessage.error("请输入商品库存");
  if (data.attrValue[0].price<=0) return ElMessage.error("请输入商品价格");
  if (showType.value == "add")
    productCreateApi(userStore.userInfo.service.mer_id, data).then((res) => {
      ElMessage.success(res.message);
      emit("reload");
      beforeClose();
    });
  else
    productUpdateApi(
      userStore.userInfo.service.mer_id,
      data.product_id,
      data
    ).then((res) => {
      ElMessage.success(res.message);
      emit("reload");
      beforeClose();
    });
};

const cancelClick = () => {
  beforeClose();
};
const beforeClose = () => {
  drawer.value = false;
};
const open = () => {};

defineExpose({
  drawer,
  show,
});
</script>

<template>
  <el-drawer
    :size="800"
    v-model="drawer"
    direction="rtl"
    @open="open"
    :before-close="beforeClose"
  >
    <template #header>
      <h4 v-if="showType=='add'">添加商品</h4>
      <h4 v-else>编辑商品 [{{formData.product_id}}]</h4>
    </template>
    <template #default>
      <div class="dra-body">
        <el-form ref="formRef" :model="formData" label-width="150px">
          <el-form-item label="商品条码" required>
            <el-input
              v-model="formData.attrValue[0].bar_code"
              type="number"
              placeholder="请输入商品条码"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品名称" required>
            <el-input
              v-model="formData.store_name"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="平台分类" required>
            <el-cascader
              v-model="formData.cate_id"
              class="pageWidth"
              :options="categoryList"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item label="商品封面图" required>
            <el-upload
              v-model:file-list="formData.image"
              :action="config.upload"
              name="field"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :limit="1"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品轮播图" required>
            <el-upload
              v-model:file-list="formData.slider_image"
              :action="config.upload"
              name="field"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :limit="9"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品详情">
            <el-upload
              v-model:file-list="formData.content.image"
              :action="config.upload"
              name="field"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :limit="9"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品单位" required>
            <el-input
              v-model="formData.unit_name"
              placeholder="请输入商品单位"
            ></el-input>
          </el-form-item>
          <el-form-item label="零售价" required>
            <el-input
              v-model="formData.attrValue[0].price"
              type="number"
              placeholder="请输入零售价"
            ></el-input>
          </el-form-item>
          <el-form-item label="库存" required>
            <el-input
              v-model="formData.attrValue[0].stock"
              type="number"
              placeholder="请输入库存"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-dialog v-model="dialogImgVisible">
        <img
          style="width: 100%; height: 100%"
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
        />
      </el-dialog>
    </template>
    <template #footer>
      <el-button @click="cancelClick">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.dra-body {
  width: 100%;
  display: flex;
  flex-direction: column;
  /* align-items: center; */
  text-align: center;
}
::v-deep .el-upload--picture-card {
  --el-upload-picture-card-size: 60px !important;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  height: 60px !important;
  width: 60px !important;
}
</style>
