<template>
    <Card :bordered="false" :padding="0" dis-hover>
        <p v-if="showTitle" @click="toggle" style="cursor:pointer;">
            <Row type="flex" justify="start" align="middle" style="margin-top:14px;margin-bottom:14px">
                <Icon custom='iconfont icon-custom-pack' color="#f3b352" v-show="showGrid" size="14"/>
                <Icon v-show="!showGrid" color="#f3b352" custom='iconfont icon-custom-spread' size="14"/>
                <span style="margin-left:10px;font-size: 14px;font-weight:bold" v-text="myConfig.title"/>
            </Row>
        </p>
        <div style="padding-left:24px">
            <Divider v-if="showTitle" style="margin-top:0px;margin-bottom:10px;"/>
            <Upload v-show="false" id="billiviewUp"
                    multiple
                    ref="billupload"
                    :accept="FileAccept"
                    :format="FileFormat"
                    :data="headers"
                    :show-upload-list="false"
                    :on-success="handleSuccess"
                    :on-exceeded-size="handleMaxSize"
                    :before-upload="handleBeforeUpload"
                    :on-format-error="handleFormatError"
                    :max-size="fileSize"
                    :action="uploadfile">
                <a>上传</a>
            </Upload>
            <div v-show="showGrid">
                <EditGridCardS ref="grid" :config="myConfig" :dictData="dictData"></EditGridCardS>
            </div>
        </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>
    </Card>
</template>
<script>
import load from '@/components/base/load';
import EditGridCardS from './editgridcard2.vue';
import {embed} from 'pdfobject';
import $ from 'jquery';
import Viewer from 'viewerjs';
import Cookies from 'js-cookie';
import {resolveComponent} from 'vue';

export default {
    name: 'mappendix',
    components: {EditGridCardS},
    mixins: [load],
    data () {
        return {
            myConfig: {
                headStyle: '',
                readOnly: false,
                showAddBtn:true,
                showDelBatchBtn:true,
                downfile: '',
                delfile: '',
                pdffile: '/mss-sysconf-boot/downloadPdf?filekey=',
                notdelfile: false,
                showfilemode: false,
                filemodedata: [],
                showPage: false,
                fileSize: 20,
                fileNum: 10,
                title: '附件',
                dynamicHeight: true,
                showTitle: true,
                scenetype: '3',
                height: 840,
                items: [{
                    label: '操作状态',
                    name: 'modflag',
                    type: 'ComboBox',
                    data: [{code: 'N', name: '初始'}, {code: 'M', name: '待删除'},
                        {code: 'I', name: '新增'}, {code: 'D', name: '删除'}],
                    visible: false,
                    width: 100,
                    readOnly: true
                }, {
                    label: '附件类型',
                    name: 'filememo',
                    type: 'ComboBox',
                    dictkey: 'CUSTFILETYPE',
                    codeWithName: false,
                    width: 300,
                    visible: false,
                    readOnly: true
                }, {
                    label: '附件类型',
                    name: 'filemode',
                    type: 'TextBox',
                    width: 300,
                    readOnly: true
                }, {
                    label: '文件名称',
                    name: 'filename',
                    type: 'TextBox',
                    minWidth: 200,
                    readOnly: true
                }, {
                    label: '文件大小',
                    name: 'filesize',
                    render: this.sizeActionRender,
                    width: 120,
                    readOnly: true
                }, {
                    label: '上传日期',
                    name: 'ph_timestamp',
                    type: 'DateBox',
                    vtype: 'datetime',
                    width: 150,
                    readOnly: true
                }, {
                    label: '操作',
                    key: 'action',
                    align: 'center',
                    render: this.actionRender,
                    width: 350,
                }]
            },
            loadFlag: false,
            billno: '',
            filememo: '',
            modulecode: '',
            idkey: '',
            showGrid: true,
            uploadfile: '',
            textStr: '',
            imgUrl: '',
            txtPanelFlag: false,
            pdfFlag: false,
            btnReadOnly: false,
            loading: true,
            fileSize: 0,
            initData: [],
            notShowBtn: [],
            rowBtnData: [
                {
                    icon: 'custom-fileupload',
                    name: 'upFile',
                    text: '上传'
                },
                {
                    icon: 'custom-filedel',
                    name: 'delFile',
                    text: '删除'
                },
                {
                    icon: 'custom-filedown',
                    name: 'downFile',
                    text: '下载'
                },
                {
                    icon: 'custom-filesearch',
                    name: 'searchFile',
                    text: '查看'
                },
                {
                    icon: 'custom-filerecall',
                    name: 'recall',
                    text: '撤回'
                },
                {
                    icon: 'custom-fileupload',
                    name: 'reupFile',
                    text: '变更'
                },
            ]
        };
    },
    created () {
        this.myConfig = Object.assign({}, this.myConfig, this.config);

        if (this.myConfig.showTitle !== undefined) {
            this.showTitle = this.myConfig.showTitle;
        }

        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;
        }
        // this.myConfig.showAddBtn = true;
        // this.myConfig.showDelBatchBtn = true;
        this.myConfig.generalOrientation = true;
        if (this.myConfig.fileSize !== undefined) {
            this.fileSize = Number(this.myConfig.fileSize) * 1024;
        }
        // if (this.myConfig.notdelfile) {
        //     this.myConfig.items[0].visible = true;
        // } else {
        //     this.myConfig.items[0].visible = false;
        // }

        if (this.myConfig.uploadfile.indexOf('?') != -1) {
            this.uploadfile = this.myConfig.uploadfile + '&token=' + this.getToken();
        } else {
            this.uploadfile = this.myConfig.uploadfile + '?token=' + this.getToken();
        }

        if (this.myConfig.notShowBtn !== undefined) {
            this.notShowBtn = this.myConfig.notShowBtn;
        }
    },
    computed: {
        headers () {
            let obj = {};
            if (this.modulecode) {
                obj.billmoduleid = this.modulecode;
            }
            obj.billno = this.billno;
            obj.scenetype = this.myConfig.scenetype;
            obj.usercode = this.getUserCode()
            obj.username = this.getUserName();
            if (this.myConfig.notdelfile) {
                obj.modflag = 'I';
            } else {
                obj.modflag = 'N';
            }
            if (obj.scenetype === '4') {
                obj.idkey = this.idkey;
            }
            if (this.filememo) {
                obj.filememo = this.filememo;
            }
            return obj;
        },
        FileFormat () {
            if (this.myConfig.fileType) {
                return this.myConfig.fileType;
            } else {
                return [];
            }
        },
        FileAccept () {
            if (this.myConfig.fileType) {
                let str = '';
                this.myConfig.fileType.forEach(e => {
                    str = str + '.' + e + ',';
                });
                return str;
            } else {
                return '';
            }
        }
    },
    props: {
        config: {
            type: Object,
            default: null
        },
        dictData: {
            type: Object,
            default:null
        }
    },
    methods: {
        handleFormatError (file) {
            let type = this.myConfig.fileType.join(',');
            this.alert('文件[' + file.name + ']的格式不正确，请上传格式为(' + type + ')的文件');
            this.loadFlag = true;
        },
        toggle () {
            this.showGrid = !this.showGrid;
        },
        setShowGrid (value) {
            this.showGrid = value;
        },
        actionRender (h, params) {
            let btnConfig = {};
            btnConfig.showNum = 5;
            btnConfig.fontStyle = '';
            btnConfig.items = [];
            if (params.row.filekey) {
                let del = this.$Method.copy(this.rowBtnData[1]);
                if (this.myConfig.readOnly) {
                    del.readOnly = true;
                }
                if (params.row.scenetype !== '0' && params.row.modflag !== 'M' && this.notShowBtn.indexOf(del.name) < 0) {
                    btnConfig.items.push(del);
                }
            } else {
                let up = this.$Method.copy(this.rowBtnData[0]);
                if (this.myConfig.readOnly) {
                    up.readOnly = true;
                }
                if (this.notShowBtn.indexOf(up.name) < 0) {
                    btnConfig.items.push(up);
                }

            }
            btnConfig.items.push(this.$Method.copy(this.rowBtnData[2]));
            if (this.isType(params.row.filetype) !== '0') {
                btnConfig.items.push(this.$Method.copy(this.rowBtnData[3]));
            }
            let recall = this.$Method.copy(this.rowBtnData[4]);
            if (this.myConfig.readOnly) {
                recall.readOnly = true;
            }
            if (this.myConfig.notdelfile) {
                if (params.row.modflag === 'N' && this.notShowBtn.indexOf(recall.name) < 0) {
                    btnConfig.items.push(recall);
                }
                let reupFile = this.$Method.copy(this.rowBtnData[5])
                if ((!params.row.filekey || params.row.filekey !== '') && params.row.modflag === 'N' && this.notShowBtn.indexOf(reupFile.name) < 0) {
                    btnConfig.items.push(reupFile);
                }
            }
            return h('div', [
                h(resolveComponent('RowBtnToolbar'), {
                    config: btnConfig,
                    onDoAction: (val) => {
                        if (val.name === 'upFile') {
                            this.editGrid(params);
                        }
                        if (val.name === 'delFile') {
                            this.delFile(params);
                        }
                        if (val.name === 'downFile') {
                            this.downFile(params);
                        }
                        if (val.name === 'searchFile') {
                            this.searchFile(params);
                        }
                        if (val.name === 'recall') {
                            this.recall(params);
                        }
                        if (val.name === 'reupFile') {
                            this.reupFile(params);
                        }
                    }
                })
            ]);
        },
        sizeActionRender (h, params) {
            let fize = Number(params.row.filesize);
            let str = '';
            if (fize < 1024) {
                str = fize + 'B';
            }
            if (fize > 1024 && fize < 1048576) {
                str = parseFloat(fize / 1024).toFixed(2) + 'K';
            }
            if (fize > 1048576 && fize < 1073741824) {
                str = parseFloat(fize / 1048576).toFixed(2) + 'M';
            }
            if (fize > 1073741824) {
                str = parseFloat(fize / 1073741824).toFixed(2) + 'G';
            }
            return h('span', str);
        },
        downFile (params) {
            let downUrl = this.myConfig.downfile + params.row.filekey + "&ent_id=" + this.getEnt_id() + "&token=" + this.getToken() + "&billno=" + this.billno;
            window.open(downUrl);
        },
        delCommon (filekey, notdelfile) {
            let delUrl = this.myConfig.delfile + filekey + "&ent_id=" + this.getEnt_id() + "&notdelfile=Y&token=" + this.getToken() + "&billno=" + this.billno;
            $.ajax({
                type: 'GET',
                url: encodeURI(delUrl),
                async: true,
                dataType: 'json'
            });
        },
        delFile (params) {
            if (!this.checkIsEdit()) {
                return;
            }
            if (!this.myConfig.notdelfile) {
                this.delCommon(params.row.filekey, 'N');
                let row = this.$Method.copy(params.row);
                row.filekey = '';
                row.filename = '';
                row.filetype = '';
                row.filesize = '';
                row.inputer = '';
                row.inputer_name = '';
                row.lastmoddate = '';
                row.ph_timestamp = '';
                this.$refs.grid.updateRow(params.index, row);
                // this.$refs.grid.delRow(params.index);
            } else {
                if (params.row.modflag === 'M') {
                    this.alert('当前状态不允许删除');
                    return;
                }
                if (params.row.modflag === 'I') {
                    this.delCommon(params.row.filekey, 'N');
                    this.$refs.grid.delRow(params.index);
                }
                if (params.row.modflag === 'N') {
                    let row = this.$Method.copy(params.row);
                    row.modflag = 'M';
                    this.$refs.grid.updateRow(params.index, row);
                }
            }
            if (this.myConfig.readOnly) {
                this.setReadOnly(false);
            }
        },
        recall (params) {
            if (params.row.modflag !== 'M') {
                this.alert('当前状态不用撤回');
                return;
            }
            let row = this.$Method.copy(params.row);
            row.modflag = 'N';
            this.$refs.grid.updateRow(params.index, row);
        },
        searchFile (params) {
            if (this.isType(params.row.filetype) === '1') {
                this.showTxt(params);
            }
            if (this.isType(params.row.filetype) === '2') {
                this.showPhoto(params);
            }
            if (this.isType(params.row.filetype) === '3') {
                this.showPdf(params);
            }
        },
        handleSuccess (response, file, fileList) {
            this.getFilesInfo(this.billno, this.modulecode, this.myConfig.notdelfile, this.myConfig.scenetype, this.doInitData);
            this.flag = false;
            if (this.myConfig.scenetype === '4') {
                this.loadFlag = true;
            } else {
                this.hideLoading();
            }
            this.$emit('handleSuccessAfter' , response, file, fileList);
        },
        handleMaxSize (file) {
            this.alert('文件[' + file.name + ']的文件大小不允许超过' + this.myConfig.fileSize + 'M');
            if (this.myConfig.scenetype === '4') {
                this.loadFlag = true;
            } else {
                this.hideLoading();
            }
        },
        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;
        },
        setPro (obj) {
            if (obj) {
                this.myConfig = Object.assign({}, this.myConfig, obj);
            }
        },
        setReadOnly (value) {
            let obj = {};
            obj.readOnly = value;
            this.setPro(obj);
            this.$refs.grid.setReadOnly(value);
            this.setBtnReadOnly(value);
        },
        showTxt (params) {
            let downUrl = this.myConfig.downfile + params.row.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 (params) {
            let downUrl = this.myConfig.downfile + params.row.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 (params) {
            let pdfUrl = this.myConfig.pdffile + params.row.filekey + '&token=' + this.getToken();
            //this.pdfSrc = pdfUrl;
            embed(encodeURI(pdfUrl), this.$refs.pdf);
            //pdfObject.embed(encodeURI(pdfUrl), this.$refs.pdf);
            this.pdfFlag = true;
        },
        getChangeData () {
            return this.$refs.grid.getChangeData();
        },
        setData (key, billmoduleid, idkey) {
            if (key) {
                this.billno = key;
                this.modulecode = billmoduleid;
                this.idkey = idkey;
                if (this.myConfig.scenetype === '4') {
                    this.getFilesInfoByIdkey(this.idkey, this.doInitData);
                } else {
                    this.getFilesInfo(key, this.modulecode, this.myConfig.notdelfile, '3', this.doInitData);
                }
                this.btnReadOnly = false;
            } else {
                this.btnReadOnly = true;
                this.billno = '';
                this.modulecode = '';
                this.idkey = '';
                this.$refs.grid.setData([]);
            }
        },
        setBillno (value) {
            this.billno = value;
            if (this.billno) {
                this.btnReadOnly = true;
            }
        },
        setModulecode (value) {
            this.modulecode = value;
        },
        doInitData (data) {
            this.$refs.grid.setData(data);
        },
        clearData () {
            this.billno = '';
            this.$refs.grid.clearData();
        },
        getData () {
            return this.$refs.grid.getData();
        },
        doCommonAllfile (flag) {
            let data = this.$refs.grid.getData();
            if (data.length === 0) {
                return;
            }
            let usercode = Cookies.get('user_code') ? Cookies.get('user_code') : 0;
            let username = Cookies.get('user_name') ? Cookies.get('user_name') : 0;
            let filekey = '';
            data.forEach(el => {
                if (flag) {
                    filekey = filekey + el.filekey + ",";
                } else {
                    if (el.modflag === 'M') {
                        filekey = filekey + el.filekey + ",";
                    }
                }
            });
            if (filekey) {
                filekey = filekey.substring(0, filekey.length - 1);
            } else {
                return;
            }
            let delUrl = this.myConfig.delfile + filekey + "&ent_id=" + this.getEnt_id();
            let token = this.getToken();
            if (token) {
                delUrl = delUrl + '&token=' + token;
            }
            delUrl = delUrl + '&billno=' + this.billno;
            delUrl = delUrl + '&billmoduleid=' + this.modulecode;
            data.forEach(el => {
                delUrl = delUrl + '&filememo=' + el.filememo;
            });

            let notdelfile = 'N';
            if (this.myConfig.notdelfile) {
                notdelfile = 'Y';
            }
            delUrl = delUrl + '&usercode=' + usercode + '&username=' + username + '&notdelfile=' + notdelfile;
            $.ajax({
                type: 'GET',
                url: encodeURI(delUrl),
                async: true,
                dataType: 'json'
            });
        },
        dellAllfile () {
            this.doCommonAllfile(true);
        },
        updateAllfile () {
            this.doCommonAllfile(false);
        },
        handleBeforeUpload () {
            let check = true;
            if (this.$refs.billupload && this.$refs.billupload.fileList) {
                check = this.$refs.billupload.fileList.length < this.myConfig.fileNum;
                if (!check) {
                    this.alert('上传的文件数量过多(一次最多允许上传' + this.myConfig.fileNum + '个文件)');
                }
            }
            if (!this.flag) {
                this.flag = true;
                this.loadingtext = '上传中';
                if (this.myConfig.scenetype === '4') {
                    this.loadFlag = false;
                } else {
                    this.showLoading();
                }

            }
            return check;
        },
        editGrid (params) {
            if (this.myConfig.beforeUpload) {
                this.myConfig.beforeUpload();
            }
            if (!this.billno) {
                this.alert('单据主健信息为空,不允许上传');
                return;
            }
            if (this.checkIsEdit()) {
                this.$nextTick(() => {
                    this.$refs.billupload.clearFiles();
                });
                if (this.myConfig.readOnly) {
                    this.setReadOnly(false);
                }
                this.filememo = params.row.filememo;
                document.querySelector('#billiviewUp input').click();
            }
        },
        reupFile (params) {
            if (this.myConfig.beforeUpload) {
                this.myConfig.beforeUpload();
            }
            if (!this.billno) {
                this.alert('单据主健信息为空,不允许上传');
                return;
            }
            if (this.checkIsEdit()) {
                this.$nextTick(() => {
                    this.$refs.billupload.clearFiles();
                });
                if (this.myConfig.readOnly) {
                    this.setReadOnly(false);
                }
                this.filememo = params.row.filememo;
                document.querySelector('#billiviewUp input').click();
            }
        },
        isChange () {
            return this.$refs.grid.isChange();
        },
        checkIsEdit () {
            let flag = true;
            if (this.myConfig.editObjectBefore) {
                flag = this.myConfig.editObjectBefore(this.myConfig.name);
            }
            return flag;
        },
        setBtnReadOnly (value) {
            if (!value) {
                if (this.billno) {
                    this.btnReadOnly = value;
                }
            } else {
                this.btnReadOnly = value;
            }
        },
    }
};
</script>
