<template>
  <!-- Modal -->
  <a-modal v-model:visible="modalVisible" fullscreen :title="title" title-align="start" :footer="false"
    @cancel="handleClose">
    <div class="titlebox">
      <div class="bar"></div>
      <div class="name">文章信息</div>
    </div>
    <a-form :model="modalForm" ref="modalFormRef" :auto-label-width="true" :rules="rules">
      <a-row :gutter="24" style="margin-top: 35px">
        <a-col :span="12">
          <a-form-item field="article_title" label="文章标题：">
            <a-input v-model="modalForm.article_title" placeholder="请输入文章标题" :style="{ width: '250px' }"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="article_status" label="文章状态：">
            <a-select v-model="modalForm.article_status" placeholder="请选择文章状态" :style="{ width: '182px' }">
              <a-option :value="1">正常</a-option>
              <a-option :value="2">禁用</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">

          <a-form-item field="is_top" label="是否置顶：">
            <a-select v-model="modalForm.is_top" placeholder="请选择是否置顶" :style="{ width: '182px' }">
              <a-option :value="1">是</a-option>
              <a-option :value="0">否</a-option>
            </a-select>

          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="source_id" label="文章来源：">
            <a-select v-model="modalForm.source_id" placeholder="请选择文章来源"
              :style="{ width: '200px' }">

              <a-option size="large" style="max-width:500px" v-for="item in originList" :key="item.source_id"
                :value="item.source_id" :label="item.source_name">
                {{ item.source_name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="article_url" label="文章地址：">
            <a-input v-model="modalForm.article_url" placeholder="请输入文章地址" :style="{ width: '250px' }"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="article_image" label="文章图片：">
            <a-space size="large">
              <a-image fit="cover" width="80" height="80" class="headImg" :src="modalForm.article_image">
              </a-image>
            </a-space>
            <a-upload action="/" :fileList="file ? [file] : []" class="upload" :auto-upload="false"
              @change="onChangeFile" accept="image/*" @before-upload="beforeUpload" :show-file-list="false"
             />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="sort" label="排序值：">
            <a-input-number mode="button" :min="0" v-model="modalForm.sort" placeholder="请输入排序" :style="{ width: '180px' }"></a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="article_science_class" label="文章分类：">
            
            <a-select multiple allow-search value-key="basic_class_name" v-model="modalForm.article_science_class" placeholder="请选择文章分类"
              :style="{ width: '300px' }" @search="handelAllList">

              <a-option size="large" style="max-width:500px" v-for="item in classifyList" :key="item.basic_class_id"
                :value="item" :label="item.basic_class_name">
                {{ item.basic_class_name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider />
    </a-form>
    <div class="titlebox">
      <div class="bar"></div>
      <div class="name">操作</div>
    </div>
    <a-row :gutter="24" style="margin-top: 35px">
      <a-col :span="24">
        <a-form-item field="" label="" no-style>
          <a-space>
            <a-button type="primary" @click="handleSubmit" v-has="'admin:sysArticleList:save'">保存</a-button>
          </a-space>
        </a-form-item>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script setup>
import { ref, toRefs, watch, getCurrentInstance } from 'vue';
import { getAllClassifyList, addArticle, editArticle,getAllOriginList } from '@/api/kepu/list';
import { ossSign, ossUpload } from '@/api/oss';
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance();
const file = ref();
const props = defineProps({
  // 是否显示
  modalVisible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: '',
  },
  modalForm: {
    type: Object,
  },
});
const title = ref('');
const emits = defineEmits(['familyVisibleChange', 'freshDetail']);
const { modalVisible, modalForm } = toRefs(props);
const classifyList = ref([]);
const originList = ref([]);
//获取区域列表
const handelAllList = (value) => {
  console.log(value);
  getAllClassifyList({
    basic_class_name: value
  }).then((res) => {
    const { data, code, message } = res;
    if (code == 200) {
      classifyList.value = data
    }
  });
};
const handelOriginAllList = (value) => {

  getAllOriginList({
    basic_class_name: value
  }).then((res) => {
    const { data, code, message } = res;
    if (code == 200) {
      originList.value = data
    }
  });
};

watch(
  () => props.id,
  () => {
    if (props.id) {
      title.value = '编辑文章信息';
   
    } else {
      title.value = '修改文章信息';
    }
  },
  { immediate: true }
);

const rules = {
  article_title: [{ required: true, message: '请输入文章标题' }],
  article_status: [{ required: true, message: '请选择文章状态' }],
  is_top: [{ required: true, message: '请选择是否置顶' }],
  article_url: [{ required: true, message: '请输入文章地址' }],
  article_image: [{ required: true, message: '请上传文章图片' }],
  source_id: [{ required: true, message: '请选择文章来源' }],
  sort: [{ required: true, message: '请输入排序值' }],
  article_science_class: [{ type:'array',required: true, message: '请选择文章分类' }],
};
const handleSubmit = () => {
  proxy.$refs.modalFormRef.validate(async (valid) => {
    let data = null;
    let {
      article_title,
      article_status,
      is_top,
      article_image,
      source_id,
      article_url,
      article_science_class,
      sort
    } = modalForm.value;
    if (!valid) {
      if (props.id) {
       console.log( article_science_class)
        data = await editArticle(props.id, {
          article_title,
          article_status,
          is_top,
          article_image,
          source_id,
          article_url,
          article_science_class,
          sort:sort===''?1:sort,        
        });
      } else {
        data = await addArticle({
          article_title,
          article_status,
          is_top,
          article_image,
          source_id,
          article_url,
          article_science_class,
          sort:sort===''?1:sort,
        });
      }
      if (data.code == 200) {
        props.id
          ? proxy.$message.success('修改成功')
          : proxy.$message.success('添加成功');
        emits('freshDetail');
      }
      handleClose();
      emits('freshDetail');
    } else {
      console.log(valid);
      proxy.$message.error('表单校验失败');
      //done(false);
    }
  });
};
const onChangeFile = (fileList) => {

getOssSign(4, fileList[0].file);
}
const beforeUpload = (file, type) => {
    return new Promise((resolve, reject) => {
      if (file.size >= 10 * 1024 * 1024) {
        proxy.$notification.error("图片大小不能超过10M");
        reject('cancel')
      } else {
        resolve(true)
      }
    });
  };
  const getOssSign = async (scene, File) => {
    const { data, code, message } = await ossSign({
      user_type: 4,
      scene,
    });
    if (code == 200) {
      let { access_id, dir, policy, signature, host } = data;
      //let index = File.lastIndexOf("/");
      let filename = File.name;
      let time = dayjs().format("YYYYMMDDHHmmss")
      let formData = new FormData();
      formData.append('OSSAccessKeyId', access_id);
      formData.append('policy', policy);
      formData.append('signature', signature);
      formData.append('key', dir + time + filename);
      formData.append('success_action_status', 200);
      formData.append('file', File, filename);
      ossUpload(host, formData).then((res) => {
        console.log(host + "/" + dir + time + filename)
        modalForm.value.article_image = host + "/" + dir + time + filename;
        proxy.$refs.modalFormRef.validateField(['article_image'],(valid) => {})
      });

    }
  }
// Akiraka 20230210 关闭弹窗
const handleClose = () => {
  proxy.$refs.modalFormRef.resetFields();
  emits('familyVisibleChange', false);
};
const getData = () => {
  handelOriginAllList();
  handelAllList();

};
defineExpose({
  getData,
});
</script>
<style scoped>
.row {
  display: flex;
}
.upload{
  margin-left: 10px;
}
</style>