<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="标题" v-bind="validateInfos.title">
            <a-input v-model:value="formData.title" placeholder="请输入标题"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="文章类型">
            <a-radio-group v-model:value="formData.type" button-style="solid" :disabled="disabled">
              <a-radio-button value="1">招生章程</a-radio-button>
              <a-radio-button value="2">高考动态</a-radio-button>
              <a-radio-button value="3">校内资讯</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="院校id" v-bind="validateInfos.schoolId">
            <a-input v-model:value="formData.schoolId" placeholder="请输入院校id"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="院校名称" v-bind="validateInfos.schoolName">
            <a-input v-model:value="formData.schoolName" placeholder="请输入院校名称"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="发布者" v-bind="validateInfos.author">
            <a-input v-model:value="formData.author" placeholder="请输入发布者"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="发布日期" v-bind="validateInfos.releaseTime">
            <a-date-picker placeholder="请选择发布日期" v-model:value="formData.releaseTime"
                           showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"
                           :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="年份" v-bind="validateInfos.year">
            <a-input v-model:value="formData.year" placeholder="请输入年份"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="阅读量" v-bind="validateInfos.viewCount">
            <a-input-number v-model:value="formData.viewCount" placeholder="请输入阅读量"
                            style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <Tinymce v-model="articleContent" @change="handleTinymceChange" width="100%"/>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted} from 'vue';
import {defHttp} from '/@/utils/http/axios';
import {useMessage} from '/@/hooks/web/useMessage';
import {getValueType} from '/@/utils';
import {saveOrUpdate} from '../YxArticle.api';
import {Form} from 'ant-design-vue';
import {Tinymce} from '/@/components/Tinymce/index';
import form from "/@/views/demo/form/index.vue";
import {getMenuListResultModel} from "/@/api/sys/model/menuModel";

const props = defineProps({
  formDisabled: {type: Boolean, default: false},
  formData: {
    type: Object, default: () => {
    }
  },
  formBpm: {type: Boolean, default: true}
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  title: '',
  type: '1',
  schoolId: '',
  schoolName: '',
  author: '',
  releaseTime: '',
  year: '',
  viewCount: undefined,
});
const {createMessage} = useMessage();
const labelCol = ref<any>({xs: {span: 24}, sm: {span: 5}});
const wrapperCol = ref<any>({xs: {span: 24}, sm: {span: 16}});
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {};
const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: true});

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});


/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  articleContent.value = ''
  console.log(formData)
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, record);
    if (formData.id) {
      getContent()
    }else{
      articleContent.value = ''
    }
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  model.content = articleContent.value
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

onMounted(() => {
  console.log(`the component is now mounted.`)
})
function getContent() {
  let params = {id: formData.id}
  defHttp.get({url: '/yx/yxArticle/queryById', params})
    .then((res) => {
    console.log(res)
    articleContent.value = res.content
  });
}

const articleContent = ref('');

function handleTinymceChange(value: string) {
  formData.articleContent = value
  console.log(value);
}

defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
