<template>
  <div v-if="eventId" 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" :disabled="!isEditable" placeholder="请输入标题" style="width: 468px !important" />
            </el-form-item>
            <el-form-item label="发布单位：" prop="publish_group">
              <el-input v-model="formData.publish_group" disabled placeholder="请输入发布单位" style="width: 468px !important" />
            </el-form-item>
            <el-form-item label="信息模板：" prop="template_id">
              <el-radio-group v-model="formData.template_id" :disabled="!isEditable">
                <el-radio label="预设模板">预设模板</el-radio>
                <el-radio label="自定义模板">自定义模板</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="formData.template_id === '预设模板'" 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.template_id === '自定义模板'" prop="customPageUrl">
              <el-input v-model="formData.customPageUrl" placeholder="请输入自定义详情页面链接地址" style="width: 468px !important" />
            </el-form-item>
            <el-form-item label="信息内容：" prop="content">
              <el-input
                v-model="formData.content"
                type="textarea"
                disabled
                placeholder="请输入信息内容"
                style="width: 468px !important"
              ></el-input>
            </el-form-item>
            <el-form-item label="查看附件：">
              <ul>
                <li v-for="(file, index) in files" :key="index" @click="viewFile(file)">
                  {{ file.name }}
                </li>
              </ul>
            </el-form-item>
          </div>
          <h4 class="common-dialog-title">推送配置</h4>
          <div class="box1">
            <el-form-item label="发布名单：" prop="user_count" style="width: 468px !important">
              <span class="highlight-text">已选择{{ formData.user_count }}人</span>
              <template v-if="isEditable">
                <el-text class="common-btn-text-primary" @click="toggleReleaseList">查看详情</el-text>
              </template>
              <template v-else>
                <span class="common-btn-text-primary disabled">查看详情</span>
              </template>
            </el-form-item>
            <el-row :gutter="18">
              <el-col :span="6">
                <el-form-item label="发布时间：" prop="releaseTime">
                  <el-button type="text" :disabled="!isEditable" @click="publishNow">立即发布</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="13">
                <el-form-item label="定时发布：" prop="publish_time">
                  <el-date-picker v-model="formData.publish_time" type="datetime" :disabled="!isEditable" placeholder="选择发布时间"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="消息反馈方式：" prop="response_type" style="width: 468px !important">
              <el-select v-model="displayFeedbackText" :disabled="!isEditable" 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="materials">
              <ul>
                <li v-for="(material, index) in auditMaterials" :key="index">
                  {{ material }}
                </li>
              </ul>
            </el-form-item>
            <el-form-item label="审核人：" prop="examine_by">
              <el-input v-model="formData.examine_by" disabled placeholder="请输入审核人姓名" style="width: 368px !important" />
            </el-form-item>
          </div>
        </el-form>
        <div class="common-dialog-footer">
          <el-button @click="closeDialog">返回</el-button>
          <el-button @click="submitForm">编辑</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </div>
    </div>
  </div>
  <ContactSelect v-model="contactSelectState.show" :tree-data="treeData" :default-check-data="selectData" @confirm="handleData" />
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { getInformationView, getInformationUpdate } from '@/api/informationissue/informationissue';
import { ElMessage } from 'element-plus';
import ContactSelect from '@/components/ContactSelect/index.vue';
const props = defineProps<{
  eventId: string | number;
}>();
const emit = defineEmits<{
  (e: 'close'): void;
}>();
const isEditable = ref(false);
const formData = ref({
  title: '',
  publish_group: '',
  template_id: '',
  content: '',
  user_count: 0,
  releaseTime: '',
  response_type: '',
  examine_by: '',
  publish_time: '',
  materials: ''
});
const treeData = reactive([
  {
    id: 1,
    label: '茂南区',
    deptType: true,
    children: [
      {
        id: 2,
        userId: 1,
        label: '李里丽'
      },
      {
        id: 3,
        userId: 2,
        label: '何里'
      },
      {
        id: 4,
        userId: 3,
        label: '张力'
      }
    ]
  },
  {
    id: 5,
    label: '电白区',
    deptType: true,
    children: [
      {
        id: 6,
        userId: 4,
        label: '王五'
      },
      {
        id: 7,
        userId: 5,
        label: '冯可'
      },
      {
        id: 8,
        userId: 6,
        label: '刘森'
      },
      {
        id: 9,
        userId: 3,
        label: '张力'
      }
    ]
  }
]);
let contactSelectState = reactive({
  show: false,
  eventId: ''
});
const selectData = ref([]);
const handleData = (data) => {
  selectData.value = data;
  formData.value.user_count = data.length;
};
const toggleReleaseList = () => {
  contactSelectState.show = !contactSelectState.show;
};
const presetTemplates = [
  { value: 'template1', label: '模板一' },
  { value: 'template2', label: '模板二' }
];

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

const selectedPresetTemplate = ref('');

const files = ref([
  { name: '2023年4月29日广东省发布突发事件预警信息.pdf', url: '/path/to/file1.pdf' },
  { name: '2023年5月15日广东省发布突发事件预警信息.docx', url: '/path/to/file2.docx' }
]);
// 在原有的反馈选项数组的基础上，创建一个映射对象（map object）
const feedbackTextMap = {
  0: '仅需阅读',
  1: '点击确认',
  2: '签字确认'
};

// 创建一个计算属性，根据 formData 中的 response_type 返回对应的文本
const displayFeedbackText = computed({
  get() {
    return feedbackTextMap[formData.value.response_type];
  },
  set(value) {
    // 当选择器的值改变时，将对应的 key 值设置到 formData 中
    formData.value.response_type = Object.keys(feedbackTextMap).find((key) => feedbackTextMap[key] === value);
  }
});
const auditMaterials = ['2023年4月29日广东省发布突发事件预警信息.pdf', '审核材料2'];

const fetchDetail = async () => {
  try {
    const response = await getInformationView({ info_id: props.eventId });
    if (response.code === 200) {
      formData.value = response.data;
    } else {
      ElMessage.error(response.msg);
    }
  } catch (error) {
    ElMessage.error('获取信息详情失败，请稍后再试');
  }
};

watch(
  () => props.eventId,
  (newVal) => {
    if (newVal) {
      fetchDetail();
    }
  },
  { immediate: true }
);

const viewFile = (file) => {
  window.open(file.url, '_blank'); // 打开新标签页
};

const publishNow = () => {
  ElMessage.info('点击了立即发布');
};

const submitForm = async () => {
  if (validateFormData()) {
    // 如果是编辑状态，则执行保存操作
    if (isEditable.value) {
      try {
        const requestData = { ...formData.value, info_id: props.eventId };
        const response = await getInformationUpdate(requestData);
        if (response.code === 200) {
          ElMessage.success('信息更新成功');
          isEditable.value = false; // 保存后重新禁用编辑
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        ElMessage.error('更新信息失败，请稍后再试');
      }
    } else {
      // 如果不是编辑状态，则切换到编辑模式
      isEditable.value = true;
    }
  }
};

const validateFormData = (): boolean => {
  // 这里添加你的验证逻辑，例如检查是否所有的必填项都有值
  if (!formData.value.title.trim()) {
    ElMessage.error('标题不能为空');
    return false;
  }
  // 添加其他验证规则
  return true;
};

const closeDialog = () => {
  emit('close');
};
</script>

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