<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div>
    <!-- 主要内容区域 -->
    <div class="container mx-auto px-0 py-0 w-[1440px] mb-10">
      <bread-crumb :breadcrumbItems="breadcrumbItems" />

      <div class="grid grid-cols-12 gap-8 mt-5">
        <!-- 左侧导航 -->
        <div class="col-span-4">
          <div class="bg-yellow-50 rounded-lg shadow-sm p-6">
            <div class="flex items-start text-yellow-600">
              <el-icon class="mt-0.5 mr-3 text-yellow-600"><Warning /></el-icon>
              <div>
                <h3 class="text-base font-medium text-yellow-800 mb-5">
                  留言须知：
                </h3>
                <h4 class="text-yellow-800 mb-2 font-medium">
                  “网民有话说”平台受理以下事项:
                </h4>
                <ul
                  class="text-sm text-yellow-700 space-y-1 list-disc pl-4 mb-5"
                >
                  <li>
                    (一)
                    有关承办单位的工作职责、政策法规、办事流程、执法程序、行政审批等政务信息及公共服务信息的咨询.
                  </li>
                  <li>(二) 承办单位职责范围内的非紧急类求助.</li>
                  <li>
                    (三)
                    对城市治理、公共服务、市场监管、经济社会发展等方面的投诉举报和建议,
                  </li>
                  <li>
                    (四)
                    对行政机关、公共服务企事业单位工作人员工作作风、行政效能等方面的投诉举报.
                  </li>
                  <li>(五)其他应当受理的事项。</li>
                </ul>
                <h4 class="text-yellow-800 mb-2 font-medium">
                  对以下事项不予受理:
                </h4>
                <ul
                  class="text-sm text-yellow-700 space-y-1 list-disc pl-4 mb-5"
                >
                  <li>(一) 不属于承办单位职责或服务范围的事项。</li>
                  <li>
                    (二) 依法应当通过110、119、120等紧急服务专线处理的事项。
                  </li>
                  <li>
                    (三)
                    属于人大、政协、法院、检察院、军队、武警职责范围的事项。
                  </li>
                  <li>(四) 依法应当通过诉讼、仲裁、行政复议解决的事项。</li>
                  <li>
                    (五)
                    已进入诉讼、仲裁、行政复议、信访、信息公开等法定程序或已通过上述法定程序处理的事项。
                  </li>
                  <li>(六) 涉及国家机密、商业秘密、个人隐私的事项。</li>
                  <li>
                    (七)
                    正在办理过程中或已依法办理完毕，诉求人无新情况、新理由，向“网民有话说”平台提出的同一事项。
                  </li>
                  <li>
                    (八)
                    违反法律法规、社会公序良俗以及恶意攻击、骚扰或无实质诉求内容的事项。
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧表单 -->
        <div class="col-span-8">
          <div class="bg-white rounded-lg shadow-sm p-8">
            <h2 class="text-2xl font-bold text-gray-800 mb-6">提交留言</h2>
            =
            <form @submit.prevent="handleSubmit" class="space-y-6">
              <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">
                  <span class="text-red-500">*</span> 姓名
                </label>
                <el-input
                  v-model="formData.name"
                  placeholder="请输入您的姓名"
                  class="!rounded-button"
                />
              </div>
              <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">
                  <span class="text-red-500">*</span> 联系电话
                </label>
                <el-input
                  v-model="formData.phoneNumber"
                  placeholder="请输入联系电话"
                  class="!rounded-button"
                />
              </div>
              <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">
                  <span class="text-red-500">*</span> 留言标题
                </label>
                <el-input
                  v-model="formData.title"
                  placeholder="请输入留言标题"
                  class="!rounded-button"
                />
              </div>
              <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">
                  <span class="text-red-500">*</span> 留言内容
                </label>
                <el-input
                  v-model="formData.content"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入留言内容"
                  class="!rounded-button"
                />
              </div>

              <!-- <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">
                  上传附件
                </label>
                <el-upload
                  :file-list="fileList"
                  class="upload-demo"
                  action="/ms/file/upload.do"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="3"
                  ref="uploadRef"
                  :on-success="handleSuccess"
                  :on-exceed="handleExceed"
                  accept=".jpg,.png,.doc,.docx,.xslx,pdf"
                >
                  <el-button
                    type="danger"
                    class="!rounded-button whitespace-nowrap"
                    >选择文件</el-button
                  >
                  <template #tip>
                    <div class="text-sm text-gray-500 mt-1">
                      支持 jpg、jpeg、png、pdf、doc、docx、xslx 格式文件
                    </div>
                  </template>
                </el-upload>
              </div> -->
              <div class="space-y-2">
                <label class="block text-sm font-medium text-gray-700">
                  <span class="text-red-500">*</span> 验证码
                </label>
                <div class="flex items-center space-x-4">
                  <el-input
                    v-model="formData.captcha"
                    placeholder="请输入验证码"
                    class="!rounded-button"
                  />
                  <div
                    class="flex-shrink-0 w-32 h-10 bg-gray-100 rounded-lg overflow-hidden cursor-pointer"
                    @click="refreshCaptcha"
                  >
                    <img
                      :src="captchaImage"
                      alt="验证码"
                      class="w-full h-full object-cover"
                    />
                  </div>
                </div>
              </div>
              <div class="flex justify-center">
                <el-button
                  type="danger"
                  @click="handleSubmit"
                  class="!rounded-button whitespace-nowrap px-12 text-base"
                >
                  提交留言
                </el-button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance, watch } from "vue";
import { ElMessage } from "element-plus";
import { Warning, ArrowRight, Message } from "@element-plus/icons-vue";
import BreadCrumb from "@/components/breadcrumb/BreadCrumb.vue";
import { getWantMessage, uploadFile } from "@/api/wm/wm";
import { ElMessageBox } from "element-plus";
import { baseImageUrl } from "@/utils/config";

// const { proxy } = getCurrentInstance();

const breadcrumbItems = ref([
  { title: "首页", path: "/wm/wmhome" },
  { title: "我要留言" },
]);

const captchaText = ref("");
const captchaImage = ref("");
const fileList = ref([]);
const uploadRef = ref();
const formData = ref({
  name: "",
  title: "",
  content: "",
  phoneNumber: "",
  // contentImg: "",
  captcha: "",
});

const refreshCaptcha = () => {
  const captcha = generateCaptcha();
  captchaText.value = captcha.text;
  captchaImage.value = captcha.image;
};

onMounted(() => {
  refreshCaptcha();
});

// 文件上传个数限制
function handleExceed(files: any, fileList: any) {
  ElMessageBox.alert(`最多只能上传 3 个文件`);
}
//文件移除回调
function beforeRemove(file: any, fileList: any) {
  // var index = -1;
  // index = formData.value.contentImg.findIndex(function (text) {
  //   return text.uid == file.uid;
  // });
  // if (index != -1) {
  //   formData.value.contentImg.splice(index, 1);
  // }
  // return ElMessageBox.confirm(`确定移除 ${file.name}这个文件？`);
}
//文件上传成功回调
function handleSuccess() {
  ElMessage({
    message: "上传成功",
    type: "success",
  });
}

//提交表单
const handleSubmit = () => {
  if (!formData.value.name) {
    ElMessage({
      message: "请填写姓名",
      type: "warning",
    });
    return;
  }
  if (!formData.value.phoneNumber) {
    ElMessage({
      message: "请填写联系方式",
      type: "warning",
    });
    return;
  }
  if (!formData.value.title) {
    ElMessage({
      message: "请填写留言标题",
      type: "warning",
    });
    return;
  }
  if (!formData.value.content) {
    ElMessage({
      message: "请填写留言内容",
      type: "warning",
    });
    return;
  }
  if (!formData.value.captcha) {
    ElMessage({
      message: "请填写验证码",
      type: "warning",
    });
    return;
  }
  if (formData.value.captcha.toUpperCase() !== captchaText.value) {
    ElMessage({
      message: "验证码错误",
      type: "error",
    });
    refreshCaptcha();
    formData.value.captcha = "";
    return;
  }
  //将fileList中的文件逗号拼接，赋值给FormData.contentImg
  // formData.value.contentImg = fileList.value.map((file) => file.raw).join(",");
  // const formData = new FormData();
  // fileList.value.forEach((file) => {
  //   formData.append("file", file.raw);
  // });

  // 提交表单
  getWantMessage(formData.value).then((res) => {
    ElMessage({
      message: "提交成功",
      type: "success",
    });
    // 重置表单和验证码
    formData.value = {
      name: "",
      title: "",
      content: "",
      phoneNumber: "",
      contentImg: "",
      captcha: "",
    };
    uploadRef.value.clearFiles(); // 清空文件列表
    refreshCaptcha();
  });
};

const letters = Array.from("ABCDEFGHJKLMNPQRSTUVWXYZ23456789");

const generateCaptcha = () => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return "";
  canvas.width = 128;
  canvas.height = 40;
  // 设置背景
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  // 生成验证码文字
  const captchaText = Array.from(
    { length: 4 },
    () => letters[Math.floor(Math.random() * letters.length)]
  ).join("");
  // 绘制文字
  ctx.font = "bold 24px Arial";
  ctx.textBaseline = "middle";
  // 随机颜色和位置绘制每个字符
  for (let i = 0; i < captchaText.length; i++) {
    const x = 20 + i * 25;
    const y = 20 + Math.random() * 8 - 4;
    const angle = (Math.random() - 0.5) * 0.4;
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(angle);
    // 随机颜色
    const hue = Math.floor(Math.random() * 360);
    ctx.fillStyle = `hsl(${hue}, 70%, 40%)`;
    ctx.fillText(captchaText[i], 0, 0);
    ctx.restore();
  }
  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.beginPath();
    ctx.strokeStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${
      Math.random() * 255
    }, 0.5)`;
    ctx.lineWidth = 1;
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }
  // 添加噪点
  for (let i = 0; i < 50; i++) {
    const x = Math.random() * canvas.width;
    const y = Math.random() * canvas.height;
    ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${
      Math.random() * 255
    }, 0.5)`;
    ctx.fillRect(x, y, 2, 2);
  }
  return {
    text: captchaText,
    image: canvas.toDataURL(),
  };
};
</script>
<style scoped>
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e5e7eb !important;
}
:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #d1d5db !important;
}
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #3b82f6 !important;
}
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #e5e7eb !important;
  border-radius: 0.5rem;
}
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #d1d5db !important;
}
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px #3b82f6 !important;
}
</style>
