<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="min-h-screen bg-gray-50">
    <div
      class="bg-[url('@/assets/imgs/tyjb-bg.png')] bg-cover bg-center h-[240px] flex items-center justify-center text-[65px] font-bold text-white"
    >
      太原市互联网应急指挥和举报中心
    </div>
    <div id="app" class="container mx-auto px-4 py-4 max-w-5xl">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="140px"
        class="space-y-3"
      >
        <!-- 举报人基本信息 -->
        <el-card class="shadow-md">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-lg font-semibold">举报人基本信息</span>
            </div>
          </template>

          <div class="gap-0">
            <!-- 真实姓名 -->
            <el-form-item label="真实姓名" prop="userName" class="mb-0">
              <el-input
                v-model="form.userName"
                placeholder="请输入真实姓名"
                clearable
              ></el-input>
            </el-form-item>

            <!-- 性别 -->
            <el-form-item label="性别" prop="userSex" class="mb-0">
              <el-radio-group v-model="form.userSex">
                <el-radio
                  v-for="item in userSexOptions"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>

            <!-- 电子邮箱 -->
            <el-form-item label="电子邮箱" prop="userEmail" class="mb-0">
              <el-input
                v-model="form.userEmail"
                placeholder="请输入电子邮箱"
                clearable
              ></el-input>
            </el-form-item>

            <!-- 电话号码 -->
            <el-form-item label="电话号码" prop="userMobile" class="mb-0">
              <el-input
                v-model="form.userMobile"
                placeholder="请输入电话号码"
                clearable
              ></el-input>
            </el-form-item>

            <!-- 地域选择 -->
            <el-form-item label="地域" prop="region" class="mb-0">
              <el-cascader
                v-model="form.region"
                class="w-full"
                :options="getCityOptions()"
                placeholder="请选择省/市"
                clearable
                @change="handleRegionChange"
              ></el-cascader>
            </el-form-item>

            <!-- 通讯地址 -->
            <el-form-item
              label="通讯地址"
              prop="userAddress"
              class="mb-0 md:col-span-2"
            >
              <el-input
                v-model="form.userAddress"
                type="textarea"
                :rows="2"
                placeholder="请输入详细通讯地址"
              ></el-input>
            </el-form-item>
          </div>
        </el-card>

        <!-- 举报信息 -->
        <el-card class="shadow-md">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-lg font-semibold">举报信息</span>
            </div>
          </template>

          <!-- 被举报类型 -->
          <el-form-item label="被举报类型" prop="reportType" class="mb-4">
            <el-radio-group
              v-model="form.reportType"
              @change="handleReportTypeChange"
            >
              <el-radio
                v-for="item in reportTypeOptions"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <!-- 网站类型 -->
          <div v-if="form.reportType === 1" class="mb-4">
            <el-form-item label="网址名称" prop="websiteName" class="mb-0">
              <el-input
                v-model="form.websiteName"
                placeholder="请输入网址名称"
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="被举报网址" prop="websitAddress" class="mb-0">
              <el-input
                v-model="form.websitAddress"
                placeholder="请输入被举报网址"
                clearable
              ></el-input>
            </el-form-item>
          </div>

          <!-- 搜索引擎类型 -->
          <div v-if="form.reportType === 2" class="space-y-4 mb-4">
            <el-form-item label="搜索引擎类型" prop="searchType">
              <el-select
                v-model="form.searchType"
                placeholder="请选择搜索引擎类型"
                clearable
                class="w-full"
                @change="handleSearchEngineTypeChange"
              >
                <el-option
                  v-for="item in searchEngineTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <div class="gap-0">
              <el-form-item
                label="举报关键字"
                prop="searchKeyword"
                class="mb-0"
              >
                <el-input
                  v-model="form.searchKeyword"
                  placeholder="请输入举报关键字"
                  clearable
                ></el-input>
              </el-form-item>

              <el-form-item label="网站名称" prop="websiteName" class="mb-0">
                <el-input
                  v-model="form.websiteName"
                  placeholder="请输入网站名称"
                  clearable
                ></el-input>
              </el-form-item>

              <el-form-item
                label="被举报网址"
                prop="websitAddress"
                class="mb-0 md:col-span-2"
              >
                <el-input
                  v-model="form.websitAddress"
                  placeholder="请输入被举报网址"
                  :disabled="disabled"
                  clearable
                ></el-input>
              </el-form-item>
            </div>
          </div>

          <!-- APP类型 -->
          <div v-if="form.reportType === 3" class="mb-0">
            <el-form-item label="APP名称" prop="websiteName" class="mb-0">
              <el-input
                v-model="form.websiteName"
                placeholder="请输入APP名称"
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="APP官方地址" prop="websitAddress" class="mb-0">
              <el-input
                v-model="form.websitAddress"
                placeholder="请输入APP官方地址"
                clearable
              ></el-input>
            </el-form-item>
          </div>

          <!-- 信息所在详细网址 -->
          <el-form-item
            label="信息所在详细网址"
            prop="websitDetailAddress"
            class="mb-4"
          >
            <el-input
              v-model="form.websitDetailAddress"
              placeholder="请输入信息所在详细网址"
              clearable
              :disabled="disabled"
            ></el-input>
          </el-form-item>

          <!-- 举报内容 -->
          <el-form-item label="举报内容" prop="reportContent" class="mb-4">
            <el-input
              v-model="form.reportContent"
              type="textarea"
              :rows="4"
              placeholder="举报内容不能为空且不能超过500个字符"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>

          <!-- 危害类型 -->
          <el-form-item label="危害类型" prop="harmType" class="mb-4">
            <el-select
              v-model="form.harmType"
              placeholder="请选择危害类型"
              clearable
              class="w-full"
            >
              <el-option
                v-for="item in harmTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 附件上传 -->
          <el-form-item label="附件" prop="fileUrl" class="mb-4">
            <!-- <el-upload
              v-model:file-list="fileList"
              action="#"
              accept=".jpg,.png,.jpeg,.doc,.docx,.pdf"
              list-type="text"
              :auto-upload="false"
              :limit="3"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-change="handleUploadChange"
              :on-success="handleUploadSuccess"
              :on-remove="removeUploadFile"
            >
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip text-sm text-gray-500">
                  每个附件大小不能超过10M，最多可上传3个附件
                </div>
              </template>
            </el-upload> -->

            <el-upload
              :file-list="contentImg"
              :action="'/cms/upload/uploadFile'"
              :limit="3"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-error="contentImgError"
              :on-success="contentImgSuccess"
              :on-remove="contentImghandleRemove"
              accept=".jpg,.png,.jpeg,.doc,.docx,.pdf"
              list-type="text"
              name="multipartFile"
            >
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip text-sm text-gray-500">
                  每个附件大小不能超过10M，最多可上传3个附件
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 图形验证码 -->
          <el-form-item label="图形验证码" prop="captcha" class="mb-4">
            <div class="flex items-center space-x-4">
              <el-input
                v-model="form.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>
          </el-form-item>
        </el-card>
        <!-- 按钮区域 -->
        <div class="flex justify-center space-x-4 pt-5 pb-10">
          <el-button type="primary" @click="submitForm" class="w-[100px]"
            >提交</el-button
          >
          <el-button @click="resetForm" class="w-[100px]">重置</el-button>
        </div>
      </el-form>
    </div>
    <Footer class="w-[100%] mt-0"></Footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import cityData from "@/assets/city.json";
import { getUpdateForm, uploadFile } from "@/api/jb/jb";
import Footer from "@/components/footer.vue";

const disabled = ref(false);
const fileList = ref([]);
const formRef = ref();
const contentImg = ref<any>([]);

const harmTypeOptions = [
  { label: "网络“开盒”恶意评价、侮辱谩骂及造谣污蔑等信息", value: 1 },
  { label: "网络交易环境", value: 2 },
  { label: "网上虚假宣传制售“特供酒", value: 3 },
  { label: "境外赌场招赌信息", value: 4 },
  { label: "含有病态、低俗内容的热搜榜单", value: 5 },
  { label: "生活服务类平台信息", value: 6 },
  { label: "涉企侵权信息举报", value: 7 },
  { label: "低俗", value: 8 },
  { label: "谣言", value: 9 },
  { label: "淫秽色情", value: 10 },
  { label: "赌博", value: 11 },
  { label: "诈骗", value: 12 },
  { label: "侵权", value: 13 },
  { label: "病毒", value: 14 },
  { label: "违背宪法原则", value: 15 },
  { label: "攻击党和政府", value: 16 },
  { label: "违背社会公德", value: 17 },
  { label: "其他违法和不良信息", value: 18 },
  { label: "宣扬邪教", value: 19 },
  { label: "迷信暴力", value: 20 },
  { label: "新冠肺炎疫情", value: 21 },
  { label: "侵权假冒", value: 22 },
];

const searchEngineTypeOptions = [
  { label: "其他", url: "http://", value: 1 },
  { label: "百度", url: "http://www.baidu.com", value: 2 },
  { label: "谷歌", url: "http://www.google.com", value: 3 },
  { label: "雅虎", url: "http://www.yahoo.cn", value: 4 },
  { label: "搜狗", url: "http://www.sogou.com", value: 5 },
  { label: "360", url: "https://www.so.com", value: 6 },
  { label: "必应", url: "https://cn.bing.com", value: 7 },
];
// 被举报类型选项
const reportTypeOptions = [
  { label: "网站", value: 1 },
  { label: "搜索引擎类", value: 2 },
  { label: "APP", value: 3 },
];

const userSexOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 2 },
];

// 获取城市选项
function getCityOptions() {
  return cityData.provinces.map((province: any) => ({
    label: province.provinceName,
    value: province.provinceName,
    children: province.citys.map((city: any) => ({
      label: city.cityName,
      value: city.cityName,
    })),
  }));
}

// 处理区域选择变化
function handleRegionChange(val: string[]) {
  if (val.length === 2) {
    form.country = val[0];
    form.city = val[1];
  }
}

// 表单数据
const form = reactive({
  userName: "",
  userSex: 1,
  userEmail: "",
  userMobile: "",
  region: [],
  country: "",
  city: "",
  userAddress: "",
  reportType: 1, // 举报信息
  websiteName: "", //网址名称
  websitAddress: "", //被举报网址
  searchType: "", //搜索引擎类型
  searchKeyword: "", //举报关键字
  websitDetailAddress: "", //信息所在详细网址
  reportContent: "",
  harmType: "",
  fileUrl: "",
  images: "",
  captcha: "",
  status: "0",
});

// 表单验证规则
const rules = reactive({
  userName: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 10, message: "请输入2 到 10 位真实姓名", trigger: "blur" },
  ],
  userSex: [{ required: true, message: "请选择性别", trigger: "change" }],
  userEmail: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  userMobile: [
    { required: true, message: "请输入电话号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  region: [{ required: true, message: "请选择地域", trigger: "change" }],
  reportType: [
    { required: true, message: "请选择被举报类型", trigger: "change" },
  ],
  websiteName: [{ required: true, message: "请输入网址名称", trigger: "blur" }],
  websitAddress: [
    { required: true, message: "请输入被举报网址", trigger: "blur" },
    // { type: "url", message: "请输入正确的网址", trigger: "blur" },
  ],
  searchType: [
    { required: true, message: "请选择搜索引擎类型", trigger: "change" },
  ],
  searchKeyword: [
    { required: true, message: "请输入举报关键字", trigger: "blur" },
  ],
  websitDetailAddress: [
    { required: true, message: "请输入信息所在详细网址", trigger: "blur" },
    // { type: "url", message: "请输入正确的网址", trigger: "blur" },
  ],
  reportContent: [
    { required: true, message: "请输入举报内容", trigger: "blur" },
    { min: 1, max: 500, message: "举报内容不能超过500个字符", trigger: "blur" },
  ],
  harmType: [{ required: true, message: "请选择危害类型", trigger: "change" }],
  captcha: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
  ],
});

// 处理举报类型变化
function handleReportTypeChange(value: string) {
  form.websitAddress = ""; //被举报网址
  form.websitDetailAddress = ""; //信息所在详细网址
  form.websiteName = ""; //网址名称
  form.searchType = ""; //搜索引擎类型
  form.searchKeyword = ""; //举报关键字
  disabled.value = false;
}

// 处理搜索引擎类型变化
function handleSearchEngineTypeChange(value: string) {
  searchEngineTypeOptions.forEach((item: any) => {
    if (item.value === value) {
      form.websitAddress = item.url; //被举报网址
      form.websitDetailAddress = item.url; //信息所在详细网址
    }
  });
  if (value === "http://") {
    disabled.value = false;
  } else {
    disabled.value = true;
  }
}

// 处理文件上传超出限制
function handleExceed(files: any, fileList: any) {
  ElMessage({
    message: `最多只能上传 3 个文件，当前选择了 ${files.length} 个文件，共 ${
      files.length + fileList.length
    } 个文件`,
    type: "warning",
  });
}

// 文件上传前的验证
function beforeUpload(file: any) {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage({
      message: "单个附件大小不能超过 10MB!",
      type: "warning",
    });
    return false;
  }
  return true;
}

// 处理文件上传成功
function contentImgSuccess(response: any, file: any, fileList: any) {
  if (response.result) {
    contentImg.value.push({
      url: file.url,
      name: file.name,
      path: response.data,
      uid: file.uid,
    });
  }
  debugger;
}

// 处理文件上传错误
function contentImgError(response: any, file: any, fileList: any) {
  response = response.toString().replace("Error: ", "");
  // debugger;
  response = JSON.parse(response);
  ElMessage({
    message: response.msg,
    type: "error",
  });
}

// 移除上传文件
function contentImghandleRemove(file: any, fileList: any) {
  var index = -1;
  index = contentImg.value.findIndex(function (text: any) {
    return text.uid == file.uid;
  }); //查找元素下标
  if (index != -1) {
    contentImg.value.splice(index, 1); //删除元素
  }
}

// 移除上传文件
// function removeUploadFile(file: any, fileList: any) {}

// 处理文件上传变化
// function handleUploadChange(files: any, fileList: any) {
// let formData = new FormData();
// fileList.forEach((file: any) => {
//   formData.append("multipartFile", file.raw); // 注意这里使用multipartFile对应后端参数
// });
// uploadFile(formData).then((res: any) => {
//   if (res.code === 200) {
//     form.images = res.data;
//     ElMessage.success("文件上传成功!");
//   } else {
//     ElMessage.error("文件上传失败!");
//   }
// });
// }

// 处理文件上传成功
// function handleUploadSuccess(res: any, file: any, fileList: any) {}

// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      // 验证验证码
      if (form.captcha.toUpperCase() !== captchaText.value) {
        ElMessage({
          message: "验证码错误",
          type: "error",
        });
        refreshCaptcha();
        form.captcha = "";
        return;
      }
      //contentImg转json赋值给form.fileUrl
      form.fileUrl = JSON.stringify(contentImg.value);
      getUpdateForm(form).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            message: "提交成功!",
            type: "success",
          });
          // 重置表单字段
          resetForm();
          refreshCaptcha(); // 刷新验证码
        } else {
          ElMessage({
            message: "提交失败!",
            type: "error",
          });
        }
      });
      // if (fileList.value.length === 0) {
      //   getUpdateForm(form).then((res) => {
      //     if (res.code === 200) {
      //       ElMessage.success("提交成功!");
      //       resetForm();
      //     } else {
      //       ElMessage.error("提交失败!");
      //     }
      //   });
      // } else {
      //   let formData = new FormData();
      //   fileList.value.forEach((file: any) => {
      //     formData.append("multipartFile", file.raw); // 注意这里使用multipartFile对应后端参数
      //   });
      //   uploadFile(formData).then((res: any) => {
      //     if (res.code === 200) {
      //       form.images = res.data;
      //       getUpdateForm(form).then((res) => {
      //         if (res.code === 200) {
      //           ElMessage.success("提交成功!");
      //           resetForm();
      //         } else {
      //           ElMessage.error("提交失败!");
      //         }
      //       });
      //     } else {
      //       ElMessage.error("文件上传失败!");
      //     }
      //   });
      // }
    } else {
      ElMessage({
        message: "请填写完整信息!",
        type: "error",
      });
      return false;
    }
  });
}
// 重置表单
function resetForm() {
  formRef.value.resetFields();
  contentImg.value = [];
  ElMessage({
    message: "表单已重置",
    type: "info",
  });
}

const letters = Array.from("ABCDEFGHJKLMNPQRSTUVWXYZ23456789");
const captchaText = ref<string>("");
const captchaImage = ref<string>("");

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

onMounted(() => {
  refreshCaptcha();
});
function 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>
.min-h-screen {
  /* min-height: 1080px; */
}
</style>
