<template>
  <div class="common-dialog">
    <div class="common-dialog-content">
      <div class="common-dialog-title-box">
        <h3 class="common-dialog-title">信息发布申请</h3>
      </div>
      <div class="common-dialog-box">
        <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
          <h4 class="common-dialog-title">信息内容</h4>
          <div class="box1">
            <el-form-item label="标题：" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" style="width: 468px !important" />
            </el-form-item>

            <el-form-item label="发布单位：" prop="publishUnit">
              <el-input v-model="formData.publishUnit" placeholder="请输入发布单位" style="width: 468px !important" />
            </el-form-item>

            <el-form-item label="信息模板：" prop="templateType">
              <el-radio-group v-model="formData.templateType">
                <el-radio label="预设模板">预设模板</el-radio>
                <el-radio label="自定义模板">自定义模板</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="formData.templateType === '预设模板'" label="预设模板：" prop="presetTemplate">
              <el-select v-model="selectedPresetTemplate" placeholder="请选择预设模板" style="width: 300px !important">
                <el-option v-for="option in presetTemplates" :key="option.value" :label="option.label" :value="option.value"></el-option>
              </el-select>
              <el-text class="common-btn-text-primary" @click="showExample">样例</el-text>
            </el-form-item>
            <el-form-item v-if="formData.templateType === '自定义模板'" prop="customPageUrl">
              <el-input v-model="formData.customPageUrl" placeholder="请输入自定义详情页面链接地址" style="width: 468px !important" />
            </el-form-item>
            <el-form-item label="信息内容：" prop="messageContent">
              <el-input v-model="formData.messageContent" type="textarea" placeholder="请输入信息内容" style="width: 468px !important"></el-input>
            </el-form-item>
            <el-form-item label="上传附件：" prop="files">
              <el-upload
                ref="upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :file-list="files"
                list-type="text"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                action="https://jsonplaceholder.typicode.com/posts/"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">支持扩展名: .doc, .docx, .pdf, .jpg</div>
                </template>
              </el-upload>
            </el-form-item>
          </div>
          <h4 class="common-dialog-title">推送配置</h4>
          <div class="box1">
            <el-form-item label="发布名单：" prop="releaseList" style="width: 468px !important"
              ><span class="highlight-text">已选择{{ formData.releaseList }}人</span>
              <el-text class="common-btn-text-primary" @click="showReleaseList">查看详情</el-text>
            </el-form-item>
            <el-row :gutter="18">
              <el-col :span="12">
                <el-form-item label="发布时间：" prop="releaseTime">
                  <el-radio-group v-model="formData.releaseType">
                    <el-radio :label="'now'" @change="publishNow">立即发布</el-radio>
                    <el-radio :label="'schedule'">定时发布</el-radio>
                  </el-radio-group>
                  <div v-if="formData.releaseType === 'now'">发布时间：{{ formattedCurrentTime }}</div>
                  <el-date-picker v-else v-model="formData.releaseTime" type="datetime" placeholder="选择发布时间" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="消息反馈方式：" prop="feedbackWay" style="width: 468px !important">
              <el-select v-model="formData.feedbackWay" placeholder="请选择消息反馈方式">
                <el-option v-for="option in feedbackOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <h4 class="common-dialog-title">审核配置</h4>
          <div class="box1">
            <el-form-item label="审核材料：" prop="auditMaterials">
              <el-upload
                ref="auditUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :file-list="auditMaterials"
                list-type="text"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                action="https://jsonplaceholder.typicode.com/posts/"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">允许上传的文件格式：doc、docx、pdf、jpg、png</div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="审核人：" prop="auditor">
              <el-input v-model="formData.auditor" placeholder="请输入审核人姓名" style="width: 368px !important" />
            </el-form-item>
          </div>
        </el-form>
        <div class="common-dialog-footer">
          <el-button @click="$emit('close')">返回</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getInformationAdd } from '@/api/informationissue/informationissue';

const formData = ref({
  title: '',
  publishUnit: '',
  templateType: '',
  content: '',
  presetTemplate: '',
  customPageUrl: '',
  releaseList: 0,
  releaseType: 'now', // 默认选择立即发布
  releaseTime: '', // 存储定时发布的时间
  feedbackWay: '',
  examineBy: '',
  timing: '',
  materials: '',
  attachs: [],
  examineAttachs: []
});

const files = ref([]);
const auditMaterials = ref([]);
const formatTime = (isoString) => {
  const date = new Date(isoString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const publishNow = () => {
  formData.value.releaseTime = new Date().toISOString(); // 设置当前时间为发布时间
};
const formattedCurrentTime = ref(formatTime(new Date().toISOString()));

const rules = {
  title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
  publishUnit: [{ required: true, message: '请填写发布单位', trigger: 'blur' }],
  releaseList: [{ required: true, message: '请选择发布名单', trigger: 'change' }],
  timing: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
  feedbackWay: [{ required: true, message: '请选择消息反馈方式', trigger: 'change' }],
  examineBy: [{ required: true, message: '请填写审核人', trigger: 'blur' }]
};

const feedbackOptions = [
  { value: '仅需阅读', label: '仅需阅读' },
  { value: '点击确认', label: '点击确认' },
  { value: '签字确认', label: '签字确认' }
];

const presetTemplates = [
  { value: 'template1', label: '模板一' },
  { value: 'template2', label: '模板二' }
];
const selectedPresetTemplate = ref('');
const selectedPresetTemplateExample = ref('');
watch(selectedPresetTemplate, (newVal) => {
  selectedPresetTemplateExample.value = presetTemplateExamples[newVal] || '';
});

const handlePreview = (file) => {
  console.log(file);
};

const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};

const beforeUpload = (file) => {
  // 处理文件上传前的逻辑
  const isValidType = ['doc', 'docx', 'pdf', 'jpg', 'png'].includes(file.name.split('.').pop().toLowerCase());
  if (!isValidType) {
    ElMessage.error('不支持的文件类型');
    return false;
  }
  return true;
};

const handleSuccess = (response, file, fileList) => {
  console.log(response, file, fileList);
};

const showReleaseList = () => {
  ElMessage.info('点击了查看发布名单');
};
const submitForm = () => {
  if (validateFormData()) {
    // 构建要提交的数据对象
    const submitData = {
      title: formData.value.title,
      publish_group: formData.value.publishUnit,
      template_id: formData.value.templateType === '0' ? parseInt(selectedPresetTemplate.value) : null,
      content: formData.value.messageContent,
      response_type: formData.value.feedbackWay,
      publish_time: formData.value.releaseType === 'now' ? new Date().toISOString() : formData.value.releaseTime,
      examine_by: formData.value.auditor, // 假设审核人姓名字段是 'auditor'
      publish_channel: '', // 确保这个字段有适当的值
      user_count: formData.value.releaseList,
      users: [], // 确保这个字段有适当的值
      attachs: files.value.map((file) => ({ file_name: file.name })),
      examine_attachs: auditMaterials.value.map((file) => ({ file_name: file.name }))
    };

    // 调用 API 提交数据
    getInformationAdd(submitData)
      .then(() => {
        ElMessage.success('信息发布申请已提交');
        // 处理响应，可能需要清空表单或进行其他操作
      })
      .catch((error) => {
        ElMessage.error('提交失败: ' + error.message);
      });
  }
};

const validateFormData = (): boolean => {
  let isValid = true;
  for (const rule of Object.values(rules)) {
    for (const r of rule) {
      const value = formData.value[r.field];
      if (r.required && (!value || value.length === 0)) {
        ElMessage.error(r.message);
        isValid = false;
      }
    }
  }
  return isValid;
};
</script>

<style scoped>
.box1 {
  border: 1px solid #dcdfe6; /* 浅灰色边框 */
  padding: 10px; /* 可选：为了美观，可以添加一些内边距 */
  margin-bottom: 10px;
}
.highlight-text {
  font-weight: bold; /* 加粗 */
  font-size: 1.2em; /* 放大字体大小 */
}
</style>
