import { util } from '../../util/util.js'
import { base } from './base.js'
import {httpUtil} from "../../util/httpUtil.js";
import {config} from "../../config.js";
import PhotoSwipeLightbox from "../../../../css/vendor/libs/photoswipe/photoswipe-lightbox.esm.js";
import {fullMap} from "../../fullMap.js";
import {khcPhoto} from "../alert/khcPhoto.js";
import {khcToastr} from "../alert/khcToastr.js";

class inputImage extends base {
    constructor(data) {
        super(data);
        this.type='img';
        this.fileArray = [];
        this.imageStatusData={};
    }
    getFileArray(){
        return this.fileArray;
    }
    render(parentObjID) {
        let data=this.data
        this.initFunc();//初始化文件上传函数
        if(data.kind==undefined||data.kind=='default'){
            this.renderDefault(parentObjID);
        }
        if(data.kind=='custom'){
            this.renderCustom(parentObjID);
        }
    }
    getValue() {
        return this.fileArray;
    }
    setValue(fileArray) {
        if (typeof fileArray == 'string') {
            if (fileArray == '') {
                this.fileArray=[];
            }else{
                this.fileArray = JSON.parse(fileArray);
            }
        } else {
            this.fileArray = fileArray;
        }
        this.showImageList();
    }
    showImageList() {
        let that = this;
        document.getElementById(that.objID + 'photoswipe-example-form').innerHTML = '';
        let fileArray=that.fileArray;
        let html='';
        for (let i = 0; i < fileArray.length; i++) {
            this.imageStatusData[fileArray[i].diskFileName]='hide';
            let fileInfo=fileArray[i];
            let imageUrl='';
            let imageAwsUrl='';
            if(fileArray[i].source=='minio'){
                imageUrl=config.getMinioUrl()+'/'+fileInfo.diskFileName;
                imageAwsUrl=config.getAwsUrl()+'/'+that.imageAwsSize+'/'+fileInfo.diskFileName
            }
            if(fileArray[i].source=='service'){
                imageUrl=config.getConfigJson().downFileUrl+'?realFileName=' + fileInfo.realFileName + '&fileDiskName=' + fileInfo.diskFileName + '&suffix=' + fileInfo.suffix;
                imageAwsUrl=config.getConfigJson().downFileUrl+'?realFileName=' + fileInfo.realFileName + '&fileDiskName=' + fileInfo.diskFileName + '&suffix=' + fileInfo.suffix;
            }
            html += `     <div class="col-sm-${that.imageCol} mb-4" id="${fileInfo.diskFileName}mouseout_form">
                            <a id="${fileInfo.diskFileName}mouseover_form" class="img-thumbnail img-thumbnail-zoom-in" href="${imageUrl}" data-pswp-width="${fileInfo.width}" data-pswp-height="${fileInfo.height}" target="_blank">                            
                            <span class="img-thumbnail-overlay bg-white opacity-75" title="点击查看原图"></span>
                            <span class="img-thumbnail-content display-4 text-secondary" title="点击查看原图"><i class="ion ion-ios-search"></i></span>
                            <img src="${imageAwsUrl}" alt="" style="width:100%;height:100%">
                            </a>
                            <button id="${fileInfo.diskFileName}_form" type="button" name="deleteImage" class="btn btn-xs btn-danger mr-2" style="display: none"><span class="far fa-trash-alt"></span>&nbsp;删除</button>
                            </div>`
        }
        let spanCss='cursor:pointer;'
        if(fileArray.length>0){
            spanCss='cursor:pointer;margin-top: 40px'
        }
        html += `     <div class="col-sm-4" id="${that.objID}_upload_button_div" style="${that.data.is_show_image_button=='N'?'display:none':''}">
                        <span id="${that.eleID}upload" style="${spanCss}" class="ticket-assignee-add bg-lighter text-muted mb-3" title="上传图片">
                        <span class="ui-icon bg-primary border-0 text-white">
                        <i class="ion ion-md-add "></i>
                        </span>
                        </span>
                      </div>`
        document.getElementById(that.objID + 'photoswipe-example-form').insertAdjacentHTML("beforeEnd", html);
        for (let i = 0; i < fileArray.length; i++) {
            document.getElementById(fileArray[i].diskFileName+'mouseover_form').addEventListener('mouseover', ()=>{
                that.setImageStatusById(fileArray[i].diskFileName);
                if(that.data.is_show_image_button=='Y'){
                    document.getElementById(fileArray[i].diskFileName+'_form').style.display=''
                }
            })
            document.getElementById(fileArray[i].diskFileName+'mouseout_form').addEventListener('mouseout', ()=>{
                that.imageStatusData[fileArray[i].diskFileName]=true;
                setTimeout( ()=>{
                    let imageStatus=that.imageStatusData[fileArray[i].diskFileName];
                    if(imageStatus){
                        document.getElementById(fileArray[i].diskFileName+'_form').style.display='none'
                    }
                },1000)
            })
            if(that.data.is_show_image_button=='Y'){
                document.getElementById(fileArray[i].diskFileName+'_form').addEventListener('mouseover', ()=>{
                    that.setImageStatusById(fileArray[i].diskFileName);
                    document.getElementById(fileArray[i].diskFileName+'_form').style.display=''
                })
                document.getElementById(fileArray[i].diskFileName+'_form').addEventListener('click', ()=>{
                    let fileDiskName = fileArray[i].diskFileName;
                    that.fileArray = that.fileArray.filter( (item)=> {
                        return item.diskFileName != fileDiskName;
                    });
                    that.showImageList();
                })
            }
        }
        if(that.data.is_show_image_button=='Y'){
            document.getElementById(that.eleID+'upload').addEventListener('click', ()=>{
                if(fileArray.length>=that.data.file_image_max_num){
                    khcToastr.showErrorMessage('最大上传图片数量：'+that.data.file_image_max_num);
                }else{
                    document.getElementById(that.eleID).click()
                }
            })
        }
        let imageId='#'+that.objID+'photoswipe-example-form';
        khcPhoto.init({gallery:imageId});
    }
    hide(){
        if(this.data.kind==undefined||this.data.kind=='default'){
            document.getElementById(this.objID).setAttribute('style', 'display:none');//隐藏
        }
        if(this.data.kind=='custom'){
            document.getElementById(this.objID).parentNode.parentNode.setAttribute('style', 'display:none');//隐藏
        }
    }
    show(){
        if(this.data.kind==undefined||this.data.kind=='default'){
            document.getElementById(this.objID).setAttribute('style', '');//展示
        }
        if(this.data.kind=='custom'){
            document.getElementById(this.objID).parentNode.parentNode.setAttribute('style', '');//展示
        }
    }
    //限制文件类型P()
    setAccept(accept){
        this.data.accept=accept;
        document.getElementById(this.eleID).accept=accept;
    }
    initFormCol(obj) {
        let form=fullMap.getObj(obj.data.parentObjID)
        //undefined是查询输入框，两个输入框占一行，所以比例要调整一下
        //modals是弹出模态框，模态框本身就小，比例也要调整一下
        if(form==undefined||form.formShowType=='modals'){
            obj.labelCol=3;
            obj.inputCol=9;
            obj.imageCol=4;
            obj.imageAwsSize='150x130';
        }else{
            obj.labelCol=2;
            obj.inputCol=10;
            obj.imageCol=2;
            obj.imageAwsSize='200x160';
        }
    }
    renderDefault(parentObjID){
        let that=this;
        let canNull = that.data.can_null;
        let labelName = that.data.label_name;
        this.data.accept='.jpg,.png,.jpeg';//todo 图片格式暂时写死
        that.initFormCol(that);
        let questionCircleHtml=that.getQuestionCircleIconHtml();
        let htmlTemplate=`
        <div class="form-group row row col-sm-${that.data.col}" id="${that.objID}" name="${that.data.name}div" style="display: none">
        <label class="col-form-label col-sm-${that.labelCol} text-sm-right" style="line-height:30px;vertical-align: middle;">
        <font id="${that.objID}CanNull" style="font-size: 22px;vertical-align: middle;${canNull!='Y'?'display:none;':''}" color="red">*</font>
        ${labelName}
        ${questionCircleHtml}
        </label>
        <div class="col-sm-${that.inputCol} demo-vertical-spacing-sm">
        <div id="${that.objID}photoswipe-example-form" class="row pswp-gallery pswp-gallery--single-column">
        </div>
        <input style="display: none" type="file" id="${that.eleID}" name="${that.data.name}" class="custom-file-input" accept="${that.data.accept}">
        <small class="form-text text-muted"></div><font style="display:none;"  validate="validate"  color="red">12412345123</font></small>
        </div></div>
        <div class="form-group row" id="${that.objID}list" name="${that.data.name}list">
        `;
        document.getElementById(parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
        util.addEventListener(that.eleID,'change',that.uploadFileFunc)
    }
    initFunc(){
        let that=this;
        this.uploadFileFunc= ()=> {
            let fileList = document.getElementById(that.eleID).files;
            let file = fileList[0];
            let img=new Image();
            let url = window.URL || window.webkitURL;
            img.src=url.createObjectURL(file)
            img.onload= function (){
                let imgInfo=this;
                let fileFullName = file.name;
                let lastPoint = fileFullName.lastIndexOf(".");
                let params = new FormData();
                params.append("uploadFile", file, file.name);
                params.append("upload_file_to_type",that.data.upload_file_to_type);
                params.append("width",imgInfo.width);
                params.append("height",imgInfo.height);
                const selfConfig = {
                    headers: {
                        "Content-Type": "multipart/form-data;boundary=" + new Date().getTime(),
                        Authorization:'Bearer '+config.getToken()}
                };
                let obj={url:config.getConfigJson().upFileUrl,params:params,config:selfConfig}
                httpUtil.post(obj, (response)=>{
                    let fileInfo = response.data.data.fileInfo;
                    if(!(that.fileArray instanceof Array)){
                        that.fileArray=[];
                    }
                    that.fileArray.push(fileInfo);
                    that.showImageList();
                    //因为调用的事件是change，导致如果同一个文件上传两次，第二次不触发change事件，所以上传完成后清空file tag的值
                    document.getElementById(that.eleID).value = '';
                })
            }
        }
    }
    //指定图片大小
    setImageStatusById(imageId){
        let that=this;
        let fileArray=that.fileArray;
        for (let i = 0; i < fileArray.length; i++) {
            if(fileArray[i].diskFileName!=imageId){
                that.imageStatusData[fileArray[i].diskFileName]=true;
                document.getElementById(fileArray[i].diskFileName+'_form').style.display='none'
            }
        }
        that.imageStatusData[imageId]=false;

    }
    renderCustom(parentObjID){
        let that=this;
        let data=that.data
        let obj=document.getElementById(parentObjID).querySelector('[name="' + data.name + '"]');
        console.log('show my layout name：'+data.name+"    eleID："+that.eleID)
        obj.setAttribute("id", that.eleID);
        document.getElementById(parentObjID).querySelector('[name="' + data.name + 'div"]').setAttribute("id", that.objID);
        document.getElementById(parentObjID).querySelector('[name="' + data.name + 'list"]').setAttribute("id", that.objID+'list');
        util.addEventListener(that.eleID,'change',that.uploadFileFunc)
    }
    
}
export { inputImage }