<template>
  <span style="margin-left: 10px">
      <el-button type="danger" @click="handleRowDel" :size="tableOption.size ? tableOption.size : 'small'" v-if="tableOption.selection && tableOption.selection==true && delFlag" :disabled="!(selectedData && selectedData.length>0)">批量删除</el-button>
      <el-button type="info" @click="handleExport" :size="tableOption.size ? tableOption.size : 'small'" v-if="tableOption.selection && tableOption.selection==true" :disabled="!(selectedData && selectedData.length>0)">导出excel</el-button>
      <el-button type="warning" @click="handleJpeg" :size="tableOption.size ? tableOption.size : 'small'">导出图片</el-button>
      <el-button type="primary" @click="handleImport" :size="tableOption.size ? tableOption.size : 'small'" style="margin-left: 10px;" v-if="importFlag">批量导入</el-button>
      <el-dialog title="批量导入"
                :visible.sync="boxVisible"
                lock-scroll
                :modal-append-to-body="false"
                :append-to-body="true"
                @close="hide">
        <avue-form v-model="importForm"
                    ref="importForm"
                    :option="importOption"
                    @submit="handleSubmit"
                    @reset-change="resetChange">
            <template slot="file" slot-scope="scope">
                <el-upload
                        ref="upload"
                        drag
                        action=""
                        :limit="1"
                        accept=".xls,.xlsx"
                        :on-remove="onRemove"
                        :on-change="onChange"
                        :http-request="httpRequest"
                        :auto-upload="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div style="width:56px;color:#409EFF;font-style:normal;text-decoration:underline;font-size:14px;cursor:pointer;" slot="tip" @click.prevent="templateDownload">模版下载</div>
                </el-upload>
            </template>
        </avue-form>
    </el-dialog>
  </span>
</template>
<script>
import html2canvas from 'html2canvas';
// import { validatenull } from '@/packages/utils/validate';
import moment from 'moment';
// import axios from 'axios';
// import store from '@/store'
export default {
    name: "tableTopBtns",
    props:{
        selectedData:Array,
        tableData:{
            type: Array,
            required: true
        },
        tableOption:{
            type: Object,
            required: true
        },
        excelName:{
            type: String,
            default: () => {
                return '表配置Excel';
            }
        },
        pngName:{
            type: String,
            default: () => {
                return '表配置PNG';
            }
        },
        parentRefs:{
            required: true
        },
        dateFormat:Array,
        api:{
            type: String,
            required: true
        },
        importFlag:{
            type: Boolean,
            default: () => {
                return true;
            }
        },
        delFlag:{
            type: Boolean,
            default: () => {
                return true;
            }
        },
        importApi:{
            type: String,
            default: () => {
                return 'common/batchInput';
            }
        },
        importStencil:{
            type: Array,
            default: () => {
                return [];
            }
        }
    },
    components: {},
    data () {
    return {
        tableRow: {},
        boxVisible:false,
        importForm:{
            module:this.api
        },
        importOption:{
            column:[{
                label: '模块',
                prop: 'module',
                disabled:true,
                span:12,
            },{
                label: '是否覆盖',
                prop: 'isCover',
                type:"select",
                valueDefault:'false',
                dicData:[{
                    label: "是",
                    value: "true"
                },{
                    label: "否",
                    value: "false"
                }]
            },{
                label: '工厂',
                prop: 'orgId',
                type:"select",
                dicUrl:'/api/FactoryInfo',
                // dicData:'orgId',
                span: 24,
                props:{
                    label:'name',
                    value:'id'
                },
                rules: [{
                    required: true,
                    message: "请选择工厂",
                    trigger: "blur"
                }]
            },{
                label: "文件",
                prop: "file",
                slot:true,
                span: 24,
                formslot:true,
                rules: [{
                    required: true,
                    message: "请选择文件",
                    trigger: "blur"
                }]
            }]
        }
    };
    },
    created () {//初始化数据格式
    },
    watch: {
        api(curVal){
            this.importForm.module=curVal;
        },
    },
    mounted () { },
    computed: {
      // ...mapGetters(["permission", "menuAll"])
    },

    methods: {
        handleJpeg () {
            // let vm = this;
            let table = this.parentRefs.$el;
            html2canvas(table).then(canvas => {
            var url = canvas.toDataURL();
            let a = document.createElement('a');
            a.href = url;
            a.download = this.pngName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            });
        },
        handleRowDel () {
            var data = Object.assign([],this.selectedData),idData=[];
            data.forEach(item=>{
            idData.push(item.id)
            })
            console.log(idData);
            this.$confirm(`是否确认批量删除所选的项`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
            })
            .then(() => {
              this.requestMethod(this.api+'/batchDelete',{'listIds':idData}).then(() =>{
                this.$emit("RefreshData");
                this.$message({
                  showClose: true,
                  message: "删除成功",
                  type: "success"
                });
              });
            })
            .catch(() => { });
        },
        formatJson (filterVal, jsonData) {
            var _this = this
            return jsonData.map(v =>
            filterVal.map(j => {
              if (j === 'timestamp') {
                return _this.parseTime(v[j]);
              } else {
                return v[j];
              }
            }),
            );
        },
        getExcelHeaderAndFilter(){
            let obj={
                header:[],
                filter:[]
            }
            if(this.importStencil.length > 0){
                this.importStencil.forEach(item=>{
                    if(item.prop !== 'orgId'){
                        obj.header.push(item.label)
                        obj.filter.push(item.prop)
                    }
                })
            }
            else {
                if(this.tableOption && this.tableOption.column){
                    this.tableOption.column.forEach(item=>{
                        if(item.prop !== 'orgId'){
                            obj.header.push(item.label)
                            obj.filter.push(item.prop)
                        }
                    })
                }
            }
            return obj;
        },
        handleExport () {
            import('@/vendor/Export2Excel').then(excel => {
            const tHeader = this.getExcelHeaderAndFilter().header;
            const filterVal = this.getExcelHeaderAndFilter().filter;
            // const list = this.tableData;
            var tableData = Object.assign([],this.selectedData);
            if(this.dateFormat && this.dateFormat.length>0){
              tableData.forEach(row=>{
                for(var key in row){
                  if(this.dateFormat.includes(key)){
                    row[key]=moment(new Date(row[key])).format('YYYY-MM-DD HH:mm:ss')
                  }
                }
              })
            }
            const list = tableData;
            const data = this.formatJson(filterVal, list);
            excel.export_json_to_excel(tHeader, data, this.excelName);
            });
        },
        handleAdd () {
            this.$refs.crud.rowAdd();
        },
        handleImport(){//批量导入
            this.boxVisible=true;
        },
        onRemove(){
            this.importForm.file="";
        },
        onChange(file){
            if(!file.response){
                this.importForm.file=file;
            }
        },
        hide(){
            this.$refs['upload'].clearFiles();
            this.$refs['importForm'].resetForm();
            this.importForm.module=this.api;
        },
        handleSubmit(form){
            this.$refs.upload.submit();
            // form.orgId=this.$store.state.user.userInfo.orgId;
            const fd = new FormData();
            for (const o in form) {
                fd.append(o, form[o])
            }
            this.requestMethod(this.importApi,fd).then(()=>{
                this.boxVisible=false;
                this.hide();
                this.$message({
                    showClose: true,
                    message: "导入成功",
                    type: "success"
                });
                this.$emit("RefreshData");
            }).catch(res=>{
                this.$message({
                    showClose: true,
                    message: res.message,
                    type: "error"
                });
                if(res.data){
                    this.$emit("RefreshData");
                    import('@/vendor/Export2Excel').then(excel => {
                        const tHeader = this.getExcelHeaderAndFilter().header;
                        let filterVal = this.getExcelHeaderAndFilter().filter;
                        tHeader.push('错误信息');
                        filterVal.push('errorInfo');
                        tHeader.push('状态');
                        filterVal.push('status');
                        var tableData = Object.assign([],res.data.data);
                        if(this.dateFormat && this.dateFormat.length>0){
                            tableData.forEach(row=>{
                                for(var key in row){
                                    if(this.dateFormat.includes(key)){
                                        row[key]=moment(new Date(row[key])).format('YYYY-MM-DD HH:mm:ss')
                                    }
                                }
                            })
                        }
                        const list = tableData;
                        const data = this.formatJson(filterVal, list);
                        excel.export_json_to_excel(tHeader, data, this.api+'_Excel');
                    });
                }
            })
        },
        httpRequest(fd) {
            this.importForm.file=fd.file;
        },
        templateDownload(){
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = this.getExcelHeaderAndFilter().header;
                let filterVal = this.getExcelHeaderAndFilter().filter;
                var tableData = Object.assign([],[]);
                const list = tableData;
                const data = this.formatJson(filterVal, list);
                excel.export_json_to_excel(tHeader, data, this.api+'_Excel模版');
                this.$message({
                    showClose: true,
                    message: '模版下载完成',
                    type: "success"
                });
            });
        },
        resetChange(){
            this.$refs['upload'].clearFiles();
            this.importForm.module=this.api;
        }
}
};
</script>
