<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="formRef" :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="publish_group">
              <el-input v-model="formData.publish_group" placeholder="请输入发布单位" style="width: 468px !important" />
            </el-form-item>

            <el-form-item label="信息模板：" prop="templateType">
              <el-radio-group v-model="formData.template_type">
                <el-radio value="0">预设模板</el-radio>
                <el-radio value="1">自定义模板</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="formData.template_type === '0'" label="预设模板：" prop="template_type">
              <el-select
                v-model="formData.template_id"
                placeholder="请选择预设模板"
                style="width: 300px !important"
                @change="handleTemplateIdChanged"
              >
                <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="showTemplateExample">样例</el-text>
            </el-form-item>
            <el-form-item v-if="formData.template_type === '1'" prop="template_url">
              <el-input v-model="formData.template_url" placeholder="请输入自定义详情页面链接地址" style="width: 468px !important" />
            </el-form-item>
            <el-form-item label="信息内容：" prop="content">
              <el-input v-model="formData.content" :rows="4" type="textarea" placeholder="请输入信息内容" style="width: 468px !important"></el-input>
            </el-form-item>
            <el-form-item label="上传附件：" prop="attachs">
              <file-upload v-model="formData.attachs" :limit="4" :file-type="['pdf', 'doc', 'docx', 'jpg', 'png']" />
            </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.user_count }}人</span>
              <el-text class="common-btn-text-primary" @click="toggleReleaseList">查看详情</el-text>
            </el-form-item>
            <el-row :gutter="18">
              <el-col :span="14">
                <el-form-item label="发布时间：" prop="publish_time">
                  <el-radio-group v-model="formData.publish_type">
                    <el-radio :value="'0'" @change="publishNow">立即发布</el-radio>
                    <el-radio :value="'1'">定时发布</el-radio>
                  </el-radio-group>
                  <div v-if="formData.publish_type === '0'" style="min-width: 240px">发布时间：{{ formattedCurrentTime }}</div>
                  <el-date-picker v-else v-model="formData.publish_time" type="datetime" placeholder="选择发布时间" style="width: 250px !important" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="消息反馈方式：" prop="response_type" style="width: 300px !important">
              <el-select v-model="formData.response_type" 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="examine_attachs">
              <file-upload v-model="formData.examine_attachs" :limit="4" :file-type="['pdf', 'doc', 'docx', 'jpg', 'png']" />
            </el-form-item>
            <el-form-item label="审核人：" prop="auditor">
              <el-autocomplete
                v-model="formData.examine_by"
                :fetch-suggestions="querySearch"
                placeholder="请输入审核人姓名"
                style="width: 368px !important"
                @select="handleSelect"
              >
                <template #suffix>
                  <i class="el-icon-search"></i>
                </template>
                <template #prepend>
                  <el-button icon="el-icon-search" @click="openUserSelect"></el-button>
                </template>
              </el-autocomplete>
            </el-form-item>
          </div>
        </el-form>
        <div class="common-dialog-footer">
          <!--
          <el-button @click="$emit('close')">返回</el-button>
          -->
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
        </div>
      </div>
    </div>
  </div>
  <ContactSelect
    v-model="contactSelectState.show"
    :tree-data="treeContactSelectData"
    :default-check-data="selectContactSelectData"
    @confirm="handleContactSelectData"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { addInformation, getTemplateList, getUser } from '@/api/informationissue/informationissue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const formRef = ref(null);
const buttonLoading = ref(false);

const formData = ref({
  title: '',
  publish_group: '',
  template_type: '0',
  template_id: '',
  template_url: '',
  content: '',
  publish_type: '0', // 默认选择立即发布
  publish_time: '', // 存储定时发布的时间
  response_type: '',
  examine_by: '',
  attachs: [],
  examine_attachs: [],
  user_count: 0,
  users: [],
  publish_channel: '粤政易' // 默认
});

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 = () => {
  formattedCurrentTime.value = formatTime(new Date().toISOString()); // 设置当前时间为发布时间
};
const formattedCurrentTime = ref(formatTime(new Date().toISOString()));

// 审核人模糊查询
const users = ref([]);

const querySearch = (queryString, cb) => {
  const results = queryString ? users.value.filter(this.createFilter(queryString)) : users.value;
  // 调用 callback 返回建议列表的数据
  cb(results);
};
const handleSelect = (item) => {
  formData.value.examine_by = item.username;
};

const rules = {
  title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
  content: [{ required: true, message: '请填写信息内容', trigger: 'blur' }],
  publish_group: [{ required: true, message: '请填写发布单位', trigger: 'blur' }],
  publish_time: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
  response_type: [{ required: true, message: '请选择消息反馈方式', trigger: 'change' }],
  examine_by: [{ required: true, message: '请填写审核人', trigger: 'blur' }],
  attachs: [
    {
      validator: (rule, value, callback) => {
        if (value.length == 0) {
          return callback(new Error('请上传附件'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  examine_attachs: [
    {
      validator: (rule, value, callback) => {
        if (value.length == 0) {
          return callback(new Error('请上传审批附件'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

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

const presetTemplates = ref([]);

const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      if (formData.value.user_count <= 0) {
        proxy?.$modal.msgError('请选择发布名单');
        return;
      }
      formData.value.users = selectContactSelectData.value.map((u) => ({ user_id: u.userId, nick_name: u.label }));
      try {
        buttonLoading.value = true;
        await addInformation(formData.value);
        proxy?.$modal.msgSuccess('信息发布申请已提交');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

const showTemplateExample = () => {
  ElMessage.info('点击了查看模板样例');
};

const handleTemplateIdChanged = async (value: any) => {
  const n = presetTemplates.value.find((i) => i.value === value);
  formData.value.content = n.content;
};

// 通讯录（用玉波做的接口改成动态获取）
const treeContactSelectData = 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
});
const selectContactSelectData = ref([]);
const handleContactSelectData = (data) => {
  selectContactSelectData.value = data;
  formData.value.user_count = data.length;
};
const toggleReleaseList = () => {
  contactSelectState.show = !contactSelectState.show;
};

onMounted(() => {
  formData.value.publish_time = formattedCurrentTime.value;
  getTemplateList({}).then((res) => {
    res.data.forEach((item, index) => {
      presetTemplates.value.push({ value: item.name, label: item.name, content: item.content });
    });
    getUser({}).then((res) => {
      users.value = res.data.map((user) => ({ value: user.username, username: user.username }));
    });
  });
});
</script>

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