<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请填写标签名称"></el-input>
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker
            v-model="form.model.color"
            placeholder="请选择标签颜色"
          ></el-color-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.model.description"
            type="textarea"
            :rows="3"
            placeholder="请填写标签描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.model.sort" placeholder="请填写排序"></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" type="primary" @click="confirm">保存</el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">更新</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { cloneDeep } from 'lodash';
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../user.service';
  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      name: '',
      color: '#409EFF',
      description: '',
      sort: '0',
    },
    rules: {
      name: [{ required: true, message: '请填写标签名称', trigger: 'blur' }],
      color: [{ required: true, message: '请选择标签颜色', trigger: 'change' }],
      sort: [{ required: true, message: '请填写排序', trigger: 'blur' }],
    },
  });
  const loading = ref(false);
  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { code, data } = await api.tag.detail(id);
    code == '200' && (form.model = data);
    loading.value = false;
  }
  // 表单关闭时提交
  async function confirm() {
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = cloneDeep(form.model);
      const { code } =
        props.modal.params.type == 'add'
          ? await api.tag.add(submitForm)
          : await api.tag.edit(props.modal.params.id, submitForm);
      if (code == '200') {
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }
  async function init() {
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
  }
  onMounted(() => {
    init();
  });
</script>
