<template>
  <el-dialog
    :title="type == 'add' ? '添加轮播图' : '修改轮播图'"
    v-model="state.visible"
    width="50%"
  >
    <el-form
      :model="state.ruleForm"
      :rules="state.rules"
      ref="formRef"
      label-width="100px"
      class="good-form"
    >
      <el-form-item label="图片" prop="url">
        <!-- <el-upload
          class="avatar-uploader"
          :action="state.uploadImgServer"
          accept="jpg,jpeg,png"
          :headers="{
            token: state.token
          }"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-success="handleUrlSuccess"
        >
          <img style="width: 200px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.ruleForm.url" :src="state.ruleForm.url" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload> -->
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="simpleImgHttpUpload"
        >
          <img
            v-if="state.ruleForm.url"
            :src="state.ruleForm.url"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item required label="商品名称">
        <el-select
          style="width: 300px"
          v-model="state.goodsId"
          @change="handleChangeGoods"
          filterable
          clearable
          placeholder="请选择商品"
        >
          <el-option
            v-for="item in state.goodsList"
            :key="item.goodsId"
            :label="`${item.goodsName}(ID: ${item.mechanismId}) `"
            :value="item.goodsId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跳转链接" prop="link">
        <el-input type="primary" link v-model="state.ruleForm.link"></el-input>
      </el-form-item>
      <el-form-item label="排序值" prop="sort">
        <el-input type="number" v-model="state.ruleForm.sort"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, defineEmits, nextTick } from "vue";
import { request, uploadToOSS } from "@/utils";
// import { localGet, uploadImgServer } from '@/utils'
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useUserStoreHook } from "@/store/modules/user";
const { VITE_APP_H5 } = import.meta.env;
import UploadImage from "@/components/UploadImage.vue";

const channelId = useUserStoreHook()?.profile.id;

const props = defineProps({
  type: String,
  reload: Function
});
const emits = defineEmits(["success"]);
const formRef = ref(null);
const state = reactive({
  visible: false,
  goodsId: "",
  ruleForm: {
    url: "",
    link: "",
    sort: ""
  },
  rules: {
    url: [{ required: "true", message: "图片不能为空", trigger: ["change"] }],
    link: [
      { required: "true", message: "跳转链接不能为空", trigger: ["change"] }
    ],
    sort: [{ required: "true", message: "排序不能为空", trigger: ["change"] }]
  },
  id: "",
  goodsList: []
});

// 获取详情
const getDetail = id => {
  request.get(`/mallService/mechanism/carousels/${id}`).then(res => {
    state.ruleForm = {
      url: res.data.carouselUrl,
      link: res.data.redirectUrl,
      sort: res.data.carouselRank
    };
  });
};

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.ruleForm.url = val.data || "";
};
// 开启弹窗
const open = id => {
  state.visible = true;
  getGoodList();
  nextTick(() => {
    formRef.value.resetFields();
  });
  if (id) {
    state.id = id;
    getDetail(id);
  } else {
    state.ruleForm = {
      url: "",
      link: "",
      sort: ""
    };
  }
};
// 关闭弹窗
const close = () => {
  state.visible = false;
};
const submitForm = () => {
  console.log(formRef.value.validate);
  formRef.value.validate(valid => {
    if (valid) {
      if (props.type == "add") {
        request
          .post("/mallService/mechanism/carousels", {
            carouselUrl: state.ruleForm.url,
            redirectUrl: state.ruleForm.link,
            carouselRank: Number(state.ruleForm.sort)
          })
          .then(() => {
            ElMessage.success("添加成功");
            state.visible = false;
            emits("success");
          });
      } else {
        request
          .put("/mallService/mechanism/carousels", {
            carouselId: state.id,
            carouselUrl: state.ruleForm.url,
            redirectUrl: state.ruleForm.link,
            carouselRank: Number(state.ruleForm.sort)
          })
          .then(() => {
            ElMessage.success("修改成功");
            state.visible = false;
            emits("success");
          });
      }
    }
  });
};
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.ruleForm.url = resp;
  });
};

// 获取商品列表
const getGoodList = () => {
  return new Promise(resolve => {
    request
      .get("/mallService/mechanism/goods/list", {
        params: {
          page: 1,
          pageSize: 1000
        }
      })
      .then(resp => {
        state.goodsList = resp.data.list;
      });
  });
};

const handleChangeGoods = id => {
  let url = `${VITE_APP_H5}/#/${channelId}/shop/productDetail?id=${id}`;
  state.ruleForm.link = url;
  // let detail = state.goodsList.find(v => v.goodsId == id);
};

defineExpose({ open, close });
</script>

<style scoped lang="scss">
.avatar-uploader {
  color: #ddd;
  font-size: 30px;
  width: 178px;
  height: 178px;
  text-align: center;
}
::v-deep .avatar-uploader .el-upload {
  width: 100%;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 10px;
}
.avatar-uploader-icon {
  display: block;
  width: 178px;
  height: 178px;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
}
</style>
