<template>
  <div class="abstract">
    <div class="blList">
      <div
        class="listItem"
        v-for="(item, index) in list"
        @click="handleItem(item)"
        :class="{ active: active.filesTypeId == item.filesTypeId }"
        :key="index"
      >
        <div class="title">{{ item.filesTypeName }}</div>
      </div>
    </div>
    <div class="abstractCentenr">
      <div class="centerTop" v-show="!show">
        <el-upload
          class="upload-demo upload"
          drag
          :before-upload="upload"
          :file-list="fileList"
          :http-request="uploadNewFile"
          :on-success="handleSuccess"
          :on-preview="previewFile"
          :show-file-list="false"
          :accept="accept"
          :before-remove="removeFile"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          multiple
        >
          <el-icon class="el-icon--upload" style="margin-top: 20px" size="26"
            >
            <i style="font-size: 26px; color: #26559B" class="iconfont icon-Upload"></i>
            <!-- <upload-filled /> -->
            </el-icon>
          <div class="el-upload__text">
            点击或拖拽文件上传<br />支持 jpg、png、jpeg、doc、pdf ≤ 500MB
          </div>
        </el-upload>
      </div>
      <div class="centerBottom">
        <div class="dossierList">
          <div
            class="item"
            v-for="(item, index) in active.caseFilesList"
            :key="index"
          >
            <div class="itemLeft">
              <i
                :class="'iconfont icon-word'"
                v-if="getExtension(item.filesUrl, 'word')"
                style="font-size: 32px"
              ></i>
              <i
                :class="'iconfont icon-PDFtubiao'"
                v-else-if="getExtension(item.filesUrl, 'pdf')"
                style="font-size: 32px"
              ></i>
              <el-image
                class="itemLeftImg"
                v-else
                style="width: 40px; height: 40px"
                :src="item.filesUrl"
                :key="item.filesUrl"
                :initial-index="srcList.findIndex(ele => ele === item.filesUrl)"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="srcList"
                show-progress
                fit="cover"
              />
              <!-- <img class="itemLeftImg" @click="handleView"  :src="item.filesUrl" alt="" /> -->
              <div class="itemText" :title="item.filesTitle">
                {{ item.filesTitle }}
              </div>
            </div>
            <div class="operation">
              <el-icon title="下载"
                size="16px"
                @click="downloadByUrl({ fileName: item.filesTitle, url: item.filesUrl })"
                ><Download
              /></el-icon>
              <el-icon size="16px" @click="handleDel(item)" v-show="!show" title="删除"
                ><CircleClose
              /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from "vue";
import { addCaseFile } from "../originalPhoto/quisk";
import { ElMessage, ElMessageBox } from "element-plus";
import { uploadNewFile, addByMediaLiBrary, show } from "@/store/case";
import { updateByTreeFileLists } from "@/store/case";
import viewImg from "@/components/viewImg/index.vue";
import { useUpload } from "@/hook/upload";
import { downloadFile, downloadByUrl } from "@/util/index.ts";
import { delCaseFile } from "@/store/caseFile";
import { router } from "@/router";
const srcList = ref([]);
const settype = ref(false);
const ruleFormRef = ref(null);
const active = ref({
  filesTypeId: 0,
  caseFilesList: [],
});
const list = ref([]);
const fileList = ref([]);
const ssjId = ref(0);
const zjjId = ref(0);
const showModal = ref(false);
const caseId = computed(() => router.currentRoute.value?.params?.caseId);
const fileInfo = ref({
  accept: ".jpg, .jpeg, .png, .mp4",
  formats: [".jpg", ".png", ".jpeg", ".doc", ".docx", ".pdf"],
  DrawFormatDesc: "jpg、png、jpeg、doc、pdf上传",
  fileSize: 500 * 1024 * 1024,
});
const { size, removeFile, previewFile, file, accept } = useUpload({
  maxSize: fileInfo.value.fileSize,
  formats: fileInfo.value.formats,
});
getList();
const handleClick = (tab) => {
  console.log(tab);
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
function getList() {
  updateByTreeFileLists(caseId.value).then((res) => {
    let newlist = res.find((ele) => ele.filesTypeName == "案件卷宗") || [];
    list.value = newlist.childrenList || [];
    if(show.value){//展示也过滤现场照片空数据
      list.value = list.value?.filter(element => element.caseFilesList) || []
    }
    ssjId.value = newlist.childrenList.find(
      (ele) => ele.filesTypeName == "诉讼卷"
    ).filesTypeId;
    zjjId.value = newlist.childrenList.find(
      (ele) => ele.filesTypeName == "证据卷"
    ).filesTypeId;
    let activeIndex =
      list.value.findIndex(
        (item) => item.filesTypeId == active.value.filesTypeId
      ) || 0;
    if (!active.value.filesTypeId) {
      activeIndex = 0;
    }
    let activeItem = list.value[activeIndex];
    active.value.filesTypeId = activeItem.filesTypeId;
    active.value.caseFilesList = activeItem.caseFilesList;
    let newsrcList = [];
    activeItem.caseFilesList.map((ele) => {
      if (isImage(ele.filesUrl)) {
        newsrcList.push(ele.filesUrl);
      }
    });
    srcList.value = newsrcList;

    console.log("list.value", list.value);
  });
}
const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
};
function handleSuccess(item) {
  let uploadId = item?.data.id;
  addByMediaLiBrary({
    caseId: caseId.value,
    filesTypeId: active.value.filesTypeId,
    uploadId,
  }).then((res) => {
    getList();
  });
}

const upload = async (file: File) => {
  const fileType = file.name
    .substring(file.name.lastIndexOf("."))
    .toUpperCase();
  let imgList = [".jpg", ".png", ".jpeg", ".doc", ".docx", ".pdf"];
  let fileList = [".doc", ".docx", ".pdf"];
  if (!imgList.some((type) => type.toUpperCase() === fileType)) {
    ElMessage.error(`请上传pdf、word 格式文件和 jpg、png、jpeg格式图片`);
    return false;
  } else if (fileList.includes(fileType.toLowerCase()) ? file.size > 500 * 1024 * 1024 : file.size > 10 * 1024 * 1024) {
    ElMessage.error(
      `请上传≤10MB jpg、png、jpeg格式图片，及≤500MB pdf、doc文件`
    );
    return false;
  } else {
    return file;
  }
};
function handleActive(params) {
  console.log("handleActive", params);
}
function getExtension(name, type) {
  if (!name) return true;
  let fileType = name.substring(name.lastIndexOf("."));
  console.log("getExtension", fileType, type, name);
  let fileList = [".doc", ".docx"];
  if (type == "pdf" && fileType == ".pdf") {
    return true;
  }
  if (type == "word" && fileList.includes(fileType)) {
    return true;
  }

  if (type == "word" && fileList.includes(fileType)) {
    return true;
  }
  return false;
  // if(fileList.includes(fileType)){
  //   return 'word'
  // }
  // return 'img'
}
async function handleAdd() {
  await addCaseFile({
    caseId: caseId.value,
    fileInfo: fileInfo.value,
    filesTypeName: ["案件卷宗"],
  });
  getList();
}
async function handleView() {
  await addCaseFile({
    caseId: caseId.value,
    fileInfo: fileInfo.value,
    filesTypeName: ["案件卷宗"],
  });
  getList();
}

function handleDel(file) {
  ElMessageBox.confirm("确定删除？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await delCaseFile({ caseId: caseId.value, filesId: file.filesId });
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getList();
  });
}
const handleviewer = (file) => {
  showModal.value = true;
  console.log("file", file);
};
const handleItem = (item) => {
  console.log("handleClick", item);
  active.value.filesTypeId = item.filesTypeId;
  active.value.caseFilesList = item.caseFilesList;
  let newsrcList = [];
  item.caseFilesList.map((ele) => {
    if (isImage(ele.filesUrl)) {
      newsrcList.push(ele.filesUrl);
    }
  });
  srcList.value = newsrcList;
};
</script>
<style lang="scss" scoped>
.abstract {
  height: 100%;
  display: flex;

  .el-form-item--label-top {
    margin-bottom: 14px;
  }
  .form-content {
    height: calc(100vh - 225px);
    overflow-y: scroll;
  }
  .demo-tabs {
    .el-tabs__item {
      height: 32px;
      line-height: 32px;
    }
  }
  .blList {
    width: var(--leftwidth);
    height: 100%;
    overflow-x: scroll;
    .name {
      color: #26559b;
    }
    .listItem {
      padding: 24px 48px;
      width: calc(var(--leftwidth) - 0px);
      cursor: pointer;
      
        &:hover{
          background: rgba(69,144,255,0.1);;
        }
    }
    .active {
      background: rgba(69, 144, 255, 0.1);
    }
  }
  .abstractCentenr {
    background: #f5f5f5;
    height: 100%;
    width: calc(100% - var(--leftwidth));
    padding: 32px;
    .centerTop {
      height: 148px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 32px;
      .upload {
        height: 100%;
        width: 100%;
      }
      .import {
        margin-right: 20px;
        padding-top: 40px;
        height: 100%;
        width: 148px;
        text-align: center;
        background: #fff;
      }
    }
    .centerBottom {
      .selcet {
        // float: right;
        // text-align: right;
        display: flex;
        justify-content: space-between;
      }
      .dossierList {
        .item {
          background: #fafafa;
          border: 1px solid #d9d9d9;
          padding: 0 42px;
          border-radius: 2px;
          width: 100%;
          height: 80px;
          line-height: 80px;
          display: flex;
          justify-content: space-between;
          margin-bottom: 15px;
          .itemLeft {
            display: flex;
            width: calc(100% - 78px);
            align-items: center;
            .itemText {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              width: calc(100% - 80px);
            }
            .iconfont {
              margin-right: 20px;
            }
            .itemLeftImg {
              width: 32px;
              height: 32px;
              margin-right: 20px;
              border-radius: 2px;
            }
          }
          .operation {
            .el-icon {
              cursor: pointer;
              margin: 10px;
            }
          }
        }
      }
    }
  }
}
</style>
