<template>
  <div>
    <template v-if="modeltype==='upload'">
    <Modal  title="导入" v-model="showUpload" class-name="vertical-center-modal—bill" :width="modelWidth" :footer-hide="true" @on-visible-change="visibleChange">
        <Row type="flex" justify="start" :gutter="5">
            <Col span='16'>
                <Card :padding="0" :bordered="false" dis-hover >
                    <div style="margin-bottom:10px;display: flex;justify-content: space-between;">
                        <div>
                            <span class="efuture-title-verticalline"/> <span style="font-size: 14px;font-weight:bold">任务文件</span>
                       </div>
                       <Button size="small" customIcon="iconfont icon-custom-anniu-shuaxin" @click="Refurbish">刷新</Button>
                    </div>
                    <SimpleViewGrid
                        ref="grid"
                        :config="gridConfig"
                        :dictData="dictData"
                         @rowclick="gridClick"
                    />
                </Card>
                <Divider style="margin:12px 0"/>
                <Card :padding="0" :bordered="false" dis-hover >
                    <div style="margin-bottom:10px;display: flex;justify-content: space-between;">
                        <div>
                            <span class="efuture-title-verticalline"/> <span style="font-size: 14px;font-weight:bold">导入错误信息</span>
                       </div>
                       <Button size="small" customIcon="iconfont icon-custom-filedown" @click="downErr">下载</Button>
                    </div>
                    <SimpleViewGrid
                        ref="griderr"
                        :config="gridErrConfig"
                        :dictData="dictData"
                    />
                </Card>
            </Col>
            <Col  span='8'>
                <p style="margin-bottom:10px;">
                       <span class="efuture-title-verticalline"/> <span style="font-size: 14px;font-weight:bold">导入文件</span>
                </p>
                <div class="demo-spin-col-bill">
                    <RadioGroup v-if="showType" v-model="type" style="margin-bottom:24px">
                        <Radio v-for="(item,index) in myConfig.typeData" :key="index" :label="item.code">
                            <span>{{item.name}}</span>
                        </Radio>
                    </RadioGroup>
                    <div :style="divStyle">
                        <Row type="flex" justify="center" >
                            <Col  style="margin-top:30px;margin-bottom:10px">
                                <Icon  custom="iconfont icon-custom-excel" size="60"  />
                            </Col>
                        </Row>
                        <Row type="flex" justify="center">
                            <Col>
                                <Input v-model="name" style="width:150px;" :border="false" placeholder="(支持xls、xlsx格式)" clearable disabled/>
                            </Col>
                        </Row>
                        <Row type="flex" justify="center"  :gutter="10">
                            <Col>
                                <Upload ref="upload"
                                    :before-upload="handleUpload"
                                    accept=".xlsx,.xls"
                                    :format="myConfig.fileType"
                                    :on-format-error="handleFormatError"
                                    :on-success="handleSuccess"
                                    :show-upload-list="false"
                                    :action="url">
                                        <Button style="width:150px;">选择文件</Button>
                                        </Upload>
                            </Col>
                        </Row>
                    </div>
                    <Spin v-show="loading" fix>
                            <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                            <div>导入中</div>
                    </Spin>
                </div>
            </Col>
        </Row>
    </Modal>
    </template>
    <template v-if="modeltype === 'down'">
        <Modal v-model="showUpload" title="选择模版" @on-ok="downTemplate" class-name="vertical-center-modal—bill">
        <RadioGroup v-model="type">
            <Radio v-for="(item,index) in myConfig.typeData" :key="index" :label="item.code">
                    <span>{{item.name}}</span>
            </Radio>
        </RadioGroup>
        </Modal>
    </template>
    <template v-if="modeltype === 'export'">
        <Modal v-model="showUpload" title="导出" :width="modelWidth" class-name="vertical-center-modal—bill" :footer-hide="true">
            <Row type="flex" justify="start"  align="middle" :gutter="0" style="margin-bottom:20px">
                <Col span="3">
                    <Button @click="doAsyncExport">生成导出任务</Button>
                </Col>
                <Col  v-if="checkExport" span="21">
                    <p   v-if="checkExportFailFlag" style="border:1px solid #F3B352;background-color:#FFF7EB;padding-left:30px;padding-right:30px"> <Icon custom="iconfont icon-custom-daishenpi"   size="20" color="#F3B352"/> <span style="margin-left: 12px;font-size:18px;color:#F3B352;font-weight:bold">已存在生成中的导出任务，请稍后生成导出任务</span> </p>
                    <p   v-if="checkExportSuccessFlag" style="border:1px solid #739943;background-color:#FBFFF6;padding-left:30px;padding-right:30px"> <Icon custom="iconfont icon-custom-wancheng"   size="20" color="#739943"/> <span style="margin-left: 12px;font-size:18px;color:#739943;font-weight:bold">导出任务已生成，请稍后在任务列表下载文件</span> </p>
                </Col>
            </Row>
            <div style="margin-bottom:10px;display: flex;justify-content: space-between;">
                <div>
                    <span class="efuture-title-verticalline"/> <span style="font-size: 14px;font-weight:bold" v-text="exportGridConfig.gridtitle" />
                </div>
                <Button size="small" customIcon="iconfont icon-custom-anniu-shuaxin" @click="Refurbish">刷新</Button>
            </div>
            <SimpleViewGrid
                        ref="grid"
                        :config="exportGridConfig"
                        :dictData="dictData"
                    />
        </Modal>
    </template>
  </div>
</template>
<script>
    import { resolveComponent } from 'vue';
    export default {
        name:'mbillasyncimport',
        data () {
            return {
                myConfig:{
                    typeData:[],
                    fileType:['xlsx','xls'],
                    setImportUrl:null,
                    resources:'',
                },
                initConfig:{
                    typeData:[],
                    fileType:['xlsx','xls'],
                    setImportUrl:null,
                    resources:'',
                },
                gridConfig:{
                    gridtitle:'任务文件',
                    showPage:false,
                    dynamicHeight:false,
                    height:250,
                    items:[{
                        label:'日期',
                        name:'taskdate',
                        type:'DateBox',
                        vtype:'datetime',
                        width:150
                    }, {
                        label:'状态',
                        name:'taskstatus',
                        type:'ComboBox',
                        codeWithName:false,
                        data:[{  code : 'N',  name : '进行中'},{  code : 'F',  name : '导入失败'}, {  code : 'Y',  name : '已生成'} ,{  code : 'E',  name : '部分导入成功'}],
                        width:100,
                    },{
                        label:'文件名称',
                        name:'filename',
                        type:'TextBox'
                    },{
                        label:'操作',
                        key:'action',
                        align: 'center',
                        render: this.actionRender,
                        width:200
                    }]
                },
                gridErrConfig:{
                    gridtitle:'任务文件',
                    showPage:false,
                    dynamicHeight:false,
                    height:250,
                    items:[{
                        label:'错误信息',
                        name:'errmsg',
                        type:'TextBox'
                    }]
                },
                exportGridConfig:{
                    gridtitle:'任务日志',
                    showPage:false,
                    dynamicHeight:false,
                    height:250,
                    items:[{
                        label:'日期',
                        name:'taskdate',
                        type:'DateBox',
                        vtype:'datetime',
                        width:150
                    }, {
                        label:'状态',
                        name:'taskstatus',
                        type:'ComboBox',
                        codeWithName:false,
                        data:[{  code : 'N',  name : '进行中'},{  code : 'F',  name : '导入失败'}, {  code : 'Y',  name : '已完成'} ,{  code : 'C',  name : '已取消'},],
                        width:100,
                    },{
                        label:'文件名称',
                        name:'filename',
                        type:'TextBox'
                    },{
                        label:'操作',
                        key:'action',
                        align: 'center',
                        render: this.actionRender,
                        width:250
                    }]
                },
                file: null,
                name:'',
                type:'',
                showType:false,
                showUpload:false,
                modeltype:'upload',
                param:{},
                curlUrl:'',
                loading:false,
                checkExport:false,
                isExport:false,
                downMethod:'exportTemplate',
                importMethod:'asyncImport',
                billkey:'',
                rowBtnData:[
                    {
                    icon:'custom-filedown',
                    name:'downFile',
                    text:'下载'
                    },
                    {
                    icon:'custom-filedel',
                    name:'delTask',
                    text:'删除'
                    },
                    {
                    icon:'custom-filerecall',
                    name:'cancelTask',
                    text:'取消'
                    }
                ],
                checkExportFailFlag: false,
                checkExportSuccessFlag:true,
                actionGrid:null,
                modulecode:''
            };
        },
        props:{
            config: {
                type:Object,
                default () {
                    return {};
                }
            },
        } ,
        computed:{
            filename(){
                if (this.name) {
                    return this.name;
                } else {
                    return '(支持xls、xlsx格式)';
                }
            },
            modelWidth() {
                return this.clientWidth * 0.8;
            },
            clientWidth () {
                return this.$Store.state.app.clientWidth;
            },
            clientHeight () {
                return this.$Store.state.app.clientHeight;
            },
            divStyle() {
                let height = 560;
                let style = 'border:1px solid #DCDFE6;'
                style = style + 'height:' + height + 'px;'
                return style;
            },
            url() {
                let url = this.curlUrl;
                let para = this.$Method.copy(this.param);
                if (this.showType) {
                    if (this.myConfig.typeData.length > 0) {
                        if (this.type) {
                            para.billmoduleid = para.billmoduleid+'_' + this.type;
                        }
                    }
                }
                return url+'&param=' +encodeURI(JSON.stringify(para));
            }
        },
        methods: {
            init () {
                this.myConfig = Object.assign({},this.initConfig, this.config);
                if (this.myConfig.typeData && this.myConfig.typeData.length > 0) {
                    this.showType = true;
                    this.type = this.myConfig.typeData[0].code;
                }
                if (this.myConfig.importMethod) {
                    this.importMethod = this.myConfig.importMethod;
                }
                 if (this.myConfig.downMethod) {
                    this.downMethod = this.myConfig.downMethod;
                }
                if (!this.myConfig.downfile) {
                    this.myConfig.downfile =  this.OmdUrl.downfile;
                }
            },
            setModeltype(value) {
                this.modeltype = value;
            },
            initData(billkey,modulecode,grid) {
                let para = {};
                if (billkey) {
                    para.billkey = billkey;
                    para.tasktype = '1';
                    this.billkey = billkey;
                    this.setImpExportData(para);
                } else {
                    this.billkey = '';
                    para.modulecode = modulecode;
                    para.tasktype = '2';
                    this.actionGrid = grid;
                    this.modulecode = modulecode;
                    this.setImpExportData(para);
                }
            },
            clearData() {
                this.$refs.grid.clearData();
                this.$refs.griderr.clearData();
            },
            setImpExportData (para) {
                let self = this;
                self.$refs.grid.clearData();
                self.synchroPost(this.myConfig.resources, 'importexportservice.search', para, function (data) {
                    if (data.impexporthead) {
                        self.$refs.grid.setData(data.impexporthead);
                    }
                });
            },
            setImpErrData(taskid) {
                let self = this;
                let para = {};
                para.taskid = taskid;
                self.$refs.griderr.setData([])
                 self.synchroPost(this.myConfig.resources, 'importexportservice.searchImportErr', para, function (data) {
                    if (data.imperrmsgdetail) {
                        self.$refs.griderr.setData(data.imperrmsgdetail);
                    }
                });
            },
            setShowUpload(flag) {
                if (flag) {
                    this.init();
                }
                this.showUpload = flag;
            },
            setResources(url) {
                this.myConfig.resources = url;
            },
            setUrl(url,method,param) {
                if (url) {
                    url = url.replace('rest', this.importMethod);
                }
                let self = this;
                this.curlUrl = this.getResturl(url,method,{},self);
                if (this.myConfig.setImportUrl) {
                    this.curlUrl = this.myConfig.setImportUrl(this.curlUrl,'import');
                }
                Object.assign(this.param, param);

                if (this.myConfig.typeData.length > 1) {
                    if (!this.type) {
                        this.type = this.myConfig.typeData[0].code;
                    }
                }
            },
            setDownUrl(url,param) {
                if (url) {
                    url = url.replace('rest', this.downMethod);
                }
                let self = this;
                this.curlUrl = this.getResturl(url,null,{},self);
                if (this.myConfig.typeData.length > 1) {
                    this.param = param;
                    this.type = this.myConfig.typeData[0].code;
                    this.showUpload = true;
                } else {
                    let temp  = this.curlUrl +'&param=' +encodeURI(JSON.stringify(param));
                    if (this.myConfig.setImportUrl) {
                        temp = this.myConfig.setImportUrl(temp,'down');
                    }
                    window.open(temp,'_self');
                }
            },
            handleUpload (file) {
                if (!this.checkFormat(file)) {
                    this.handleFormatError(file);
                    this.file = null;
                    this.name = '';
                    return false;
                } else {
                    if (this.checkTask()) {
                        this.alert('存在进行中的导入任务，请稍后导入数据');
                        this.file = null;
                        this.name = '';
                        return false;
                    } else {
                        this.file = file;
                        this.name = file.name;
                        this.isExport = true;
                        this.upload();
                    }
                }
                return false;
            },
            checkFormat(file) {
                const _file_format = file.name.split('.').pop().toLocaleLowerCase();
                const checked = this.myConfig.fileType.some(item => item.toLocaleLowerCase() === _file_format);
                return checked;
            },
            checkTask() {
                let self = this;
                let para = {};
                if (this.modeltype === 'upload') {
                    para.tasktype = '1';
                    para.billkey = this.billkey;
                } else {
                    para.tasktype = '2';
                    para.modulecode = this.modulecode;
                }
                let flag = false;
                self.synchroPost(this.myConfig.resources, 'importexportservice.checkTask', para, function (data) {
                    if (data.flag === '-1') {
                       flag = true;
                    }
                });
                return flag;
            },
            upload () {
                if (!this.name) {
                    this.file = null;
                }
                if (this.file !== null) {
                    this.loading = true;
                    this.$refs.upload.post(this.file);
                }
            },

            handleFormatError (file) {
                let type = this.myConfig.fileType.join(',');
                this.alert('文件[' + file.name + ']的格式不正确，请上传格式为(' + type + ')的文件');
            },
            handleSuccess(res) {
                let self = this;
                setTimeout(() => {
                    self.file = null;
                    self.name = '';
                    self.Refurbish();
                    if (self.myConfig.importSuccess) {
                        self.myConfig.importSuccess(res);
                    }
                    self.loading = false;
                }, 2000)

            },
            downTemplate() {
                if (this.type) {
                    let param = this.$Method.copy(this.param);
                    if (param.billmoduleid) {
                        param.billmoduleid =  param.billmoduleid + '_' + this.type;
                        let temp  = this.url +'&param=' +encodeURI(JSON.stringify(param));
                        window.open(temp,'_self');
                        this.showUpload = false;
                    }
                }
            },
            actionRender (h, params) {
                let btnConfig = {};
                btnConfig.showNum = 4;
                btnConfig.fontStyle = '';
                btnConfig.items = [];
                if (params.row.filekey) {
                    let del = this.$Method.copy(this.rowBtnData[0]);
                    btnConfig.items.push(del);
                }
                if (this.modeltype === 'export') {
                    if (params.row.taskstatus === 'N') {
                        btnConfig.items.push(this.$Method.copy(this.rowBtnData[2]));
                    }
                }
                btnConfig.items.push(this.$Method.copy(this.rowBtnData[1]));
                return h('div', [
                    h(resolveComponent('RowBtnToolbar'), {
                        config:btnConfig,
                        onDoAction:(val) => {
                                if (val.name === 'delTask') {
                                    this.delTask(params);
                                }
                                if (val.name === 'downFile') {
                                    this.downFile(params);
                                }
                                if (val.name === 'cancelTask') {
                                    this.cancelTask(params);
                                }
                                this.checkExport = false;
                                this.checkExportFailFlag = false;
                                this.checkExportSuccessFlag = false;
                            }
                    })
                ]);
            },
            delTask(params) {
                this.$refs.grid.delRow(params.index);
                let self = this;
                let para = {};
                para.taskid= params.row.taskid;
                self.asyncPost(this.myConfig.resources, 'importexportservice.taskDel', para, function (data) {
                    if (data.flag === '1') {
                    }
                });
            },
            cancelTask(params) {
                let self = this;
                let para = {};
                para.taskid= params.row.taskid;
                self.asyncPost(this.myConfig.resources, 'importexportservice.taskCancel', para, function (data) {
                    if (data.flag === '1') {
                        self.$refs.grid.updataRow(params.index,{taskstatus:'C'});
                    }
                });
            },
            gridClick(e) {
                this.setImpErrData(e.taskid);
            },
            downErr() {
                let data = this.$refs.griderr.getData();
                if (data.length === 0) {
                    this.alert('没有错误信息可下载');
                    return;
                } else {
                    this.$Method.exportExcel(this.gridErrConfig.items, this.$refs.griderr.getData(),null,'错误信息');
                }

            },
            Refurbish() {
                let para = {};
                if (this.modeltype === 'upload') {
                    para.tasktype = '1';
                    para.billkey = this.billkey;
                    this.$refs.griderr.clearData();
                    this.setImpExportData(para);
                } else {
                    para.tasktype = '2';
                    para.modulecode = this.modulecode;
                    this.setImpExportData(para);
                }

            },
            downFile(params) {
                if (!params.row.filekey) {
                    return;
                }
                let downUrl = this.myConfig.downfile + params.row.filekey + "&ent_id=" + this.getEnt_id() + "&token=" + this.getToken();
                window.open(downUrl);
            },
            doAsyncExport() {
                this.checkExport = false;
                this.checkExportFailFlag = false;
                this.checkExportSuccessFlag = false;
                this.$nextTick(() => {
                    if (this.checkTask()){
                        this.checkExportFailFlag = true;
                        this.checkExport = true;
                    } else {
                        this.actionGrid.export(true,this.exportFinish)
                    }
                });

            },
            exportFinish() {
                this.checkExportSuccessFlag = true;
                this.checkExport = true;
                this.Refurbish();
            },
            visibleChange(value) {
                if (this.modeltype === 'upload'){
                    if (this.isExport) {
                        if (this.$parent.asyncImportClose) {
                            this.$parent.asyncImportClose(value);
                        }
                    }

                }
            }
        }
    };
</script>
<style lang="less" scoped>
    .ivu-modal-wrap.vertical-center-modal—bill .ivu-modal-header{
        border-radius:10px;
    }
    .ivu-modal-wrap.vertical-center-modal—bill .ivu-modal-body{
        padding-top: 8px;
        padding-right: 28px;
        padding-bottom: 32px;
        padding-left: 28px;
    }
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .demo-spin-col-bill{
        position: relative;
    }
</style>
