<template>
  <!-- 新增编辑 -->
  <common-modal
    width="80%"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    :maxable="true"
    :title="isUpdate ? '编辑新闻' : '新建新闻'"
    :body-style="{ padding: '16px 24px', height: '70vh', overflow: 'hidden' }"
    @update:visible="updateVisible"
    wrapClassName="project-modal"
  >
    <NewForm v-model:form="form" ref="newFormRef" :designId="props.designId" :isUpdate="isUpdate"></NewForm>

    <template #footer>
      <div class="model-footer">
        <div class="model-footer-checkbox">
          <a-checkbox v-model:checked="nextChecked" style="color: #898e91" v-if="!isUpdate">继续创建下一条</a-checkbox>
        </div>
        <a-space>
          <a-button class="border-radius grey" @click="updateVisible(false)" type="link">取消</a-button>
          <a-button class="border-radius" type="primary" @click="save">确定</a-button>
        </a-space>
      </div>
    </template>
  </common-modal>
</template>

<script setup name="NewAddEdit">
import { ref, onMounted, defineAsyncComponent, computed } from 'vue';
import { message } from 'ant-design-vue';
import { NewApi } from '../api/NewApi';
import { useUserStore } from '@/store/modules/user';
import { FileApi } from '@/views/system/backend/file/api/FileApi';
import { getNowTime } from '@/utils/common/util';

const NewForm = defineAsyncComponent(() => import('./new-form.vue'));

const props = defineProps({
  visible: Boolean,
  data: Object,
  designId: String,
  currentCategory: Object
});

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 是否是编辑状态
const isUpdate = ref(false);
// 表单数据
const form = ref({
  iconList: [],
  fileList: [],
  fileIdList: [],
  newsSort: 100,
  newsStatus: 2,
  newsTopFlag: 'N',
  newsType: 10,
  showPublishTime: getNowTime(),
  designId: props.designId,
  newsCategoryId: props.currentCategory?.categoryId
});
// ref
const newFormRef = ref(null);

const nextChecked = ref(false);

const userStore = useUserStore();

const userinfo = computed(() => {
  return userStore.info;
});

onMounted(async () => {
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    isUpdate.value = false;
    if (userinfo.value?.realName) {
      form.value.showPublishUser = userinfo.value.realName;
      form.value.showPhotoUser = userinfo.value.realName;
    }
  }
});

// 获取详情
const getDetail = () => {
  NewApi.detail({ newsId: props.data.newsId }).then(res => {
    form.value = Object.assign(form.value, res);
    form.value.fileList = [];
    form.value.iconList = [];
    if (res.businessFileInfoList?.length > 0) {
      form.value.fileList = res.businessFileInfoList.map(item => {
        return { ...item, uid: item.fileId, name: item.fileOriginName, response: '{"status": "success"}' };
      });
      form.value.fileIdList = res.businessFileInfoList.map(item => item.fileId);
    }
    if (res.coverFileId) setFileList('iconList', [res.coverFileId]);
  });
};

// 设置文件列表
const setFileList = (name, fileIdList) => {
  FileApi.getAntdVInfoBatch({ fileIdList: fileIdList }).then(res => {
    res.data.forEach((item, index) => {
      item.fileId = fileIdList[index];
      item.uid = item.fileId;
    });
    form.value[name] = [...res.data];
  });
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  newFormRef.value.$refs.formRef.validate().then(async valid => {
    if (valid) {
      if (form.value.iconList?.length) {
        form.value.coverFileId = form.value.iconList[0]?.response?.data?.fileId
          ? form.value.iconList[0]?.response?.data?.fileId
          : form.value.iconList[0]?.uid;
      }
      // 修改加载框为正在加载
      loading.value = true;
      let result = null;

      // 执行编辑或修改
      if (isUpdate.value) {
        result = NewApi.edit(form.value);
      } else {
        result = NewApi.add(form.value);
      }
      result
        .then(async result => {
          loading.value = false;
          message.success(result.message);
          if (nextChecked.value) {
            form.value.fileIdList = [];
            form.value.fileList = [];
            form.value.iconList = [];
            form.value.content = '';
            form.value.title = '';
          } else {
            updateVisible(false);
          }
          emits('done', form.value);
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
</script>

<style scoped lang="less">
.model-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
