<template>
  <div class="efuture-filebox" v-show="myConfig.visible" :style="divStyle">
      <Input
      ref="myControl"
      v-model="filename"
      :size="myConfig.size"
      :placeholder="myConfig.placeholder"
      :disabled="myConfig.readOnly"
      :readonly="true"
    >
    <template #prepend>
        <p  v-if="!filename" @click.stop="uploadClick" style="cursor:pointer;width:30px">
            <Icon custom="iconfont icon-custom-shangchuanlogo"  :color="iconColor"/>
        </p>
         <p v-else @click.stop="uploadClick" style="cursor:pointer;width:30px">
            <Icon type="md-checkmark-circle" size="18" :color="iconColor2"/>
        </p>
    </template>
    </Input>
      <div v-if="!!filename" class="filebtn">
          <Row type="flex" justify="center" align="middle"  :gutter="16">
              <Col v-if="showPreview" style="cursor:pointer">
                 <p  @click.stop="searchFile">
                    预览
                 </p>
              </Col>
              <Col style="cursor:pointer" v-if="showDownBtn" >
                <p  @click.stop="downFile">
                    下载
                 </p>
              </Col>
               <Col style="cursor:pointer"  v-if="!myConfig.readOnly && showDelBtn">
                <p  @click.stop="delFile">
                    删除
                 </p>
              </Col>

          </Row>
     </div>
     <div ref="photo" v-show="false">
        <li><img  :src="imgUrl" :data-original="`${imgUrl}`" style="width: 100%; height: 100%;" /></li>
    </div>
    <Modal :styles="{top:'20px', width:'80%'}"  title="文本"  v-model="txtPanelFlag"  :footer-hide="true">
        <div v-html="textStr"/>
    </Modal>
      <Modal :styles="{top:'20px', width:'80%'}"  title="PDF"  v-model="pdfFlag"  :footer-hide="true">
        <div ref="pdf" style="height:630px"/>
    </Modal>
    <UploadBox ref="uploadbox" v-show="false" :config="myConfig" :readOnly="myConfig.readOnly" @success="handleSuccess" :headers="headers"  :multiSelect="false">
    </UploadBox>
 </div>
</template>
<script>
    import Base from '@/components/base/controlbase.vue';
    import UploadBox from './uploadbox.vue';
    import Viewer from 'viewerjs';
    import {embed} from 'pdfobject';
    import $ from 'jquery';
    export default {
        name: 'picturebox',
        extends: Base,
        data () {
            return {
                myConfig:{
                    fileNum: 1,
                    fileSize: 20,
                    placeholder:'请上传文件',
                    notdelfile:'N',
                    downfile:'',
                    delfile:'',
                    pdffile:'/mss-sysconf-boot/downloadPdf?filekey=',
                    scenetype:'1',
                    proName:{
                        'billmoduleid':'billmoduleid',
                        'billno':'billno'
                    },
                },
                visible: false,
                headers:{
                    'billmoduleid':'',
                    'billno':''
                },
                filename:'',
                userInfo:'',
                value:'',
                fileSize:20480,
                showDelBtn:true,
                showDownBtn:true,
                showPreview:true,
                style: {},
                defaultvalue:'',
                divStyle:{},
                fileinfo:{},
                imgUrl:'',
                txtPanelFlag:false,
                pdfFlag:false
            };
        },
        components:{
          UploadBox
        },
        computed:{
            iconColor () {
                if (this.myConfig.readOnly) {
                    return '#e3e5e8';
                } else {
                    return '#f3b352'
                }
            },
            iconColor2 () {
                if (this.myConfig.readOnly) {
                    return '#e3e5e8';
                } else {
                    return '#739943'
                }
            }
        } ,
        props:{
            fileKey:{
                type:String,
                default:''
            }
        },
        methods: {
            customInit() {
                if (this.myConfig.fileSize) {
                    this.fileSize = Number(this.myConfig.fileSize) * 1024;
                }
                if (this.myConfig.showDelBtn !== undefined) {
                    this.showDelBtn = this.myConfig.showDelBtn;
                }
                if (this.myConfig.showDownBtn !== undefined) {
                    this.showDownBtn = this.myConfig.showDownBtn;
                }
                if (this.myConfig.showPreview !== undefined) {
                    this.showPreview = this.myConfig.showPreview;
                }
                if (this.myConfig.headers !== undefined) {
                    this.headers = Object.assign({},this.headers,this.myConfig.headers);
                }

                if (!this.myConfig.downfile) {
                    this.myConfig.downfile =  this.OmdUrl.downfile;
                }
                if (!this.myConfig.delfile) {
                    this.myConfig.delfile =  this.OmdUrl.delfile;
                }
                if (!this.myConfig.uploadfile) {
                    this.myConfig.uploadfile =  this.OmdUrl.uploadfile;
                }
                if (!this.myConfig.pdffile) {
                    this.myConfig.pdffile = this.OmdUrl.pdffile;
                }
                let usercode = this.getUserCode();
                let username = this.getUserName();

                let userInfo = '&usercode=' + usercode + '&username=' + username + '&ent_id=' + this.getEnt_id();
                let notdelfile = this.myConfig.notdelfile;
                if  (this.myConfig.notdelfile !== undefined) {
                    notdelfile = this.myConfig.notdelfile;
                }
                if (notdelfile !== 'Y') {
                    userInfo = userInfo + '&notdelfile=N';
                } else  {
                    userInfo = userInfo + '&notdelfile=Y';
                }
                this.userInfo = encodeURI(userInfo);
                let url = 'ent_id=' + this.getEnt_id() +'&token=' + this.getToken();
                if (this.myConfig.uploadfile.indexOf('?') != -1) {
                    this.myConfig.uploadfile  = this.myConfig.uploadfile + '&' + encodeURI(url);
                } else {
                    this.myConfig.uploadfile  = this.myConfig.uploadfile + '?' + encodeURI(url);
                }
                this.headers = {};
                this.initFile();
            },
            initFile() {
                let value  = this.fatherValue;
                if (this.fileKey) {
                    value = this.fileKey;
                }
                this.refurbish(value);
                if (this.$refs.uploadbox) {
                    this.$refs.uploadbox.clearData();
                }
            },
            handleSuccess (obj) {
                this.setFileData([obj.data]);
                this.setFatherValue();
                if (this.config.onOpenChange) {
                    this.config.onOpenChange(false);
                }
            },
            refurbish(value) {
                if (value) {
                    this.getFileInfo(value,this.setFileData);
                } else {
                    this.fileinfo = {};
                    this.filename = '';
                }
            },
            setFileData (data) {
                if (data && data.length > 0) {
                    this.fileinfo = data[0];
                    this.filename = this.fileinfo.filename;
                    this.value = this.fileinfo.filekey;
                } else {
                    this.fileinfo = {};
                    this.filename = '';
                    this.value = '';
                }
            },
            delFile() {
                if (this.fileinfo.delUrl) {
                    this.asyncPost(encodeURI(this.fileinfo.delUrl),'',{},null,null,null,'get');
                    this.value = '';
                    this.filename = '';
                    this.fileinfo = '';
                    this.setFatherValue();
                }
            },
            downFile () {
                if (this.fileinfo.downUrl) {
                    window.open(encodeURI(this.fileinfo.downUrl), '_self');
                }
            },
             searchFile() {
                if (this.isType(this.fileinfo.filetype) === '1') {
                    this.showTxt();
                }
                if (this.isType(this.fileinfo.filetype) === '2') {
                    this.showPhoto();
                }
                if (this.isType(this.fileinfo.filetype) === '3') {
                    this.showPdf();
                }
            },
            showTxt() {
                let downUrl = this.myConfig.downfile + this.fileinfo.filekey  + '&token=' + this.getToken() ;
                let htmlObj = $.ajax({
                    url : encodeURI(downUrl),
                    async : false
                });
                let str = htmlObj.responseText;
                str = str.replace(/\r\n/ig, '<br/>');
                this.textStr =str;
                this.txtPanelFlag = true;
            },
            showPhoto() {
                let downUrl = this.myConfig.downfile + this.fileinfo.filekey + '&token=' + this.getToken();
                this.imgUrl = downUrl;
                this.$nextTick(()=> {
                    if (this.viewer == undefined) {
                        this.viewer =  new Viewer(this.$refs.photo, {
                            url: "data-original",
                            show: function () {
                                this.viewer.update();
                            },
                        });
                    }
                    this.viewer.show();
                });
            },
            showPdf() {
                let pdfUrl = this.myConfig.pdffile + this.fileinfo.filekey + '&token=' + this.getToken();
                embed(encodeURI(pdfUrl), this.$refs.pdf);
                this.pdfFlag = true;
            },
            isType (filetype) {
                var type = '';
                if (!filetype) {
                    filetype = '';
                }
                filetype = filetype.toLowerCase();
                if (filetype === 'log' || filetype === 'xml' || filetype === 'txt') {
                    type = '1';
                } else if (filetype === 'bmp' || filetype === 'jpg' || filetype === 'png'
                        || filetype === 'gif' || filetype === 'jpeg' || filetype === 'apng'
                        || filetype === 'svg') {
                    type = '2';
                } else if (filetype === 'pdf') {
                    type = '3';
                } else {
                    type = '0';
                }
                return type;
            },
            valueToFatherValue() {
                let para= {};
                if (!this.value) {
                    para.value = '';
                } else {
                    para.value = this.value;
                }
                return para;
            },
            setFatherValue() {
                let para = this.valueToFatherValue();
                para.name = this.myConfig.name;
                this.$emit('inputValue', para);
            },
            watchCustomFatherValue() {
                this.initFile();
            },
            setReadOnly(value) {
                let obj = {};
                obj.readOnly = value;
                if (obj.readOnly === false) {
                    if (this.config.readOnly !== true) {
                        this.setPro(obj);
                    }
                } else {
                    this.setPro(obj);
                }
            },
            checkPara () {
                if (this.$parent && this.$parent.valueData) {
                    this.setHeaders(this.$parent.valueData);
                }
                if (!this.isHeadersOk()) {
                    if (this.myConfig.paraErrorInfo) {
                        this.alert(this.myConfig.paraErrorInfo);
                        return false;
                    }
                }
                return true;
            },
            setHeaders(data) {
                for (let temp in this.headers) {
                    this.headers[temp] = '';
                }
                if (data) {
                    for (let pro in this.myConfig.proName) {
                        if (data[this.myConfig.proName[pro]]) {
                            this.headers[pro] = data[this.myConfig.proName[pro]];
                        } else {
                            this.headers[pro] = '';
                        }
                    }
                }
                this.headers.scenetype =  this.myConfig.scenetype;
                this.headers.usercode = this.getUserCode();
                this.headers.username = this.getUserName();
            },
            isHeadersOk() {
                let flag = true;
                for (let pro in this.headers) {
                    if (!this.headers[pro]) {
                        flag = false;
                        break;
                    }
                }
                return flag;
            },
            uploadClick () {
                if (this.checkPara()) {
                    this.$refs.uploadbox.onClick();
                }
            },
            setFocus(value) {
                if (value) {
                    this.$refs.myControl.focus();
                } else {
                    this.$refs.myControl.blur();
                }
            }
        }
    };
</script>
