<template>
  <el-dialog class="resultDiv" @mouseenter="handleEnter" @paste="(e)=>handlePase(e)" v-loading.fullscreen.lock="fullscreenLoading" :close-on-click-modal = "false"
             v-model="outerVisible" title="任务结果" width="600">
    <el-form :model="sumbitForm" label-width="auto" :rules="rules" ref="workDetailForm" style="max-width: 600px">
      <div v-if="falg">
        <el-form-item>
          &nbsp;&nbsp;  &nbsp;任务结果:{{sumbitForm.resultStatus === 2?'暂停办理':sumbitForm.resultStatus === 0?'终止任务':'完成任务'}}
        </el-form-item>
        <el-form-item v-if="sumbitForm.resultStatus === 0 ||sumbitForm.resultStatus === 1">
          &nbsp;&nbsp;  &nbsp;完成时间:{{finishTime}}
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item prop="resultStatus" label="任务结果:">
          <div>
            <el-select
                v-model="sumbitForm.resultStatus"
                placeholder="任务结果"
                size="large"
                style="width: 240px"
            >
              <el-option
                  v-for="item in selectStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </div>
        </el-form-item>
      </div>
      <div class="imgClass" v-if="falg">
        <div style="white-space: nowrap;">上传交接单：</div>
        <el-col :span="20">
          <el-row :gutter="10">
            <el-col v-for="(o, index) in filesTable" :key="o.id" :span="8"
                    style="margin-bottom: 10px; position: relative">
              <el-card :body-style="{ padding: '0px' }">
                <!-- <img :src="`${baseUrl}${o.fileUrl}`" class="image" style="max-width: 100%; height: 200px" @click="handleImageView(o.fileUrl)" /> -->
                <el-image :src="`${baseUrl}${o.fileUrl}`" class="image" style="max-width: 100%; height: 150px"
                          :preview-teleported="true" fit="contain" :preview-src-list="preList" :initial-index="index"
                />
              </el-card>
            </el-col>
          </el-row>
        </el-col>

      </div>
      <div ref="uploadDiv" v-else>
        <el-form-item label="上传交接单:">
          <el-col  :span="24">
            <el-row :gutter="10">
              <el-col v-for="(o, index) in fileEntityList" :key="o.id" :span="8"
                      style="margin-bottom: 10px; position: relative">
                <el-card :body-style="{ padding: '0px' }">
                  <!-- <img :src="`${baseUrl}${o.fileUrl}`" class="image" style="max-width: 100%; height: 200px" @click="handleImageView(o.fileUrl)" /> -->
                  <el-image :src="`${baseUrl}${o.fileUrl}`" class="image" style="     background-color: black;max-width: 100%; height: 150px"
                            :preview-teleported="true" fit="contain" :preview-src-list="viewList" :initial-index="index"
                  />

                  <Delete @click="deleteCol(o.id,o.fileUrl)" style="width: 110px; height: 20px;" />
                </el-card>
              </el-col>
            </el-row>
          </el-col>
        </el-form-item>
        <el-form-item label="  " >
          <el-upload

              v-show="uploadHidden"
              ref="upload"
              class="upload-demo"
              style="flex: auto;"
              drag
              action=""
              :on-change="handleOnChange"
              accept=".jpg,.jpeg,.png,.gif,.webp"
              v-model:file-list="fileList"
              :multiple="true"
              :auto-upload="false"
              :before-upload="handleBeforeUpload"
              :http-request="httpRequest"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖入或复制此处，或点击上传(文件可以多选)
            </div>
          </el-upload>

        </el-form-item>
        <input type="text" style="opacity: 0" ref="fileIpt">
      </div>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="outerVisible = false">关闭</el-button>
        <el-button type="primary" v-if="!falg" v-hasPermi="['business:production:onceWork:finished']" @click="onsumbit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ElButton} from "element-plus";
import {ref} from "@vue/reactivity";
import { uploadFile } from "@/api/tool/file";
import {computed, defineProps, getCurrentInstance, reactive, toRefs} from "vue";
import useUserStore from "@/store/modules/user";
import {
  selectRecordByOrderIdApi,
  updateRecordStatus,
  FileList,uploadFiles,delFile
} from "@/api/business/production/onceWorkOrder";
import {Delete, UploadFilled} from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  getList: {
    type: Function,
    default: () => { },
  },
});
const { getList } = toRefs(props);
const uploadDiv = ref(null);
const fileIpt = ref(null);
const fileList = ref([]);
const outerVisible = ref(false);
import modal from "@/plugins/modal"
const fullscreenLoading = ref<boolean>(false);
const workOrderId = ref();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const filesTable = ref<Ifile[]>();
const handlerId = ref();
const tenantId = ref();
const formHidden = ref();
const preList = ref([]);
const pasteList =ref([]);
const uploadHidden = ref(true);
const fileEntityList = ref([]);
const viewList = ref([]);
//真为查看，假为编辑
const falg = ref(false);
let refile = null;
let fileEntity:Ifile = {};
const finishTime = ref();
interface Ifile{
  id?:number;
  fileName?:string;
  url?:string;
  originalFileName?:string;
  fileUrl?:string;
}
const rules = computed(() => ({
  resultStatus: [
    { required: true, message: "任务结果不能为空"},
  ],
}));
const data = reactive({
  selectStatus: [
    {
      label: "暂停办理",
      value: 2,
      color: "#888",
    },
    {
      label: "终止任务",
      value: 0,
      color: "#2FCB81",
    },
    {
      label: "完成任务",
      value: 1,
      color: "#2FCB81",
    },

  ],
});

const { selectStatus } = toRefs(data);


const form = reactive({
  recordStatus:0,
  file:Blob,
  resultStatus:-1
})
type Tform = typeof form;
const sumbitForm = reactive<Tform>({
  file: new Blob,
  recordStatus: null,
  resultStatus:null
});
const httpRequest = (parm) => {
  // let fileEntity:Ifile = {};
  // const formData2 = new FormData();
  // formData2.append("file", parm.file);
  //
  // uploadFile(formData2).then((res:any) => {
  //   if (res.code === 200) {
  //     fileEntity.fileName = res.newFileName;
  //     fileEntity.url = res.url;
  //     fileEntity.originalFileName = res.originalFilename;
  //     fileEntity.fileUrl = res.fileName;
  //   }
  //   fileEntityList.value.push(fileEntity);
  // }).then(() => {
  //   proxy.$refs['upload'].clearFiles();
  // }).catch(() => {
  //   proxy.$refs['upload'].clearFiles();
  // })
}
function openView(id,status,userId,resultStatus,view){
  outerVisible.value = true;
  uploadHidden.value = true;
  workOrderId.value = id;
  sumbitForm.recordStatus = status;
  if(resultStatus !== -1){
    sumbitForm.resultStatus = resultStatus;
  }else{
    sumbitForm.resultStatus = null;
  }
  if(resultStatus === 0 ||resultStatus === 1){
    selectRecordByOrderIdApi({"workOrderId":id}).then((res:any)=>{
      finishTime.value = res.data[0].finishTime;
    })
  }
  sumbitForm.file = null;
  formHidden.value = status;
  falg.value = view;
  fileEntity.fileName = null;
  fileEntity.url = null;
  fileEntity.originalFileName = null;
  fileEntity.fileUrl = null;
  handlerId.value = userId;
  fileList.value = [];
  filesTable.value = null;
  pasteList.value =[];
  preList.value = [];
  viewList.value = [];
  fileEntityList.value = [];
  FileList({"masterTableName":"biz_work_order_record","masterId":id}).then((response) => {
    filesTable.value = response.data
    fileEntityList.value =response.data
    filesTable.value.forEach((file)=>{
      preList.value.push(baseUrl+file.fileUrl)
      viewList.value.push(baseUrl+file.fileUrl)
    })
  })
}
const onsumbit = () => {
  if(sumbitForm.resultStatus !== null && sumbitForm.resultStatus > -1){
    updateRecordStatus(workOrderId.value,sumbitForm.resultStatus).then(() => {
      modal.msgSuccess("提交完成");
      outerVisible.value = false;
      fileEntity= {};
      uploadFiles(workOrderId.value,fileEntityList.value);
      FileList({"masterTableName":"biz_work_order_record","masterId":workOrderId.value}).then((response) => {
        filesTable.value = response.data
        fileEntityList.value =response.data
        filesTable.value.forEach((file)=>{
          preList.value.push(baseUrl+file.fileUrl)
          viewList.value.push(baseUrl+file.fileUrl)
        })
      })
    })
    if(fileList.value.length > 0){
      proxy.$refs['upload'].submit()
    }if(pasteList.value.length > 0) {
      //uploadFiles(workOrderId.value,fileEntityList)
    }
    getList.value();
    outerVisible.value = false;
  }else{
    proxy.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        "请选择任务结果" +
        "</div>",
        { dangerouslyUseHTMLString: true }
    );
  }

}
function handleBeforeUpload(file) {
  //const formData = new FormData();
  refile = file
  // formData.append("file", file);

}
const handlePase = (e)=>{
  pasteList.value = [];

  for(let i =0 ;i<e.clipboardData.files.length;i++){
    pasteList.value.push(e.clipboardData.files[i])

  }
  if(pasteList.value.length > 0) {
    pasteList.value.forEach((file)=>{
      const formData2 = new FormData();
      formData2.append("file", file);
      uploadFile(formData2).then((res:any) => {
        let fileEntity:Ifile = {};
        if (res.code === 200) {
          fileEntity.id = res.id;
          fileEntity.fileName = res.newFileName;
          fileEntity.url = res.url;
          fileEntity.originalFileName = res.originalFilename;
          fileEntity.fileUrl = res.fileName;
        }
        console.log(res.url);
        viewList.value.push(`${baseUrl}\\${res.fileName}`);
        fileEntityList.value.push(fileEntity);
      })
    })
  }
  fileList.value = [];
}
const handleEnter = ()=>{
  if(fileList.value !== null){
    fileIpt.value.focus();
  }
  //document.getElementsByClassName("resultDiv")[0].click();
}
const deleteCol = (id,fileUrl)=>{
  fullscreenLoading.value = true;
  fileEntityList.value = fileEntityList.value.filter((file:Ifile)=>{
    if(file.fileUrl == fileUrl){

      if(file.id !== undefined){
        delFile(file.id).then(()=>{
        })
      }
    }

     return file.fileUrl !== fileUrl
  })
  viewList.value = viewList.value.filter((file)=>{
    return !file.includes(fileUrl);
  })

  if(fileEntityList.value.length === 0){
    uploadHidden.value = true;
    fileList.value = [];
  }
  fullscreenLoading.value = false;
}
const handleOnChange = (e)=>{
  fileList.value = [];
  if(e.status ==="ready"){
      const formData2 = new FormData();
      formData2.append("file", e.raw);
      uploadFile(formData2).then((res:any) => {
        let fileEntity:Ifile = {};
        console.log(res);
        if (res.code === 200) {
          fileEntity.id = res.id;
          fileEntity.fileName = res.newFileName;
          fileEntity.url = res.url;
          fileEntity.originalFileName = res.originalFilename;
          fileEntity.fileUrl = res.fileName;
        }
        viewList.value.push(`${baseUrl}\\${res.fileName}`);
        fileEntityList.value.push(fileEntity);
      })
  }
}
defineExpose({
  openView,
});
</script>
<style scoped>
.imgClass{
  display: flex;
  .el-image{
    background: #1f2d3d;
    margin: 10px;
  }
}
.inputClass{
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
}

</style>