<script setup>
import { ref, reactive, onMounted, computed } from "vue";

import { Plus } from "@element-plus/icons-vue";

import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

import { getCateList } from "@/api/category";
import { getBrandList } from "@/api/brand";
import { addGoods } from "@/api/goods";
import { ElMessage } from "element-plus";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:show", "reload"]);

const showDrawer = computed({
  get: () => props.show,
  set: (value) => {
    emit("update:show", value);
  },
});

const activeName = ref("1");
const formRef = ref(null);

const cat_list = ref([]);
const brand_list = ref([]);

const editor = ref(ClassicEditor);
const editorConfig = ref({
  toolbar: [
    "heading",
    "|",
    "bold",
    "italic",
    "link",
    "bulletedList",
    "numberedList",
    "blockQuote",
    "insertTable",
    "undo",
    "redo",
  ],
});

const rules = reactive({
  type_name: [{ required: true, message: "請輸入優惠劵名稱", trigger: "blur" }],
  type_money: [
    { required: true, message: "請輸入優惠劵金額", trigger: "blur" },
  ],
  send_type: [{ required: true, message: "請選擇發放方式", trigger: "change" }],
});

const form = reactive({
  goods_id: 0,
  goods_name: "",
  cat_id: null,
  is_on_sale: 1,
  is_alone_sale: 1,
  is_shipping: 1,
  goods_gallery: [],
});

const loading = ref(false);

onMounted(async () => {
  let res1 = await getCateList();
  if (res1.code === 200) {
    cat_list.value = res1.data;
  }

  let res2 = await getBrandList();
  if (res2.code === 200) {
    brand_list.value = res2.data;
  }
});

//上傳圖片
const goods_image = ref(null);
const goods_thumb = ref(null);
const fileList = ref([]);

const handleGoodsImgSuccess = (res) => {
  console.log('upload success')
  if (res.code === 200) {
    form.goods_img = res.data
  }else{
    ElMessage.error(res.data);
    goods_image.value.clearFiles();
  }
};

const handleGoodsThumbSuccess = (res) => {
  console.log('upload thumb success')
  if (res.code === 200) {
    form.goods_thumb = res.data
  }else{
    ElMessage.error(res.data);
    goods_thumb.value.clearFiles();  
  }
};



const handleExceed = (files) => {
  goods_image.value.clearFiles();
  const file = files[0]
  goods_image.value.handleStart(file)
  goods_image.value.submit()
};

const handleThumbExceed = (files) => {
  goods_thumb.value.clearFiles();
  const file = files[0]
  goods_thumb.value.handleStart(file)
  goods_thumb.value.submit()
};


const beforeGoodsImageRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `確定刪除 ?`
  ).then(
    () => {
      form.goods_img = '';
    },
    () => false
  );
};

const beforeGoodsThumbRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `確定刪除 ?`
  ).then(
    () => {
      form.goods_thumb = '';
    },
    () => false
  );
};

const handleGoodsGallerySuccess = (res, file) => {
  if (res.code === 200) {
    form.goods_gallery.push({uid: file.uid,img : res.data})
  }else{
    ElMessage.error(res.data);
    goods_thumb.value.clearFiles();  
  }
};

const beforeGoodsGalleryRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `確定刪除 ?`
  ).then(
    () => {
      //移除form.goods_gallery中uid為file.uid的元素
      form.goods_gallery = form.goods_gallery.filter(item => item.uid !== uploadFile.uid)
      console.log(form.goods_gallery)
    },
    () => false
  );
};

const handleClose = () => {
  showDrawer.value = false;
};

const handleSubmit = async (formEl) => {
  console.log(form);

  if (!formEl) return;

  await formEl.validate(async (valid, fields) => {
    if (!valid) return;
    let res = await addGoods(form);
    if (res.code === 200) {
      // 關閉抽屜
      showDrawer.value = false;
      // 重置表單
      formRef.value.resetFields();

      // emit reload event
      emit("reload");

      // 顥示提示訊息
      return ElMessage.success("新增成功");
    }
    // 顯示錯誤提示訊息
    return ElMessage.error(res.msg);
  });
};
</script>

<template>
  <el-drawer v-model="showDrawer" size="60%" title="新增商品">
    <template #header>
      <h4>新增商品</h4>
    </template>
    <template #default>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="一般訊息" name="1" />
        <el-tab-pane label="商品詳細" name="2" />
        <el-tab-pane label="其他訊息" name="3" />
        <el-tab-pane label="商品屬性" name="4" />
        <el-tab-pane label="商品相冊" name="5" />
        <el-tab-pane label="關連商品" name="6" />
        <el-tab-pane label="配件" name="7" />
        <el-tab-pane label="相關文章" name="8" />
      </el-tabs>
      <el-form ref="formRef" :model="form" label-width="120px">
        <div v-show="activeName == '1'">
          <el-form-item label="商品名稱">
            <el-input v-model="form.goods_name" />
          </el-form-item>
          <el-form-item label="商品簡述">
            <el-input type="textarea" v-model="form.goods_brief" />
          </el-form-item>
          <el-form-item label="商品貨號">
            <el-input v-model="form.goods_sn" />
          </el-form-item>
          <el-form-item label="商品分類">
            <el-tree-select
              v-model="form.cat_id"
              :data="cat_list"
              check-strictly
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="商品品牌">
            <el-select v-model="form.brand_id" placeholder="請選擇" clearable>
              <el-option
                v-for="v in brand_list"
                :key="v.brand_id"
                :label="v.brand_name"
                :value="v.brand_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="本店售價">
            <el-input v-model="form.shop_price" />
          </el-form-item>
          <el-form-item label="市場售價">
            <el-input v-model="form.market_price" />
          </el-form-item>
          <el-form-item label="促銷商品">
            <el-switch
              v-model="form.is_promote"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <div v-show="form.is_promote === 1">
          <el-form-item label="促銷價">
            <el-input v-model="form.promote_price" />
          </el-form-item>
          <el-form-item label="促銷日期">
            <el-col :span="11">
              <el-date-picker
                v-model="form.promote_start_date"
                type="date"
                placeholder="選擇促銷開始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-col>
            <el-col :span="2" class="text-center">
              <span class="text-gray-500">-</span>
            </el-col>
            <el-col :span="11">
              <el-date-picker
                v-model="form.promote_end_date"
                type="date"
                placeholder="選擇促銷結束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-col>
          </el-form-item>
          </div>
          <el-form-item label="分成金額">
            <el-input v-model="form.fencheng" />
          </el-form-item>
          <el-form-item label="上傳商品圖">
            <el-upload
              ref="goods_image"
              class="upload-demo"
              action="https://shop.h888.fun/adminapi/v1/goods/uploadImg"
              :limit="1"
              :on-exceed="handleExceed"
              :on-success="handleGoodsImgSuccess"
              :before-remove="beforeGoodsImageRemove"
            >
              <el-button type="primary">點擊上傳</el-button>
              <!-- <template #tip>
                <div class="el-upload__tip">4M以下的jpg或png檔.</div>
              </template> -->
            </el-upload>
          </el-form-item>
          <el-form-item label="上傳商品縮圖">
            <el-upload
              ref="goods_thumb"
              class="upload-demo"
              action="https://shop.h888.fun/adminapi/v1/goods/uploadImg"
              :limit="1"
              :on-exceed="handleThumbExceed"
              :on-success="handleGoodsThumbSuccess"
              :before-remove="beforeGoodsThumbRemove"
            >
              <el-button type="primary">點擊上傳</el-button>
            </el-upload>
          </el-form-item>
        </div>
        <div v-show="activeName == '2'">
          <ckeditor
            :editor="editor"
            v-model="form.goods_desc"
            :config="editorConfig"
          ></ckeditor>
        </div>
        <div v-show="activeName == '3'">
          <el-form-item label="商品重量">
            <el-input v-model="form.goods_weight" />
          </el-form-item>
          <el-form-item label="商品庫存">
            <el-input v-model="form.goods_number" />
          </el-form-item>
          <el-form-item label="庫存警告數量">
            <el-input v-model="form.warn_number" />
          </el-form-item>
          <el-form-item label="加入推薦">
            <el-checkbox
              label="精品"
              v-model="form.is_best"
              :true-label="1"
              :false-label="0"
            />
            <el-checkbox
              label="新品"
              v-model="form.is_new"
              :true-label="1"
              :false-label="0"
            />
            <el-checkbox
              label="熱銷"
              v-model="form.is_hot"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
          <el-form-item label="上架">
            <el-switch
              v-model="form.is_on_sale"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="做為普通商品">
            <el-switch
              v-model="form.is_alone_sale"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="免運商品">
            <el-switch
              v-model="form.is_shipping"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="商家備註">
            <el-input v-model="form.seller_note" />
          </el-form-item>
        </div>
        <div v-show="activeName == '4'"></div>
        <div v-show="activeName == '5'">
          <el-upload
            v-model:file-list="fileList"
            action="https://shop.h888.fun/adminapi/v1/goods/uploadImg"
            ref="goods_gallery"
            list-type="picture-card"
            :on-success="handleGoodsGallerySuccess"
            :before-remove="beforeGoodsGalleryRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
        <div v-show="activeName == '6'">
          <el-transfer
            v-model="value"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="State Abbreviations"
            :data="data"
          />
        </div>
        <div v-show="activeName == '7'">
          <el-transfer
            v-model="value"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="State Abbreviations"
            :data="data"
          />
        </div>
        <div v-show="activeName == '8'">
          <el-transfer
            v-model="value"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="State Abbreviations"
            :data="data"
          />
        </div>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClose">關閉</el-button>
        <el-button type="primary" @click="handleSubmit(formRef)"
          >送出</el-button
        >
      </div>
    </template>
  </el-drawer>
</template>

<style lang="less"></style>
