<template>
   <div class="main">
      <largeScreenHeader></largeScreenHeader>
      <div class="mainContent">
         <div class="boxLevelOne sideBoxLevelOne">
            <div class="boxLevelTwo boxLevelTwoFst">
               <boxHeader :boxHeaderText="'识别结果统计'"></boxHeader>
               <pieIDResultCount></pieIDResultCount>
            </div>

            <div class="boxLevelTwo">
               <boxHeader :boxHeaderText="'识别结果展示'"></boxHeader>
               <div class="faceContentBox">
                  <img src="../../assets/images/resultHeader.png" alt="error" class="resultHeader">
                  <table class="faceContentTable">
                     <thead>
                        <tr class="faceContentRow">
                           <th class="faceContentColume faceContentColumeSort">序号</th>
                           <th class="faceContentColume faceContentColumeIPAddr">访问地址</th>
                           <th class="faceContentColume faceContentColumeDate">访问时间</th>
                           <th class="faceContentColume faceContentColumeTime">响应时长</th>
                        </tr>
                     </thead>
                     <tbody>
                        <tr v-for="(item, index) in recognition.slice(0, 7)" :key="index"
                           :class="{ 'faceContentRowEven': index % 2 === 0, 'faceContentRowPrime': index % 2 !== 0 }">
                           <td class="faceContentColume faceContentColumeSort">{{ index + 1 }}</td>
                           <td class="faceContentColume faceContentColumeIPAddr">{{ item.ip }}</td>
                           <td class="faceContentColume faceContentColumeDate">{{ item.returnTime }}</td>
                           <td class="faceContentColume faceContentColumeTime">{{ item.responseTime }}</td>
                        </tr>
                     </tbody>
                  </table>
               </div>
            </div>
         </div>

         <div class="boxLevelOne midBoxLevelOne">
            <boxHeader :boxHeaderText="'OCR识别应用'"></boxHeader>
            <div class="pressButton">
               <button class="IDpressButtons1 ">身份证识别</button>
               <button class="invoicePressButtons1 " @click="goToInvoiceRecognition">发票识别</button>
               <button class="textPressButtons1" @click="goToTextRecognition">文本识别</button>
            </div>
            <div class="mainIdPicid">
               <img class="IDCardMainid" src="../../assets/images/IDCardMain.png" alt="error">
               <img class="IDCardMainUpid" src="../../assets/images/IDCardMainUp.png" alt="error">
               <img class="IDCardMainDownid" src="../../assets/images/IDCardMainDown.png" alt="error">

            </div>

            <div class="testIdPicId">
               <div class="IDMidReco">
                  <div class="icon">
                     <div class="text">身份证信息</div>
                     <img src="../../assets/images/IDTextBackImg.png" alt="error" class="faceThree">
                  </div>
                  <div class="content">
                     <img src="../../assets/images/borderIDCard.png" alt="error" class="backIDRecoMain">
                     <button class="commit" @click="onMount">识别</button>
                     <div class="IDCardPositive">
                        <el-upload class="upload-demo" :on-preview="handleBeforeUpload" :before-remove="beforeRemove"
                           drag :action="urlposi" accept=".jpg,.png" :limit=1 :on-change="handleUploading" ref="IDposi"
                           list-type="picture-card" :auto-upload="false" v-bind="dataList" :show-file-list="true">
                           <i slot="default" class="el-icon-plus"></i>
                           <div class="el-upload-list__item-thumbnail" slot="file" slot-scope="{file}">
                              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" :key="file.uid"
                                 style="object-fit: cover; width: 15.3rem !important; height:9.8rem; position: absolute;top:-0.8rem;left:-1.2rem">
                              <span class="el-upload-list__item-actions">
                                 <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <i class="el-icon-zoom-in"></i>
                                 </span>
                                 <span v-if="!disabled" class="el-upload-list__item-delete"
                                    @click="handleDownload(file)">
                                    <i class="el-icon-download"></i>
                                 </span>
                                 <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <i class="el-icon-delete"></i>
                                 </span>
                              </span>
                           </div>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                           <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>

                     </div>
                     <div class="IDCardNegative">

                        <el-upload class="upload-demo" :on-preview="handleBeforeUpload" :before-remove="beforeRemove"
                           drag :action="urlposi" accept=".jpg,.png" :limit=1 v-bind="dataList" :on-error="IDerror"
                           :on-change="handleUploading" :on-success="handleUploadSuccess" list-type="picture-card"
                           :auto-upload="false" ref="IDnega">
                           <i slot="default" class="el-icon-plus"></i>
                           <div slot="file" slot-scope="{file}">
                              <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""
                                 style="object-fit: cover; width: 15.3rem !important; height:9.8rem; position: absolute;top:-0.8rem;left:-1.2rem">
                              <span class="el-upload-list__item-actions">
                                 <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <i class="el-icon-zoom-in"></i>
                                 </span>
                                 <span v-if="!disabled" class="el-upload-list__item-delete"
                                    @click="handleDownload(file)">
                                    <i class="el-icon-download"></i>
                                 </span>
                                 <span v-if="!disabled" class="el-upload-list__item-delete"
                                    @click="handleRemove1(file)">
                                    <i class="el-icon-delete"></i>
                                 </span>
                              </span>
                           </div>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                           <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                     </div>
                  </div>
               </div>

               <div class="IDMidReco">
                  <div class="icon">
                     <div class="text">人脸信息</div>
                     <img src="../../assets/images/IDTextBackImg.png" alt="error" class="faceThree"
                        @click="handleImport">
                  </div>
                  <div class="content">
                     <img src="../../assets/images/borderIDCard.png" alt="error" class="backIDRecoMain">
                     <div class="tmp">
                        <ul class="tmpUl">
                           <li class="tmpLi">姓名： {{ this.name }}</li>
                           <li class="tmpLi">性别： {{ this.gender }}</li>
                           <li class="tmpLi">民族： {{ this.nation }}</li>
                           <li class="tmpLi">出生： {{ this.birth }}</li>
                           <li class="tmpLi">住址： {{ this.address }}</li>
                           <li class="tmpLi">身份号码： {{ this.id }}</li>
                           <li class="tmpLi">签发机关： {{ this.authority }}</li>
                           <li class="tmpLi">有效期： {{ this.date }}</li>

                        </ul>

                     </div>
                  </div>
               </div>

            </div>

         </div>

         <div class="boxLevelOne sideBoxLevelOne">
            <div class="boxLevelTwo boxLevelTwoFst">
               <boxHeader :boxHeaderText="'识别结果统计'"></boxHeader>
               <rectangleIDInvokeCount></rectangleIDInvokeCount>

            </div>

            <div class="boxLevelTwo boxLevelTwoSnd">
               <boxHeader :boxHeaderText="'服务响应监控'"></boxHeader>


               <div class="faceContentBox">
                  <img src="../../assets/images/resultHeader.png" alt="error" class="resultHeader">
                  <table class="faceContentTable">
                     <thead>
                        <tr class="faceContentRow">
                           <th class="faceContentColume faceContentColumeSort">序号</th>
                           <th class="faceContentColume faceContentColumeIPAddr">访问地址</th>
                           <th class="faceContentColume faceContentColumeDate">访问时间</th>
                           <th class="faceContentColume faceContentColumeTime">响应时长</th>
                        </tr>
                     </thead>
                     <tbody>
                        <tr v-for="(item, index) in ServerResult" :key="index"
                           :class="{ 'faceContentRowEven': index % 2 === 0, 'faceContentRowPrime': index % 2 !== 0 }">
                           <td class="faceContentColume faceContentColumeSort">{{ index + 1 }}</td>
                           <td class="faceContentColume faceContentColumeIPAddr">{{ item.ip }}</td>
                           <td class="faceContentColume faceContentColumeDate">{{ item.returnTime }}</td>
                           <td class="faceContentColume faceContentColumeTime">{{ item.responseTime }}</td>
                        </tr>
                     </tbody>
                  </table>
               </div>

            </div>
         </div>
      </div>

      <el-alert title="错误提示的文案" type="error" center show-icon>
      </el-alert>

   </div>


</template>

<script>

import axios from 'axios';
import { getToken } from "@/utils/auth";
import largeScreenHeader from '@/components/LargeScreen'
import boxHeader from '@/views/components/boxHeader.vue'
import pieIDResultCount from '@/views/updateIDCard/pieIDResultCount.vue'
import RectangleIDInvokeCount from '@/views/updateIDCard/rectangleIDInvokeCount.vue'

export default {
   components: {
      RectangleIDInvokeCount,
      boxHeader,
      largeScreenHeader,
      pieIDResultCount,
   },
   props: {
      value: [String, Object, Array],
      // 图片数量限制
      limit: {
         type: Number,
         default: 1,
      },
      // 大小限制(MB)
      fileSize: {
         type: Number,
         default: 5,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
         type: Array,
         default: () => ["png", "jpg", "jpeg"],
      },
      // 是否显示提示
      isShowTip: {
         type: Boolean,
         default: true,
      },
      showSize: {
         type: Boolean,
         default: true,
      },
   },
   methods: {
      onMount() {
         if (Object.keys(this.dataList).length === 0) {
            this.$modal.msgWarning("请选择文件");
            return;
         }
         if (Object.keys(this.dataList).length === 1) {
            this.$modal.msgWarning("请上传身份证正反面两张图片");
            return;
         }
         console.log(this.dataList);
         let formData = new FormData();  //  用FormData存放上传文件
         formData.append('type', 1)
         Object.keys(this.dataList).forEach(item => {
            formData.append('files', this.dataList[item].raw)
         })
         console.log(formData)
         this.$modal.loading("数据上传中，请稍后。。。");
         axios({
            url: [process.env.VUE_APP_BASE_API]+'/ai/ocr/recognition',
            data: formData,
            method: 'post',
            headers: {
               'Content-Type': 'application/x-www-form-urlencoded',
               Authorization: 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImQzNTQ2ZDI1LTJjY2ItNDQxMS1iOGMyLWEwODFiMmRiZjQyMCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.YxtEeGyp09occmm2CUYSTTIJNrq81IWYTGZoXyHPo0sMK_akGt-29DObz8_3uLoZQGpwd7xGD6gzvjbrEG3rVg' 
            },
         }).then(res => {
            alert(JSON.stringify(res))
            alert(res)
            // console.log("111"+dataToJS.name);
            // alert(res.data.result.data.name)
            // if(res.code===200 && Object.keys(res.data[0]===601)){
            //    alert('调用大模型失败')
            // }
            this.name = res.data.result.data.name;
            this.gender = res.data.result.data.gender;
            this.nation = res.data.result.data.ethnicity;
            this.birth = res.data.result.data.dateOfBirth;
            this.address = res.data.result.data.address;
            this.id = res.data.result.data.idNumber;
            this.authority = res.data.result.data.issuingAuthority;
            this.date = res.data.result.data.validTime;
            this.$modal.closeLoading();
            // this.$refs.IDnega.clearFiles();
            // this.$refs.IDposi.clearFiles();
            this.open = false;
            this.dataList = [];
            // this.baseUrl();
         }).catch(error => {

            alert('调用大模型失败')

         })
      },

      goToInvoiceRecognition() {
         this.$router.beforeEach((to, from, next) => {
            if (from.path === '/Violation') {
               // 清除缓存的操作
               // 可以使用 localStorage.clear() 或其他方法清除缓存
               localStorage.clear();
            }
            next();
         });
         this.$router.push('/Violation');
      },
      goToTextRecognition() {
         this.$router.beforeEach((to, from, next) => {
            if (from.path === '/Text') {
               // 清除缓存的操作
               // 可以使用 localStorage.clear() 或其他方法清除缓存
               localStorage.clear();
            }
            next();
         });
         this.$router.push('/Text');

      },




      // addPic(file){
      //    this.dataList.push({ url: file.url });
      // },
      handleUploadSuccess(res, file) {
         if (res.code === 200) {
            this.uploadList.push({ name: res.fileName, url: res.url });
            this.uploadedSuccessfully();
         } else {
            this.number--;
            this.$modal.closeLoading();
            this.$modal.msgError(res.msg);
            this.$refs.imageUpload.handleRemove(file);
            this.uploadedSuccessfully();
         }
      },
      IDerror() {

      },
      uploadedSuccessfully() {
         if (this.number > 0 && this.uploadList.length === this.number) {
            this.dataList = this.dataList.concat(this.uploadList);
            console.log('上传结束处理后', this.dataList);
            this.uploadList = [];
            this.number = 0;
            // console.log('传给父组件的图片字符串',this.listToString(this.dataList));
            // this.$emit("input", this.listToString(this.dataList));
            this.$emit("input", this.dataList);
            this.$modal.closeLoading();
         }
      },
      handleBeforeUpload(file) {

         let isImg = false;
         if (this.fileType.length) {
            let fileExtension = "";
            if (file.name.lastIndexOf(".") > -1) {
               fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
            }
            isImg = this.fileType.some((type) => {
               if (file.type.indexOf(type) > -1) return true;
               if (fileExtension && fileExtension.indexOf(type) > -1) return true;
               return false;
            });
         } else {
            isImg = file.type.indexOf("image") > -1;
         }

         if (!isImg) {
            this.$modal.msgError(
               `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
            );
            return false;
         }
         if (this.fileSize) {
            const isLt = file.size / 1024 / 1024 < this.fileSize;
            if (!isLt) {
               this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
               return false;
            }
         }
         this.$modal.loading("正在上传图片，请稍候...");
         this.number++;
      },
      handleUploading(file, dataList) {
         this.dataList.push(file);

         console.log(file);
         console.log(dataList);
      },
      handleUploadError(error, file, dataList) {
         console.log(error);
         console.log(file);
         console.log(dataList);
         this.dataList.push({
            url: file.url,
            uid: file.uid,
            file: file.file
         });

      },
      submitFileForm() {

      },
      handleRemove(file, dataList) {
         const index = this.dataList.indexOf(file);
         // 如果找到了文件，则从 dataList 中删除
         if (index !== -1) {
            this.dataList.splice(index, 1);
         }
         this.$refs.IDposi.clearFiles();
         console.log(this.dataList.length)
      },
      handleRemove1(file, dataList) {
         const index = this.dataList.indexOf(file);
         // 如果找到了文件，则从 dataList 中删除
         if (index !== -1) {
            this.dataList.splice(index, 1);
         }
         this.$refs.IDnega.clearFiles();
         console.log(this.dataList.length)
      },

      handleUploadError() {
         this.$modal.msgError("上传图片失败，请重试");
         this.$modal.closeLoading();
      },
      beforeRemove(file, dataList) {
         return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleImport() {
         this.open = true;
      },
      handlePictureCardPreview(file) {
         this.dialogImageUrl = file.url;
         this.dialogVisible = true;
      },
      handleDownload(file) {
         const fileUrl = file.url;
         const fileName = 'example.png';
         // 创建一个隐藏的 <a> 标签
         const link = document.createElement('a');
         link.href = fileUrl;
         link.download = fileName;
         // 将 <a> 标签添加到页面中
         document.body.appendChild(link);
         // 触发点击事件，开始下载
         link.click();
         // 下载完成后移除 <a> 标签
         document.body.removeChild(link);
      }


   },
   computed: {
      // 是否显示提示
      showTip() {
         return this.isShowTip && (this.fileType || this.fileSize);
      },
   },

   data() {
      return {
         uploadList: [],
         headers: {
            Authorization: "Bearer " + getToken(),
         },
         dialogImageUrl: '',
         dialogVisible: false,
         disabled: false,
         urlposi: '/ocr/recognition',
         dataList: [],
         open: false,
         currentDate: '',
         currentTime: '',
         dayOfWeek: '',//如果要星期的话可以直接用，此处为中文的星期
         imageUrl: '',
         IDCardPositiveUrl: '',
         IDCardNegativeUrl: '',
         name: '',
         gender: '',
         nation: '',
         birth: '',
         id: '',
         authority: '',
         address: '',
         date: '',
         recognition: [
            { ip: '192.168.1.1', returnTime: '10:00', responseTime: '100ms' },
            { ip: '192.168.1.2', returnTime: '13:00', responseTime: '130ms' },
            { ip: '192.168.1.3', returnTime: '11:00', responseTime: '120ms' },
            { ip: '192.168.1.4', returnTime: '9:00', responseTime: '20ms' }
         ],
         ServerResult: [
            { ip: '192.168.1.5', returnTime: '22:00', responseTime: '1020ms' },
            { ip: '192.168.1.6', returnTime: '22:30', responseTime: '1230ms' },
            { ip: '192.168.1.7', returnTime: '21:00', responseTime: '1120ms' },
            { ip: '192.168.1.8', returnTime: '2:00', responseTime: '220ms' },
            { ip: '192.168.1.9', returnTime: '23:59', responseTime: '240ms' },
            { ip: '192.168.1.10', returnTime: '1:30', responseTime: '980ms' },
            { ip: '192.168.1.11', returnTime: '3:45', responseTime: '1350ms' },
            { ip: '192.168.1.12', returnTime: '4:15', responseTime: '780ms' },
            { ip: '192.168.1.13', returnTime: '5:20', responseTime: '1500ms' },
            { ip: '192.168.1.14', returnTime: '6:10', responseTime: '890ms' },
            { ip: '192.168.1.15', returnTime: '6:10', responseTime: '890ms' },
            { ip: '192.168.1.16', returnTime: '6:10', responseTime: '890ms' }
         ],
         pieThree: {
            China: '34', USA: '55', Japan: '36'
         }





      }
   },

   watch: {
      value: {
         handler(val) {
            console.log('侦听', val);
            if (val) {
               // 首先将值转为数组
               const list = Array.isArray(val) ? val : this.value.split(",");
               // 然后将数组转为对象数组
               this.dataList = list.map((item) => {
                  if (typeof item === "string") {
                     if (item.indexOf(this.baseUrl) === -1) {
                        item = { name: this.baseUrl + item, url: item };
                     } else {
                        item = { name: item, url: item };
                     }
                  }
                  return item;
               });
               console.log('侦听处理后', this.dataList);
            } else {
               this.dataList = [];
               return [];
            }
         },
         deep: true,
         immediate: true,
      },
   }
}
</script>

<style scoped>
@import url('./../../assets/styles/updateIDCard.css');
</style>