<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form :model="dataForm" label-width="120px" ref="form" v-loading="loading" class="pr-6">
      <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '标题必须填写' }]">
        <el-input class="item" v-model="dataForm.title" name="title" clearable />
      </el-form-item>
      <el-form-item label="通知类型" prop="notice_type_id" :rules="[{ required: true, message: '请选择通知类型' }]">
        <div class="type-wrapper">
          <el-select v-model="dataForm.notice_type_id" filterable remote clearable :remote-method="remoteNoticeMethod">
            <el-option v-for="item in noticesTypes" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button type="text" size="default" class="btn" @click="addType"
            v-action="'system.NoticeTypes.add'">添加类型</el-button>
        </div>
      </el-form-item>
      <el-form-item label="通知人群类型" prop="type" :rules="[{ required: true, message: '请选择通知人群类型' }]">
        <el-radio-group @change="typeChange" :disabled="isDisabled" v-model="dataForm.type">
          <el-radio label="1">全部</el-radio>
          <el-radio label="2">指定人群</el-radio>
          <el-radio label="3">指定角色</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知人群" prop="notice_obj" v-if="dataForm.type != 1"
        :rules="[{ required: true, message: '请选择通知人群' }]">
        <el-select style="width:300px;" :disabled="isDisabled" multiple v-model="dataForm.notice_obj" filterable remote
          clearable :remote-method="remoteMethod" value-key="id">
          <el-option v-for="item in noticeObjOptions" :key="item.id" :label="item.name" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否首页弹窗" prop="is_popup" :rules="[{ required: true, message: '请设置是否首页弹窗' }]">
        <el-switch :disabled="isDisabled" v-model="dataForm.is_popup" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="排序" prop="sort" :rules="[{ required: true, message: '请输入排序' }]">
        <el-input-number v-model="dataForm.sort" :step="1" />
      </el-form-item>
      <el-form-item label="内容" prop="content" :rules="[{ required: true, message: '请输入内容' }]">
        <editor height="500" :modelValue="dataForm.content" @update:modelValue="contentChange"></editor>
      </el-form-item>
      <div class="flex justify-start ml-9">
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitFormChange(form)">确认</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { useCreate } from '@/hook/curd/useCreate';
import { useShow } from '@/hook/curd/useShow';
import { onMounted, ref } from 'vue';
import { noticesTypesList, noticesObjOption, noticesEdit, noticesAdd, noticesTypesAdd } from '@/api/notice/index';
import { FormInstance } from 'element-plus';
const emit = defineEmits(['close']);
const isDisabled = computed(() => Boolean(props.primary));
const noticeObjOptions = ref([]);
const noticesTypes = ref([]);
const dataForm = ref({})

const props = defineProps({
  primary: String | Number | Object,
  api: String,
});

const contentChange = (e) => {
  // console.log(e);
  dataForm.value.content = e
}
const cancel = () => {
  emit('close')
}

const typeChange = (e) => {
  console.log(e);
  dataForm.value.notice_obj = []
  if (dataForm.value.type != 1) {
    initTypeOtion({ type: e })
  }
}
// 初始化类型
const initTypeOtion = (params: object) => {
  noticesObjOption(params).then(res => {
    noticeObjOptions.value = res.data
  })
}
const remoteMethod = (query: string) => {
  if (query) {
    initTypeOtion({ type: dataForm.value.type, name: query })
  } else {
    initTypeOtion({ type: dataForm.value.type, name: query })
  }
}

// 初始化通知人群
const initNoticeOtion = (params: object) => {
  noticesTypesList(params).then(res => {
    noticesTypes.value = res.data
  })
}
const remoteNoticeMethod = (query: string) => {
  if (query) {
    initNoticeOtion({ name: query })
  } else {
    initNoticeOtion({})
  }
}


// 动态添加通知类型
const addType = () => {
  const typeName = ref()
  ElMessageBox({
    title: '添加类型',
    message: () =>
      h(ElInput, {
        modelValue: typeName.value,
        'onUpdate:modelValue': (val) => {
          typeName.value = val
        },
      }),
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        noticesTypesAdd({ name: typeName.value }).then(res => {
          console.log(res);
          ElMessage.success(res.message || '设置成功')
          initNoticeOtion({})
        })
        console.log(typeName.value);
      }
      done()
    }
  });
}

const {
  formData,
  form,
  loading,
  submitForm,
  close,
} = useCreate(props.api, props.primary);
const submitFormChange = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate(valid => {
      if (valid) {
        if (props.primary) {
          noticesEdit(dataForm.value.id, { ...dataForm.value }).then(res => {
            console.log(res);
            ElMessage.success(res.message || '设置成功')
            emit('close')
          })
        } else {
          noticesAdd({ ...dataForm.value }).then(res => {
            console.log(res);
            ElMessage.success(res.message || '设置成功')
            emit('close')
          })
        }

      } else {
        console.log('noooooo');
        loading.value = false;
      }
    })
    .then(() => { });
}

if (props.primary) {
  console.log(props.primary, 'props.primary');
  // dataForm.value = props.primary
  // console.log(dataForm.value, 'dataForm.valuedataForm.valuedataForm.value');
  const { afterShow } = useShow(props.api, props.primary, formData);
  afterShow.value = formData => {
    const data = unref(formData);
    console.log(data, 'formDataformData');
    dataForm.value = {
      id: data.id,
      title: data.title,
      notice_type_id: data.notice_type_id,
      type: data.type,
      is_popup: data.is_popup,
      content: data.content,
      notice_obj: data.notice_obj,
      sort: data.sort
    }
    if (dataForm.value.type != 1) {
      initTypeOtion({ type: dataForm.value.type })
    }
  };
} else {
  dataForm.value = {
    title: "",
    notice_type_id: "",
    type: "1",
    is_popup: 0,
    content: "",
    notice_obj: [],
    sort: 1
  }
}

onMounted(() => {
  initNoticeOtion({})
  close(() => emit('close'));
});
</script>
<style scoped lang="scss">
.item {
  width: 300px;
}

.type-wrapper {
  width: 80%;
  display: flex;

  .btn {
    margin: 0 6px;
  }
}
</style>
