<template>
  <div>
    <el-dialog title="推荐商品设置" v-model="dialogVisible">
      <div>
        <el-form
          :model="state.ruleForm"
          :rules="state.rules"
          ref="formRef"
          label-width="100px"
          class="good-form"
        >
          <el-form-item required label="商品名称" prop="goodsId">
            <el-select
              style="width: 300px"
              v-model="state.ruleForm.goodsId"
              filterable
              clearable
              placeholder="请选择商品"
              @change="handleChangeGoods"
            >
              <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="redirectUrl">
            <el-input
              style="width: 300px"
              v-model="state.ruleForm.redirectUrl"
              placeholder="请输入跳转链接"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input
              style="width: 300px"
              v-model="state.ruleForm.name"
              placeholder="请输入商品名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="排序值" prop="rank">
            <el-input
              style="width: 300px"
              v-model="state.ruleForm.rank"
              placeholder="请输入排序值"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, defineEmits, nextTick, computed, watch } from "vue";
import { request } from "@/utils";
import { ElMessage } from "element-plus";
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  id: {
    default: undefined
  },
  configId: {
    default: undefined
  }
});
const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  async n => {
    if (n) {
      await getGoodList();
      getGoodsDetail();
    } else {
      nextTick(() => {
        formRef.value.resetFields();
      });
    }
  }
);
const formRef = ref(null);
const state = reactive({
  ruleForm: {
    goodsId: "",
    redirectUrl: "",
    rank: "",
    name: ""
  },
  rules: {
    goodsId: [{ required: "true", message: "请选择商品", trigger: ["change"] }]
  },
  goodsList: []
});

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

const getGoodsDetail = () => {
  if (!props.id) return;
  request
    .get(`/mallService/mechanism/indexConfigs/goods/${props.id}`)
    .then(resp => {
      let { name, goodsId, redirectUrl, rank } = resp.data;
      state.ruleForm.name = name;
      state.ruleForm.goodsId = goodsId;
      state.ruleForm.redirectUrl = redirectUrl;
      state.ruleForm.rank = rank;
    });
};

const handleChangeGoods = id => {
  let detail = state.goodsList.find(v => v.goodsId == id);
  state.ruleForm.name = detail?.goodsName;
};
const submitForm = () => {
  formRef.value.validate(valid => {
    if (!valid) return;
    let params = {
      ...state.ruleForm,
      goodsId: Number(state.ruleForm.goodsId),
      rank: Number(state.ruleForm.rank),
      configId: props.configId
    };
    if (!params.name) {
      state.goodsList;
      params.name = state.goodsList.find(v => {
        state.ruleForm.goodsId == v.goodsId;
      })?.goodsName;
    }
    if (props.id) {
      params.id = props.id;
      request
        .put("/mallService/mechanism/indexConfigs/goods", params)
        .then(resp => {
          ElMessage.success(resp.message);
          dialogVisible.value = false;
          emits("success");
        });
    } else {
      request
        .post("/mallService/mechanism/indexConfigs/goods", params)
        .then(resp => {
          ElMessage.success(resp.message);
          dialogVisible.value = false;
          emits("success");
        });
    }
  });
};
</script>
