<template>
  <div>
    <el-dialog
      :title="props.id ? '编辑店铺' : '添加店铺'"
      v-model="dialogVisible"
    >
      <div class="add">
        <el-card class="add-container" shadow="never">
          <el-form
            :model="state.storeForm"
            :rules="state.rules"
            ref="goodRef"
            label-width="100px"
            readonly
            :disabled="isPreview"
            class="storeForm"
          >
            <el-form-item label="店铺类型" prop="type">
              <el-select
                v-model="state.storeForm.type"
                placeholder="请选择店铺类型"
                filterable
                clearable
                disabled
              >
                <el-option label="自营" :value="0" />
                <el-option label="第三方服务商" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="店铺所属" prop="staffId">
              <!-- <el-cascader
            :placeholder="state.defaultCate"
            style="width: 400px"
            :props="state.category"
            @change="handleChangeCate"
          ></el-cascader> -->
              <el-select
                v-model="state.storeForm.staffId"
                filterable
                clearable
                placeholder="请选择服务商"
                disabled
              >
                <el-option
                  v-for="item in state.processors"
                  :key="item.sn"
                  :label="item.nickname"
                  :value="item.staffId"
                >
                  <el-text>{{ item.nickname }}</el-text>
                  <el-tag class="ml-2">{{ item.sn }}</el-tag>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="店铺名称" prop="name">
              <el-input
                style="width: 400px"
                v-model="state.storeForm.name"
                placeholder="请输入店铺名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="营业时间" prop="serveTime">
              <el-input
                style="width: 400px"
                v-model="state.storeForm.serveTime"
                placeholder="请输入营业时间，如：周一至周五，10:00-21:00"
              ></el-input>
            </el-form-item>
            <el-form-item label="客服电话" prop="hotline">
              <el-input
                style="width: 400px"
                v-model="state.storeForm.hotline"
                placeholder="请输入客服电话"
              ></el-input>
            </el-form-item>
            <el-form-item label="店铺地址" prop="address">
              <el-input
                style="width: 400px"
                v-model="state.storeForm.address"
                placeholder="请输入店铺地址"
              ></el-input>
            </el-form-item>
            <el-form-item required label="店铺logo" prop="logo">
              <div>
                <UploadOnlyImage
                  v-model:url="state.storeForm.logo"
                  :key="coverKey"
                  type="image"
                  isSimple
                  :isPreview="isPreview"
                  :limit="1"
                />
                <div>
                  <el-text>说明：支持png、jpg图片，建议尺寸：128*128</el-text>
                </div>
              </div>
            </el-form-item>
            <el-form-item required label="店铺图片" prop="images">
              <div>
                <UploadOnlyImage
                  v-model:url="state.storeForm.images"
                  :key="coverKey"
                  type="image"
                  :isPreview="isPreview"
                />
                <!-- <UploadImage
                  v-model:url="state.storeForm.images"
                  :key="coverKey"
                  type="image"
                /> -->
                <div>
                  <el-text
                    >说明：支持png、jpg图片，建议尺寸：375*200
                    ，最多上传9张，第一张默认为主图</el-text
                  >
                </div>
              </div>
            </el-form-item>

            <el-form-item label="店铺简介" prop="intro">
              <el-input
                style="width: 400px"
                type="textarea"
                :rows="5"
                v-model="state.storeForm.intro"
                placeholder="请输入店铺简介"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="!isPreview">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitAdd()">{{
                props.id ? "立即修改" : "立即创建"
              }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  reactive,
  computed,
  defineProps,
  defineEmits,
  watch,
  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 UploadOnlyImage from "@/components/UploadOnlyImage.vue";
import UploadImage from "@/components/UploadImage.vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
const channelId = useUserStoreHook()?.profile.id;
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  id: {
    type: Number
  }
});
const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});
const isPreview = computed(() => {
  return false;
  return state.detail?.type == 1;
});
const goodRef = ref(null);

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      getStaff();

      getDetail();
    } else {
      goodRef?.value?.resetFields();
    }
  }
);
watch(
  () => props.id,
  n => {
    getDetail();
    getStaff();
  }
);

const { proxy } = getCurrentInstance();
const coverKey = ref(Date.now());
const editor = ref(null);
const route = useRoute();
const router = useRouter();
const { id } = route.query;

const state = reactive({
  detail: {},
  id: id,
  defaultCate: "",
  storeForm: {
    type: 0, // 类型
    staffId: "", // 服务商
    name: undefined,
    serveTime: "",
    hotline: "",
    address: "",
    logo: [],
    intro: "",
    images: []
  },
  processors: [],
  rules: {
    name: [
      { required: "true", message: "请填写店铺名称", trigger: ["change"] }
    ],
    type: [
      { required: "true", message: "请选择店铺类型", trigger: ["change"] }
    ],
    staffId: [
      { required: "true", message: "请选择服务商", trigger: ["change"] }
    ],
    serveTime: [
      { required: "true", message: "请填写店铺营业时间", trigger: ["change"] }
    ],
    hotline: [
      { required: "true", message: "请填写客服电话", trigger: ["change"] }
    ],
    address: [
      { required: "true", message: "请填写店铺地址", trigger: ["change"] }
    ],
    logo: [
      { required: "true", message: "请上传店铺LOGO", trigger: ["change"] }
    ],
    images: [
      { 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 staffInfo = ref({});
const categoryList = ref([]);
let instance;
onMounted(async () => {
  // getProcessors();

  await initCategory();
  if (id) {
    request.get(`/mallService/mechanism/goods/${id}`).then(res => {
      const { goods, firstCategory, secondCategory, thirdCategory, category } =
        res?.data;
      state.storeForm = {
        name: goods.name,
        intro: goods.intro,
        originalPrice: goods.originalPrice / 100,
        sellingPrice: goods.sellingPrice / 100,
        stockNum: goods.stockNum,
        goodsSellStatus: String(goods.goodsSellStatus),
        logo: goods.logo,
        tag: goods.tag,
        goodsDetailContent: goods.goodsDetailContent,
        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 getDetail = () => {
  if (!props.id) {
    return;
  }
  request
    .get(`/articleService/serviceProvider/shop?id=${props.id}`)
    .then(resp => {
      state.detail = resp.data;
      state.storeForm = {
        ...resp.data,
        logo: [{ url: resp.data.logo, name: "logo" }],
        images: resp.data.images.map((v, i) => {
          return {
            url: v,
            name: "images" + i,
            status: "success",
            uid: new Date().getTime()
          };
        })
      };
      console.log(state.storeForm);
    });
};

const getStaff = () => {
  request
    .get("/articleService/serviceProvider/staff", {
      params: {
        mechanismId: channelId
      }
    })
    .then(resp => {
      staffInfo.value = resp.data;
      state.storeForm.staffId = resp.data.staffId;
      state.processors = [resp.data];
    });
};
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 = {
        ...state.storeForm,
        logo: state.storeForm.logo[0].url,
        images: state.storeForm.images.map(v => v.url)
      };
      if (props.id) {
        // 修改店铺使用 put 方法
        request
          .post("/articleService/serviceProvider/shop/update", params)
          .then(resp => {
            ElMessage.success(resp.message);
            dialogVisible.value = false;
            emits("success");
          });
      } else {
        request
          .post("/articleService/serviceProvider/shop", params)
          .then(resp => {
            ElMessage.success(resp.message);
            // router.push({ path: "/shop/store" });
            dialogVisible.value = false;
            emits("success");
          });
      }
    }
  });
};

const getProcessors = () => {
  request.get("/articleService/demand/processors").then(resp => {
    state.processors = resp.data;
  });
};
</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>
