<template>
  <div class="add">
    <el-card class="add-container">
      <el-form
        :model="state.goodForm"
        :rules="state.rules"
        ref="goodRef"
        label-width="140px"
        class="goodForm"
      >
        <el-form-item required label="商品所属店铺">
          <el-select
            style="width: 300px"
            v-model="state.goodForm.shopIds"
            filterable
            clearable
            placeholder="请选择店铺"
          >
            <el-option
              v-for="item in state.shopList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item required label="商品分类">
          <el-select
            style="width: 300px"
            v-model="state.goodForm.goodsCategoryId"
            filterable
            clearable
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input
            style="width: 300px"
            v-model="state.goodForm.goodsName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsIntro">
          <el-input
            style="width: 300px"
            type="textarea"
            v-model="state.goodForm.goodsIntro"
            placeholder="请输入商品简介(100字)"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="originalPrice">
          <el-input
            min="0"
            style="width: 300px"
            v-model="state.goodForm.originalPrice"
            placeholder="请输入商品价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品售卖价" prop="sellingPrice">
          <el-input
            min="0"
            style="width: 300px"
            v-model="state.goodForm.sellingPrice"
            placeholder="请输入商品售价"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="stockNum">
          <el-input
            type="number"
            min="0"
            style="width: 300px"
            v-model="state.goodForm.stockNum"
            placeholder="请输入商品库存"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品标签" prop="tag">
          <el-input
            style="width: 300px"
            v-model="state.goodForm.tag"
            placeholder="请输入商品小标签"
          ></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="goodsSellStatus">
          <el-radio-group v-model="state.goodForm.goodsSellStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="交易方式">
          <el-radio-group v-model="state.goodForm.tradeType">
            <el-radio :label="0">线下</el-radio>
            <el-radio :label="1">线上</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item required label="商品主图" prop="goodsCoverImg">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="simpleImgHttpUpload"
          >
            <img
              v-if="state.goodForm.goodsCoverImg"
              :src="state.goodForm.goodsCoverImg"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容" prop="goodsDetailContent">
          <Editor v-model:value="state.goodForm.goodsDetailContent"></Editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{
            state.id ? "立即修改" : "立即创建"
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  reactive,
  ref,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance
} from "vue";
import { request, uploadToOSS } from "@/utils/index";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import Editor from "@/components/Editor.vue";
import { useRoute, useRouter } from "vue-router";

const { proxy } = getCurrentInstance();
const editor = ref(null);
const goodRef = ref(null);
const route = useRoute();
const router = useRouter();
const { id } = route.query;
const state = reactive({
  id: id,
  defaultCate: "",
  shopList: [],
  goodForm: {
    shopIds: undefined,
    goodsName: "",
    goodsCategoryId: undefined,
    goodsIntro: "",
    originalPrice: "",
    sellingPrice: "",
    stockNum: "",
    goodsSellStatus: "0",
    goodsCoverImg: "",
    goodsDetailContent: "",
    tradeType: 0,
    tag: ""
  },
  rules: {
    shopIds: [
      { required: "true", message: "请选择商品所属店铺", trigger: ["change"] }
    ],
    goodsName: [
      { required: "true", message: "请填写商品名称", trigger: ["change"] }
    ],
    originalPrice: [
      { required: "true", message: "请填写商品价格", trigger: ["change"] }
    ],
    sellingPrice: [
      { required: "true", message: "请填写商品售价", trigger: ["change"] }
    ],
    stockNum: [
      { required: "true", message: "请填写商品库存", trigger: ["change"] }
    ],
    // tag: [{ required: "true", message: "请填写商品标签", trigger: ["change"] }],
    goodsCoverImg: [
      { required: "true", message: "请上传商品图片", trigger: ["change"] }
    ],
    goodsDetailContent: [
      { required: "true", message: "请填写详情内容", trigger: ["change"] }
    ]
  },
  categoryId: "",
  category: {
    lazy: true,
    lazyLoad(node, resolve) {
      const { level = 0, value } = node;
      request
        .get("/mallService/mechanism/category", {
          params: {
            page: 1,
            pageSize: 1000,
            categoryLevel: level + 1,
            parentId: value || 0
          }
        })
        .then(res => {
          const list = res.data.list;
          const nodes = list.map(item => ({
            value: item.categoryId,
            label: item.categoryName,
            leaf: level > 1
          }));
          resolve(nodes);
        });
    }
  }
});
const categoryList = ref([]);
let instance;
const getShopList = () => {
  request
    .get("/articleService/serviceProvider/shop/paginate", {
      params: {
        page: 1,
        pageSize: 9999,
        type: -1,
        status: -1
      }
    })
    .then(resp => {
      state.shopList = resp.data.list;
    });
};
onMounted(async () => {
  console.log("加载成功");

  await initCategory();
  getShopList();
  if (id) {
    request.get(`/mallService/mechanism/goods/${id}`).then(res => {
      const {
        goods,
        firstCategory,
        secondCategory,
        thirdCategory,
        category,
        shopIds,
        tradeType
      } = res?.data;
      state.goodForm = {
        shopIds: shopIds?.[0] || undefined,
        goodsName: goods.goodsName,
        goodsIntro: goods.goodsIntro,
        originalPrice: goods.originalPrice / 100,
        sellingPrice: goods.sellingPrice / 100,
        stockNum: goods.stockNum,
        goodsSellStatus: String(goods.goodsSellStatus),
        goodsCoverImg: goods.goodsCoverImg,
        tag: goods.tag,
        goodsDetailContent: goods.goodsDetailContent,
        tradeType: tradeType,
        goodsCategoryId: category.categoryId
      };
      state.categoryId = goods.goodsCategoryId;
      state.defaultCate = `${firstCategory?.categoryName}/${secondCategory?.categoryName}/${thirdCategory.categoryName}`;
      if (instance) {
        // 初始化商品详情 html
        // instance.txt.html(goods.goodsDetailContent);
      }
    });
  }
});
onBeforeUnmount(() => {
  // instance.destroy();
  instance = null;
});
const initCategory = () => {
  return new Promise(resolve => {
    request
      .get("/mallService/mechanism/category", {
        params: {
          page: 1,
          pageSize: 1000
        }
      })
      .then(res => {
        const list = res.data.list;
        categoryList.value = list;
        resolve();
      });
  });
};
const submitAdd = () => {
  goodRef.value.validate(vaild => {
    if (vaild) {
      // 默认新增用 post 方法
      let params = {
        shopIds: [state.goodForm.shopIds],
        goodsCategoryId: Number(state.goodForm.goodsCategoryId),
        goodsCoverImg: state.goodForm.goodsCoverImg,
        goodsDetailContent: state.goodForm.goodsDetailContent,
        goodsIntro: state.goodForm.goodsIntro,
        goodsName: state.goodForm.goodsName,
        goodsSellStatus: Number(state.goodForm.goodsSellStatus),
        originalPrice: Number(state.goodForm.originalPrice) * 100,
        sellingPrice: Number(state.goodForm.sellingPrice) * 100,
        stockNum: Number(state.goodForm.stockNum),
        tag: state.goodForm.tag,
        tradeType: state.goodForm.tradeType
      };
      console.log("params", params);
      if (id) {
        params.goodsId = Number(id);
        // 修改商品使用 put 方法
        request.put("/mallService/mechanism/goods", params).then(resp => {
          ElMessage.success(resp.message);
          router.push({ path: "/shop/goods" });
        });
      } else {
        request.post("/mallService/mechanism/goods", params).then(resp => {
          ElMessage.success(resp.message);
          router.push({ path: "/shop/goods" });
        });
      }
    }
  });
};
const handleBeforeUpload = file => {
  const sufix = file.name.split(".")[1] || "";
  if (!["jpg", "jpeg", "png"].includes(sufix)) {
    ElMessage.error("请上传 jpg、jpeg、png 格式的图片");
    return false;
  }
};
const handleUrlSuccess = val => {
  state.goodForm.goodsCoverImg = val.data || "";
};
const handleChangeCate = val => {
  state.categoryId = val[2] || 0;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  if (!["image/png", "image/jpeg"].includes(rawFile.type)) {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

const simpleImgHttpUpload = options => {
  console.log("options", options);
  uploadToOSS(options.file, options.file.name).then(resp => {
    state.goodForm.goodsCoverImg = resp;
  });
};
</script>

<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.avatar-uploader {
  width: 160px;
  height: 160px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 160px;
  height: 160px;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
  display: flex;
  justify-content: center;
}
</style>
