<template>
  <div>
    <el-dialog title="类别管理" v-model="dialogVisible">
      <div>
        <el-form ref="formDataRef" :model="formData" label-width="120px">
          <el-form-item
            label="类别名称"
            prop="name"
            :rules="[{ required: true, message: '请输入类别名称' }]"
          >
            <el-input
              v-model="formData.name"
              placeholder="请输入类别名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="封面"
            required
            prop="icon"
            :rules="[{ validator: validateIcon, trigger: 'blur' }]"
          >
            <UploadOnlyImage
              v-model:url="formData.icon"
              :key="coverKey"
              type="image"
            />
          </el-form-item>
          <el-form-item
            label="关联知识库板块"
            prop="icon"
            :rules="[{ required: true, message: '请选择板块' }]"
            v-if="props.rowData?.id && props.rowData?.name == '政策'"
          >
            <el-select v-model="formData.moduleId" placeholder="请选择板块">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in articleList"
                :key="item.sn"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineProps, defineEmits, watch, reactive } from "vue";
import UploadOnlyImage from "@/components/UploadOnlyImage.vue";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { request } from "@/utils";
import { ElMessage } from "element-plus";
import { nextTick } from "process";
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const formData = ref({
  name: "",
  icon: [],
  moduleId: ""
});
const validateIcon = (rule: any, value: any, callback: any) => {
  console.log(value);

  if (!formData.value.icon.length) {
    callback(new Error("请上传封面"));
  } else {
    callback();
  }
};
const formDataRef = ref();
const articleList = ref([]);
const coverKey = ref(Date.now());

const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },

  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      initData();
      if (props.rowData.id) {
        console.log(props.rowData);
        let { icon } = props.rowData;
        formData.value = {
          ...props.rowData,
          icon: icon
            ? [
                {
                  name: "food.jpeg",
                  url: icon
                }
              ]
            : []
        };
      }
      console.log(formData.value);
    } else {
      nextTick(onReset);
    }
  }
);
const getArticleList = () => {
  // articleService/module/paginate
  request
    .get("articleService/module/paginate", {
      params: {
        page: 1,
        pageSize: 1000
      }
    })
    .then(resp => {
      articleList.value = resp.data.list;
    });
};

const onReset = () => {
  formDataRef.value.resetFields();
  formData.value.icon = [];
  formData.value.name = "";
  formData.value.moduleId = "";

  coverKey.value++;
};
const handleSubmit = () => {
  formDataRef.value.validate((valid, fields) => {
    if (!valid) return;
    let params = {
      id: formData.value?.id,
      name: formData.value?.name,
      moduleId: formData.value?.moduleId || undefined,
      icon: formData.value?.icon[0].url
    };
    let api = props.rowData.id
      ? "articleService/demand/category/update"
      : "articleService/demand/category";
    request.post(api, params).then(resp => {
      ElMessage.success(resp.message);
      dialogVisible.value = 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 initData = () => {
  getArticleList();
};
</script>
<style lang="scss" scoped></style>
