<template>
  <div class="abstract">
    <el-tabs v-model="activeName" class="demo-tabs h-full" @tab-click="handleClick">
      <el-tab-pane label="现场图" name="1">
        <div class="xct">
          <el-button
            class="w-full mt-4"
            type="primary"
            @click="gotoDraw(BoardType.scene, -1)"
          >
            绘制平面图
          </el-button>
          <!-- <el-button
            style="width: calc(50% - 6px)"
            type="primary"
            @click="handleAiItem"
          >
            AI 平面图
          </el-button> -->
          <el-button
            class="w-full mt-4"
            style="margin-left: 0"
            type="primary"
            @click="gotoDraw(BoardType.map, -1)"
          >
            绘制方位图
          </el-button>
          <div class="phote my-4 w-full" v-for="item,index in list.xct" :key="index" v-show="item.caseFilesList?.length">
            <p class="pb-2 title1">{{item.filesTypeName}}</p>
            <div class="pmt-phote w-full flex justify-between ">
              <viewImg :list="item.caseFilesList || []"  @handleItem="handleItem" height="66px" />
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane class="h-full" label="现场照片" name="2">
        <div class="scene h-full">
          <el-button class="w-full" @click="handleAdd(['三录材料', '现场照片'])">上传</el-button>
          <!-- <el-button class="w-full my-4"  style="margin-left: 0; margin-right: 0">添加场景</el-button> -->
          <div class="scene-list">
            <div class="list">
              <div class="listItem py-2" v-for="item,index in list.xczp" :key="index">
                <div class="title1 pb-2">{{item.filesTypeName}}</div>
                  <viewImg :list="item.caseFilesList || []" @handleItem="handleItems" />
                  <div class="list2" v-for="item2,index2 in item.childrenList" :key="index2" v-show="item2.caseFilesList?.length">
                  <div class="title2">{{item2.filesTypeName}}</div>
                  <viewImg :list="item2.caseFilesList || []" @handleItem="handleItems" />
                </div>
              </div>
            </div>
          </div>
          <el-button class="w-full" @click="handledrawCasePhotos">照片制卷</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="勘验笔录" name="3">
        <div class="blfrom">
          <el-upload
            class="upload-demo"
            :multiple="false"
            :show-file-list="false"
            drag
            :limit="1"
            :before-upload="upload"
            :file-list="fileLists"
            :http-request="uploadNewFile"
            :on-success="handleSuccess"
            :on-preview="previewFile"
            :accept="accept"
            :before-remove="removeFile"
          >
            <div type="primary" :disabled="!!file">
              <div>点击或拖拽文件上传</div>
              <div class="">支持 pdf、word 上传</div>
            </div>
          </el-upload>
          <el-button class="w-full mt-4" @click="handleRecords(-1)">在线填写</el-button>
        </div>
        <div class="blList">
          <div class="bllistItem flex justify-between items-center mt-4" v-for="item,index in list.klbj" :key="index">
            <div class="truncate" :title="item.filesTitle">{{item.filesTitle}}</div>
            <el-dropdown style="width: 20px" @command="(command)=>{handleCommand(command, item)}">
              <el-icon>
                <MoreFilled />
              </el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="item.createType == 'online'" command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item command="down">下载</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
    v-model="dialogVisible"
    title="请选择场景"
    width="500"
    :before-close="handleClose"
  >
    <div>
      <el-radio-group v-model="radio">
        <el-radio style="    width: 100%;" v-for="item,index in radioList" :key="index" :value="item.num">{{item.title}}</el-radio>
      </el-radio-group>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRadioItem"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { uploadNewFile, addByMediaLiBrary, getSceneListHasAi } from "@/store/case";
import { computed, ref, reactive } from "vue";
import { addCaseFile } from "../originalPhoto/quisk";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUpload } from "@/hook/upload";
import { RouteName, router } from "@/router";
import { BoardType } from "@/store/caseFile";
import { updateByTreeFileLists, getByTreeFileLists } from "@/store/case";
import { Delete, Edit } from "@element-plus/icons-vue";
import { setTypeFile } from "../originalPhoto/quisk";
import viewImg from "@/components/viewImg/index.vue"
import { delCaseFile, } from "@/store/caseFile";
const caseId = computed(() => (router.currentRoute.value?.params?.caseId));
const active = ref(true);
const radio = ref(null);
const radioList = ref([]);
const dialogVisible = ref(false);
const list = ref({
  xct:[],
  xczp:[],
  klbj:[],
});
getList()
const srcList = [
  "https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg",
  "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
];
const settype = ref(false);
const ruleFormRef = ref(null);
const klblId = ref(0);
const fmtId = ref(0);
const pmtId = ref(0);
const activeName = ref('1');
const fileLists = ref([]);
const showModal = ref(false);
const { size, fileList, upload, removeFile, previewFile, file, accept } =
  useUpload({
    maxSize: 10 * 1024 * 1024,
    formats: [".doc", ".docx", ".pdf"],
  });
const handleClick = (tab) => {
  console.log(tab);
};
const gotoDraw = (type: BoardType, id: number) => {
  router.push({
    name: RouteName.drawCaseFile,
    params: { caseId: caseId.value!, type, id },
  });
};
function getList() {
  updateByTreeFileLists(caseId.value).then(res => {
    let newlist =  res.find(ele => ele.filesTypeName == '三录材料')?.childrenList || [];
    list.value.xct = newlist.find(ele => ele.filesTypeName == '现场图')?.childrenList || [];
    list.value.xczp = newlist.find(ele => ele.filesTypeName == '现场照片')?.childrenList || [];
    list.value.klbj = newlist.find(ele => ele.filesTypeName == '勘验笔录')?.caseFilesList || [];
    klblId.value = newlist.find(ele => ele.filesTypeName == '勘验笔录').filesTypeId
    fmtId.value = list.value.xct.find(ele => ele.filesTypeName == '平面图').filesTypeId
    pmtId.value = list.value.xct.find(ele => ele.filesTypeName == '方位图').filesTypeId
    console.log('list.value', list.value)
  })
}
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 handleActive(params) {
  console.log("handleActive", params);
}
function handleItem(type, item) {
  console.log("handleItem", type, item);
  if('edit' == type) {
    gotoDraw(item.filesTypeId != pmtId.value? BoardType.scene : BoardType.map, item.filesId)
  }
  getList()
}
async function handleItems(type, item) {
  console.log("handleItem", type, item);
  if('edit' == type) {
    await setTypeFile({
      ...item,caseId:caseId.value,
      fileOptions: list.value.xczp,
    })
  }
  getList()
}
function handleSuccess(item) {
  let uploadId = item?.data.id;
  addByMediaLiBrary({ caseId: caseId.value, filesTypeId: klblId.value, uploadId }).then((res) => {
    fileLists.value = []
    getList();
  });
}
function handleRecords(fileId = -1) {
  router.push({
    name: RouteName.records,
    params: { caseId:caseId.value, fileId },
  });
}
async function handledrawCasePhotos() {
  router.push({
    name: RouteName.drawCasePhotos,
    params: { caseId: caseId.value! },
  });
  console.log("handleAdd");
}
async function handleAdd(filesTypeName) {
  await addCaseFile({ caseId: caseId.value, filesTypeName });
  getList()
  console.log("handleAdd");
}
const handleCommand = (command: string | number | object, item) => {
  switch (command) {
    case "edit":
      handleRecords(item.filesId)
      break;
    case "delete":
      handleDel(item)
      break;
    default:
      // window.open(item.filesUrl)
      console.log("other", item);
      downloadFile(item.filesUrl, item.filesTitle)
  }
  // ElMessage(`click on item ${command}`)
}
function getExtension (name) {
      return name.substring(name.lastIndexOf("."))
}
// 下载文件
function downloadFile(sourceUrl, fileName,) {
      const link = document.createElement('a');
  link.style.display = 'none';
  // 设置下载地址
  link.setAttribute('href', sourceUrl);
  // 设置文件名
  link.setAttribute('download', fileName + getExtension(sourceUrl));
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

function handleClose(e) {
  console.log("handleClose", e);
  dialogVisible.value = false
}
function handleRadioItem() {
  console.log('handleRadioItem', radio.value)
  if(radio.value == null){
    ElMessage.error('请选择对应的场景！');
    return;
  }
  dialogVisible.value = false
  window.open(`/floorplan/index.html?m=${radio.value}`)
}
function handleAiItem() {
getSceneListHasAi(caseId.value).then((res) => {
  console.log('getSceneListHasAi', res)
  let newradioList = []
  res.data.map(ele => {
      newradioList.push(ele)
  })
  radioList.value = newradioList
  if(newradioList.length){
    dialogVisible.value = true
  }else{
    ElMessage.error('暂无支持AI 平面图的场景');
  }
});
}
function handleDel(item) {
  ElMessageBox.confirm("确定删除？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await delCaseFile({ caseId: caseId.value, filesId: item.filesId });
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getList()
  });
}
</script>
<style lang="scss" scoped>
.abstract {
  height: 100%;
  .el-tab-pane{
    height: 100%;
    overflow-y: scroll;
    position: relative;
  }
  .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;
    }
  }
}
</style>
