import { util } from '../../util/util.js'
import { base } from './base.js'
import {httpUtil} from "../../util/httpUtil.js";
import {config} from "../../config.js";
import {khcToastr} from "../alert/khcToastr.js";
import {fullMap} from "../../fullMap.js";

class inputFile extends base {
    constructor(data) {
        super(data);
        this.type='file';
        this.fileArray = [];
    }
    getFileArray(){
        return this.fileArray;
    }
    render(renderParentID) {
        let that=this;
        let data=that.data
        this.initFunc();//初始化文件上传函数
        if(data.kind==undefined||data.kind=='default'){
            that.renderDefault(renderParentID);
        }
        if(data.kind=='custom'){
            that.renderCustom(renderParentID);
        }
        if(data.kind=='text_detail'){
            that.renderTextDetail(renderParentID);
        }
    }
    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.showFileList();
    }
    setDisabled(){
        if(this.data.kind=='text_detail')return
        let eleObj = document.getElementById(this.getEleID());
        eleObj.disabled=true;
        this.disabled=true;
        eleObj.parentNode.style.display='none';
        this.showFileList();//重新渲染
    }
    removeDisabled(){
        let eleObj = document.getElementById(this.getEleID());

        eleObj.disabled=false;
        this.disabled=false;
        eleObj.parentNode.style.display='';
        this.showFileList();//重新渲染
    }
    showFileList() {
        if(this.data.kind!='text_detail'){
            document.getElementById(this.objID + 'list').innerHTML = '';
        }
        let that = this;
        for (let i = 0; i < that.fileArray.length; i++) {
            let fileInfo = that.fileArray[i];
            let showFileName=fileInfo.realFileName;
            let showLength=25;
            if(showFileName.length>showLength){//文件长度大于25时省略中间内容
                showFileName=showFileName.substring(0,10)+'...'+showFileName.substring(showFileName.length-15,showFileName.length)
            }
            let fileUrl=util.getFileUrl(fileInfo);
            let openUrl='';
            //这里由于minio和service存储的suffix有区别需要判断两个一个带点一个不带
            let suffix=fileInfo['suffix'];
            let paramsFileUrl=encodeURIComponent(fileUrl);
            // 使用btoa进行Base64编码
            paramsFileUrl = btoa(paramsFileUrl);
            //let paramsFileUrl=encodeURIComponent(fileUrl);
            if(suffix=='docx'||suffix=='.docx'){
                openUrl='../preview/docxjs/index.html?file='+paramsFileUrl;
            }
            if((suffix=='xls'||suffix=='xlsx')||(suffix=='.xls'||suffix=='.xlsx')){
                openUrl='../preview/sheetjs/index.html?file='+paramsFileUrl;
            }
            if(suffix=='pdf'||suffix=='.pdf'){
                openUrl='../preview/pdfjs/web/viewer.html?file='+paramsFileUrl;
            }
            if((suffix=='jpg'||suffix=='jpeg'||suffix=='png')||(suffix=='.jpg'||suffix=='.jpeg'||suffix=='.png')){
                openUrl='../preview/photoswipe/index.html?file='+paramsFileUrl;
            }
            let previewHtml='';
            if(openUrl!=''){
                if((suffix=='xls'||suffix=='xlsx')||(suffix=='.xls'||suffix=='.xlsx')){
                    previewHtml=`<a class="dropdown-item" href='javascript:window.open("${openUrl}");'>预览</a>`;
                }else{
                    previewHtml=`<a class="dropdown-item" href='javascript:window.open("${openUrl}","title","menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1");'>预览</a>`;
                }
            }
            let html = `
            <div class="col-sm-12 row divRow"><div class="col-sm-9" style="bottom: 3px;">
            <a href="javascript:void(0)" title="${fileInfo.realFileName}" data-toggle="dropdown" aria-expanded="false">
                ${showFileName}
             </a>
             <div class="dropdown-menu" x-placement="top-start" style="position: absolute; top: -177px; left: 0px; will-change: top, left;">
                ${previewHtml}
                <a download="${fileInfo.source=='minio'||fileInfo.source=='seaweedfs'?`${fileInfo.realFileName}`:''}" class="dropdown-item"
                                 href="${fileUrl}" title="${fileInfo.realFileName}">下载</a>
            </div>
            </div>
            <div class="col-sm-3" id="${that.eleID}${fileInfo.diskFileName}" style="text-align: right;">`
            /*let html = `
            <div class="col-sm-12 row divRow"><div class="col-sm-9" style="bottom: 3px;">
            <a href="${util.getFileUrl(fileInfo)}"
            download="${fileInfo.source=='minio'?`${fileInfo.realFileName}`:''}"
            title="${fileInfo.realFileName}"
            style="cursor:pointer;color: #0c85d0">${showFileName}</a>
            </div>
            <div class="col-sm-3" id="${fileInfo.diskFileName}" style="text-align: right;">`*/
            if(!that.disabled&&that.data.kind!='text_detail'){
                html += '<span style="cursor:pointer;">删除</span>'
            }
            html += '</div></div>'
            if(this.data.kind!='text_detail'){
                document.getElementById(that.objID + 'list').insertAdjacentHTML("beforeEnd", html);
            }else{
                document.getElementById(that.eleID).innerHTML= html;
                console.log(html)
            }

            that.removeFileFunc= ()=> {
                let fileDiskName = document.getElementById(that.eleID+fileInfo.diskFileName).getAttribute('id');
                that.fileArray = that.fileArray.filter( (item) =>{
                    return item.diskFileName != fileDiskName;
                });
                if(that.fileArray.length>=that.data.file_image_max_num){
                    util.removeEventListener(that.eleID,'change',that.uploadFileFunc)
                    util.addEventListener(that.eleID,'change',that.showMaxUploadMessage)
                }else{
                    util.addEventListener(that.eleID,'change',that.uploadFileFunc)
                    util.removeEventListener(that.eleID,'change',that.showMaxUploadMessage)
                }
                //因为调用的事件是change，导致如果同一个文件上传两次时第二次不触发change事件，所以上传完成后清空file tag的值
                document.getElementById(that.eleID).value = '';
                that.showFileList();
            }
            util.addEventListener(that.eleID+fileInfo.diskFileName,'click',that.removeFileFunc)
        }
    }
    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;
    }
    renderDefault(renderParentID){
        let that=this;
        let data=that.data;
        let canNull = that.data.can_null;
        let labelName = that.data.label_name;
        let defaultValue=data.default_value;
        let isReadOnly=data.is_read_only;
        that.initFormCol(that);
        let questionCircleHtml=that.getQuestionCircleIconHtml();
        let htmlTemplate=`
        <div class="form-group row col-sm-${data.col}" id="${that.objID}" name="${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">
        <label class="custom-file">
        <input type="file" id="${that.eleID}" name="${data.name}" class="custom-file-input" accept="${data.accept}">
        <span class="custom-file-label"></span>
        </label>
        <small class="form-text text-muted"><font style="display:none;"  validate="validate"  color="red">12412345123</font></small>
        <div class="form-group row col-sm-${data.col}" id="${that.objID}list" name="${data.name}list">
        </div></div>
        `;
        document.getElementById(renderParentID).insertAdjacentHTML("beforeEnd", htmlTemplate);
        util.addEventListener(that.eleID,'change',that.uploadFileFunc)
        that.bindValueValidate();
        if(!util.isNull(defaultValue)){
            that.setValue(defaultValue)
        }
        if (isReadOnly == 'Y') {
            that.setDisabled();
        }
    }
    initFunc(){
        let that=this;
        that.uploadFileFunc= ()=> {
            let fileList = document.getElementById(that.eleID).files;
            let file = fileList[0];
            let params = new FormData();
            params.append("uploadFile", file, file.name);
            if(that.data.upload_file_to_type==undefined){
                that.data.upload_file_to_type='seaweedfs';
            }
            params.append("upload_file_to_type",that.data.upload_file_to_type);
            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}
            fullMap.getObj('mask').show('正在上传...')
            httpUtil.post(obj, (response)=>{
                let fileInfo = response.data.data.fileInfo;
                if(!(that.fileArray instanceof Array)){
                    that.fileArray=[];
                }
                that.fileArray.push(fileInfo);
                that.showFileList();
                fullMap.getObj('mask').hide();
                if(that.fileArray.length>=that.data.file_image_max_num){
                    util.removeEventListener(that.eleID,'change',that.uploadFileFunc)
                    util.addEventListener(that.eleID,'change',that.showMaxUploadMessage)
                }else{
                    util.addEventListener(that.eleID,'change',that.uploadFileFunc)
                }
            })
            //因为调用的事件是change，导致如果同一个文件上传两次时第二次不触发change事件，所以上传完成后清空file tag的值
            document.getElementById(that.eleID).value = '';
        }
        that.showMaxUploadMessage=()=>{
            if(that.fileArray.length>=that.data.file_image_max_num){
                khcToastr.showErrorMessage('最大上传附件数量：'+that.data.file_image_max_num);
            }else{
                that.uploadFileFunc();
            }
        }
    }
    renderCustom(renderParentID){
        let that=this;
        let data=that.data
        let obj=document.getElementById(renderParentID).querySelector('[name="' + data.name + '"]');
        if(obj==null){
            let hiddenFieldsDiv=document.getElementById(renderParentID).querySelector('div[name="hiddenFields"]');
            let hiddenHtmlTemplate=`<input type="hidden" name="${data.name}" id="${that.eleID}" value="">`;
            hiddenFieldsDiv.insertAdjacentHTML("beforeEnd", hiddenHtmlTemplate)
        }else{
            obj.setAttribute("id", that.eleID);
            document.getElementById(renderParentID).querySelector('[name="' + data.name + 'div"]').setAttribute("id", that.objID);
            document.getElementById(renderParentID).querySelector('[name="' + data.name + 'list"]').setAttribute("id", that.objID+'list');
            util.addEventListener(that.eleID,'change',that.uploadFileFunc)
        }
    }
    bindValueValidate(){
        let that=this;
        that.validateFunc= ()=>{
            that.validate();
        }
        let eleObj=document.getElementsByName(that.eleID);
        for (let i = 0; i < eleObj.length; i++) {
            util.addEventListener(eleObj[i],'click',that.validateFunc)//点击后校验
        }
    }
    renderTextDetail(renderParentID){
        let that=this;
        let data=that.data
        let html=`<tr>
                                <th>${data.label_name}</th>
                                <td name="${data.name}" id="${that.eleID}"></td>
                            </tr>`
        document.getElementById(renderParentID).insertAdjacentHTML("beforeEnd",html);
    }
    
}
export { inputFile }