<template>
  <div>
    <div>
      <div v-loading="uploadLoading" element-loading-text="Loading..." element-loading-svg-view-box="-10, -10, 50, 50"
        element-loading-background="rgba(122, 122, 122, 0.8)"
        class="w-[500px] operate relative right-show p-2 border-x rounded-md border-solid border-slate-50 shadow-2xl">
        <div class="w-[480px] relative h-full mx-auto bg-white dark:bg-[#161616] dark:text-white">
          <!-- 顶部占位元素 -->
          <div class="h-[160px] bg-black"></div>
          <!-- 评论区 -->
          <div class="comment_area px-5 pt-5">
            <div>
              <el-radio-group v-model="headerType" @change="useFormDataStore.changeHeaderType">
                <el-radio :label="1" size="large">地区</el-radio>
                <el-radio :label="2" size="large">大家都在搜</el-radio>
              </el-radio-group>
            </div>
            <!-- 地址区域 -->
            <div class="area_box flex items-center mb-5" v-if="headerType === 1">
              <div class="flex-1">
                <div class="flex justify-between mb-[10px]">
                  <el-input v-model="regionalInfo.currentArea" placeholder="请输入地区">
                    <template #prepend>地区</template>
                  </el-input>
                </div>

                <div class="text-[#999] text-[12px]">
                  <el-input v-model="regionalInfo.viewCount">
                    <template #prepend>
                      <el-select class="w-[80px]" v-model="regionalInfo.viewUnit" placeholder="单位">
                        <el-option label="无" value="" />
                        <el-option label="万" value="万" />
                        <el-option label="亿" value="亿" />
                      </el-select>
                    </template>
                    <template #append> 人看过 </template>
                  </el-input>
                </div>
              </div>
            </div>
            <!-- 大家都在搜 -->
            <div v-else class="mb-2">
              <el-row>
                <el-col :span="12">
                  <el-input v-model="everyoneSearch.label">
                  </el-input>
                </el-col>
                <el-col :span="12">
                  <el-input v-model="everyoneSearch.title">
                  </el-input>
                </el-col>
              </el-row>

            </div>
            <!-- 评论条数 -->
            <div class="total text-center mb-2 font-semibold text-[14px] pb-[10px]">
              <el-row>
                <el-col :span="12">
                  <el-input v-model="total" size="small">
                  </el-input>
                </el-col>
                <el-col :span="12">
                  <el-input v-model="commentLabel" size="small">
                  </el-input>
                </el-col>
              </el-row>



            </div>
            <!-- 评论列表 -->
            <div class="comment_list overflow-scroll h-[500px]">
              <div v-for="item in data" :key="item.id" class="comment_list_item flex">
                <div>
                  <el-upload v-model:file-list="item.avatarList" class="avatar-uploader" action accept="image/*"
                    :http-request="handleUpload" :show-file-list="false" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <el-avatar @click="handleUploadAvatarFlag(item)" :size="40" :src="item.avatar" />
                  </el-upload>
                </div>
                <div class="flex-1 ml-3">
                  <div class="text-[14px] flex dark:text-[#626262] text-[#adadad]">
                    <div class="w-[120px] mr-2">
                      <el-input type="text" v-model="item.nickname"></el-input>
                    </div>
                    <el-switch v-model="item.isAuthor" style="
                        --el-switch-on-color: #13ce66;
                        --el-switch-off-color: #ff4949;
                      " inline-prompt active-text="作者" inactive-text="否" />
                    <el-input v-if="item.isAuthor" v-model="AuthorTitle" size="small"></el-input>
                
              </div>

                  <div class="item_content py-2 text-[15px] break-all tracking-[0.1px]">
                    <el-input v-model="item.content" autosize type="textarea" />
                  </div>
                  <div class="dark:text-[#626262] text-[#adadad] text-[14px]">
                    <div class="flex justify-between items-center">
                      <div class="flex items-center">
                        <div class="flex items-center">
                          <div class="w-[80px]">
                            <el-input type="text" v-model="item.recoveryTime">
                            </el-input>
                          </div>
                          ·
                          <div class="w-[60px]">
                            <el-input type="text" v-model="item.area">
                            </el-input>
                          </div>
                        </div>
                        <div class="ml-3">
                          <el-input type="text" class="w-[100px]" v-model="replyTitle" size="small"></el-input>
                        </div>
                      </div>
                      <div class="flex items-center">
                        <div class="flex items-center mr-5" :class="[item.isLike ? 'text-[#f62d5a]' : '']">
                          <svg-icon :name="item.isLike ? 'isLike' : 'ding'" :size="item.isLike ? '14px' : '20px'"
                            :class="item.isLike ? 'mr-[5px]' : ''"
                            @click="useFormDataStore.changeFirstLevelLike(item)" />

                          <div class="w-[50px]">
                            <el-input size="small" type="text" v-model="item.likeCount">
                            </el-input>
                          </div>
                        </div>
                        <div class="flex items-center" :class="[item.isDisLike ? 'text-[#f62d5a]' : '']">
                          <svg-icon :name="'cai'" size="20px" />
                          <span>
                            {{ item.disLikeCount }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="mt-1">
                    <el-button size="small" @click="useFormDataStore.addSecondLevel(item)">
                      添加二级模板
                    </el-button>
                  </div>
                  <div class="mt-1 flex">
                    <el-upload v-model:file-list="item.urlList" class="avatar-uploader" action accept="image/*"
                      :http-request="handleUploadImg" :show-file-list="false" :on-success="handleImgSuccess"
                      :before-upload="beforeAvatarUpload">
                      <el-button size="small" @click="handleUploadFirstImg(item)">
                        添加图片
                      </el-button>
                    </el-upload>
                    <el-button v-if="item.firstImgUrl" class="ml-2" @click="item.firstImgUrl = ''" size="small" plain
                      type="danger">移除一级图片</el-button>
                  </div>
                  <div v-if="item.recoveryList" class="my-2">
                    <div v-for="ctem in item.recoveryList" :key="ctem.id" class="flex my-2">
                      <div>
                        <el-upload v-model:file-list="ctem.avatarList" class="avatar-uploader" action accept="image/*"
                          :http-request="handleUpload" :show-file-list="false" :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                          <el-avatar @click="handleUploadSecondAvatarFlag(item, ctem)" :size="20" :src="ctem.avatar" />
                        </el-upload>
                      </div>
                      <div class="flex-1 ml-3">
                        <div class="flex items-center text-[14px] dark:text-[#626262] text-[#adadad]">
                          <div class="w-[80px]">
                            <el-input size="small" type="text" v-model="ctem.respondent"></el-input>
                          </div>
                          <el-switch v-model="ctem.isRespondentAuthor" inline-prompt
                            @change="changeSecondRespondentAuthor(ctem)" active-text="作者" inactive-text="否" />
                          <span v-if="ctem.isAuthor"
                            class="bg-[#f62d5a] text-white py-[1px] scale-90 rounded px-[6px] ml-[5px] text-[12px]">
                            作者
                          </span>

                          <el-icon>
                            <CaretRight />
                          </el-icon>
                          <div class="w-[80px]">
                            <el-input size="small" type="text" v-model="ctem.recipient"></el-input>
                          </div>
                        </div>

                        <div class="item_content py-2 text-[15px] break-all tracking-[0.1px]">
                          <el-input v-model="ctem.content" autosize type="textarea" />
                        </div>
                        <div class="dark:text-[#626262] text-[#adadad] text-[14px]">
                          <div class="flex justify-between items-center">
                            <div class="flex items-center">
                              <div class="flex items-center">
                                <div class="w-[80px]">
                                  <el-input type="text" v-model="ctem.recoveryTime">
                                  </el-input>
                                </div>
                                ·
                                <div class="w-[60px]">
                                  <el-input type="text" v-model="ctem.area">
                                  </el-input>
                                </div>
                              </div>
                              <div class="ml-3">
                                <el-input type="text" v-model="replyTitle">
                                </el-input>
                              </div>
                            </div>
                            <div class="flex items-center">
                              <div class="flex items-center mr-5" :class="[ctem.isLike ? 'text-[#f62d5a]' : '']">
                                <svg-icon :name="ctem.isLike ? 'isLike' : 'ding'" :size="ctem.isLike ? '14px' : '20px'"
                                  :class="ctem.isLike ? 'mr-[5px]' : ''" @click="
                                    useFormDataStore.changeSecondLevelLike(ctem)
                                    " />
                                <div class="w-[50px]">
                                  <el-input size="small" type="text" v-model="ctem.likeCount">
                                  </el-input>
                                </div>
                              </div>
                              <div class="flex items-center" :class="[
                                ctem.isDisLike ? 'text-[#f62d5a]' : '',
                              ]">
                                <svg-icon :name="'cai'" size="20px" />
                              </div>
                            </div>
                          </div>
                          <div class="mt-1 flex">
                            <el-upload v-model:file-list="ctem.urlList" class="avatar-uploader" action="/api/upload"
                              accept="image/*" :http-request="handleUploadImg" :show-file-list="false"
                              :on-success="handleImgSuccess" :before-upload="beforeAvatarUpload">
                              <el-button size="small" @click="handleUploadSecondImg(item, ctem)">
                                添加二级图片
                              </el-button>
                            </el-upload>
                            <el-button v-if="ctem.secondImgUrl" class="ml-1" plain size="small" type="danger"
                              @click="ctem.secondImgUrl = ''">移除二级图片</el-button>
                          </div>
                        </div>
                      </div>
                      <div>
                        <el-icon color="red" @click="
                          useFormDataStore.removeSecondLevel(item, ctem)
                          ">
                          <Remove />
                        </el-icon>
                      </div>
                    </div>
                  </div>
                </div>
                <div @click="useFormDataStore.removeFirstLevelTemp(item)">
                  <el-icon color="red">
                    <CloseBold />
                  </el-icon>
                </div>
              </div>
              <div class="text-center py-3">
                <el-button @click="useFormDataStore.addFirstLevelTemp">添加一级评论模板</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useStore from "@/store";
import { storeToRefs } from "pinia";
import { requestFormData } from "@/request";
import router from "@/router";

const { useThemeStore, useFormDataStore, useUserStore } = useStore();
const { currentTheme } = storeToRefs(useThemeStore);
const { data, total, regionalInfo, everyoneSearch, headerType, replyTitle, commentLabel, AuthorTitle } =
  storeToRefs(useFormDataStore);

let imageUrl = ref("");

let uploadLoading = ref(false);

function resetFormData(params) {
  useFormDataStore.$reset();
}
function createImgage(params) {
  console.log("params", params);
}
// 改变二级回复人是否作者
function changeSecondRespondentAuthor(params) {
  if (params.isRecipientAuthor) {
    params.isRecipientAuthor = false;
  }
}
// 改变二级被回复人是不是作者
function changeSecondRecipientAuthor(params) {
  if (params.isRespondentAuthor) {
    params.isRespondentAuthor = false;
  }
}

function handleAvatarSuccess(response, uploadFile) {
  if (response && response.code === 401) {
    ElMessage({ message: "登录失效，请重新登录", type: "warning" });
    try {
      useUserStore.$patch({ token: "", isLogin: false });
    } catch (e) { }
    router.push("/login");
    return;
  }

  imageUrl.value = URL.createObjectURL(uploadFile.raw);
}
let uploadFirstFlag = ref(false);
let uploadSecongFlag = ref(false);
let uploadFirstAvater = ref({}); //上传的一级头像
let uploadSecondAvater = ref({}); //上传的二级头像

// 上传一级头像
async function handleUploadAvatarFlag(params) {
  uploadFirstAvater.value = params;
  uploadFirstFlag.value = true;
}

// 上传二级头像
async function handleUploadSecondAvatarFlag(first, second) {
  console.log("first, second", first, second);

  uploadFirstAvater.value = second;
  uploadSecondAvater.value = second;
  uploadSecongFlag.value = true;
}
// 上传一级评论图片
async function handleUploadFirstImg(params) {
  console.log(params);
  uploadFirstAvater.value = params;
  uploadFirstFlag.value = true;
}
// 上传二级评论图片
async function handleUploadSecondImg(first, second) {
  console.log("first, second", first, second);
  uploadFirstAvater.value = second;
  uploadSecondAvater.value = second;
  uploadSecongFlag.value = true;
}

async function handleUpload(options) {
  const { file, onSuccess, onError } = options || {};
  try {
    uploadLoading.value = true;
    const res = await requestFormData({ url: "/api/upload", data: { file } });
    if (res && res.code === 401) {
      handleUploadAuthInvalid();
      onError && onError(new Error("401 未授权"));
      return;
    }
    if (res && res.code === 0) {
      const imgUrl = res?.data?.url || res?.data?.path || res?.data || "";
      imageUrl.value = imgUrl;
      if (uploadSecongFlag.value) {
        await useFormDataStore.changeSecondAvater(
          uploadFirstAvater.value,
          uploadSecondAvater.value,
          imageUrl.value
        );
      } else {
        await useFormDataStore.changeFirstAvater(
          uploadFirstAvater.value,
          imageUrl.value
        );
      }
      onSuccess && onSuccess(res);
    } else {
      ElMessage.error(res?.message || "上传失败");
      onError && onError(new Error(res?.message || "上传失败"));
    }
  } catch (e) {
    ElMessage.error("网络错误，上传失败");
    onError && onError(e);
  } finally {
    uploadFirstFlag.value = false;
    uploadSecongFlag.value = false;
    uploadFirstAvater.value = {};
    uploadSecondAvater.value = {};
    uploadLoading.value = false;
  }
}

async function handleUploadImg(options) {
  const { file, onSuccess, onError } = options || {};
  try {
    uploadLoading.value = true;
    const res = await requestFormData({ url: "/api/upload", data: { file } });
    if (res && res.code === 401) {
      handleUploadAuthInvalid();
      onError && onError(new Error("401 未授权"));
      return;
    }
    if (res && res.code === 0) {
      const imgUrl = res?.data?.url || res?.data?.path || res?.data || "";
      imageUrl.value = imgUrl;
      if (uploadSecongFlag.value) {
        await useFormDataStore.changeSecondImg(
          uploadFirstAvater.value,
          uploadSecondAvater.value,
          imageUrl.value
        );
      } else {
        await useFormDataStore.changeFirstImg(
          uploadFirstAvater.value,
          imageUrl.value
        );
      }
      onSuccess && onSuccess(res);
    } else {
      ElMessage.error(res?.message || "上传失败");
      onError && onError(new Error(res?.message || "上传失败"));
    }
  } catch (e) {
    ElMessage.error("网络错误，上传失败");
    onError && onError(e);
  } finally {
    uploadFirstFlag.value = false;
    uploadSecongFlag.value = false;
    uploadFirstAvater.value = {};
    uploadSecondAvater.value = {};
    uploadLoading.value = false;
  }
}
async function handleImgSuccess(response, uploadFile) {
  if (response && response.code === 401) {
    handleUploadAuthInvalid();
    return;
  }
  console.log("handleImgSuccess", response);
  console.log("uploadFile", uploadFile);
}

async function beforeAvatarUpload(file) {
  const isJPG = ["image/jpeg", "image/png"].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage({
      message: "上传图片只能是 png 格式!",
      type: "warning",
    });
  }
  if (!isLt2M) {
    ElMessage({
      message: "上传图片大小不能超过 2MB!",
      type: "warning",
    });
  }
  return isJPG && isLt2M;
}
</script>

<style lang="scss" scoped>
.operate {
  line-height: normal;
}
</style>
function handleUploadAuthInvalid() {
ElMessage({ message: "登录失效，请重新登录", type: "warning" });
try {
useUserStore.$patch({ token: "", isLogin: false });
} catch (e) {}
router.push("/login");
}
