<!--
 * @Author       : yuanrunwei
 * @Date         : 2021-12-04 14:23:58
 * @LastEditors: daiqisheng
 * @LastEditTime: 2022-05-10 11:24:05
 * @FilePath     : \spfm-market-front\src\pages\main\performance\components\sheet.vue
-->
<template>
    <fullscreen id="containerClass" :fullscreen.sync="fullscreen" class="containerClass" style=" background-color: #ffffff">
        <div class="sheet-container" id="full-container">
            <div style="    margin-top: 20px; margin-left: 30px;" >
                <span style="  font-size: small;margin-right: 10px;">控制权限</span>
                <el-select v-model="state" placeholder="请选择" :disabled="this.type=='view'|| (this.type=='edit' && this.isCreater !='1') ?true:false " size="mini">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <div class="flex-justify-align-end margin-bottom-20">
                <!--      <span-->
                <!--        v-if="['template'].includes(attribute)"-->
                <!--        ><span class="sheet-container-require">*</span>模板类型:</span-->
                <!--      >-->
                <div style="display: flex;
                        margin-right: 20px;
                        background: rgb(2, 135, 251);
                        padding: 2px;
                        border-radius: 4px;">
                    <el-upload
                        action
                        :http-request="request"
                        :on-change="handleChange"
                        :show-file-list="false"
                        :disabled="this.type=='view'?true:false"
                    >
                        <el-button :disabled="this.type=='view'?true:false" size="mini">选择文件</el-button>
                    </el-upload>
                    <span style="font-size: 12px;margin-right: 5px;line-height: 2;color: white;">{{ fileListName }}</span>
                </div>
                <el-button
                    type="danger"
                    @click="handleResave"
                    size="mini"
                    :disabled="this.type=='view'?true:false"
                >保存</el-button
                >
                <!--            :disabled="handleForbid()"-->

                <el-button  size="mini" type="danger" @click="handleDownload">导出</el-button>
                <el-button size="mini" type="primary" @click="returnList">返回</el-button>
                <el-button size="mini" type="primary" @click="handleFullscreen">{{ showName }}</el-button>
            </div>
            <div id="luckysheet" class="sheet-container-block_class" ></div>
        </div>
    </fullscreen>
</template>

<script>
import luckyexcel from "luckyexcel";
import { exportExcel } from "./export";
export default {
    components: {
    },
    props: {
        isCreater: {
            type: String,
            default: "",
        },
        type: {
            type: String,
            default: "view", // view 查看 edit 编辑
        },
        attribute: {
            type: String,
            default: "template", // template 模板 order 工单 file 文件
        },
        id: {
            default: null,
        },
        // 接收人
        receiver: {
            type: String,
            default: "",
        },
        // 模板状态按钮判断
        status: { type: String, default: "" },
        mkdirId:{
            type: String,
            default:'',
        },
        fullscreen:{
            type:Boolean,
            default:false
        },
        workName:{
            type:String
        },
        workData:{
            type:Object
        }
    },
    data() {
        return {
            options: [{
                value: '1',
                label: '开启'
            },{
                value: '0',
                label: '关闭'
            }],
            state:'1',
            form: {
                charge: [
                    {
                        person: [],
                        col_start: "",
                        col_end: "",
                        row_start: "",
                        row_end: "",
                    },
                ],
                array: [],
                type: null,
                permission_type: null,
                col_start: "",
                col_end: "",
                row_start: "",
                row_end: "",
            },
            approveForm: {
                type: "",
                comments: "",
                list: [
                    {
                        label: "同意",
                        value: "同意",
                    },
                    {
                        label: "不同意",
                        value: "不同意",
                    },
                    {
                        label: "其他",
                        value: "3",
                    },
                ],
            },
            superviserules: {
                distribute: [
                    { required: true, message: "请选择派发周期", trigger: "change" },
                ],
                write: [
                    { required: true, message: "请选择填报周期", trigger: "change" },
                ],
                endTime: [
                    { required: true, message: "请选择截止时间", trigger: "change" },
                ],
            },
            superviseForm: {
                distribute: "", // 派单周期
                write: "", // 填写周期
                endTime: "", // 截止时间
            },
            originSuperviseForm: {},
            pickOptions: {
                disabledDate(time) {
                    return time.getTime() < new Date().getTime() - 8.64e7;
                },
            },
            pickWrite: {
                disabledDate(time) {
                    return time.getTime() < new Date().getTime() - 8.64e7;
                },
            },
            // 可提交标志
            addFlag: "0",
            // 督办标志
            superviseFlag: null,
            rowList: [],
            isDisable: true,
            issued_id: null,
            template_id: null,
            visible: false,
            templateType: "",
            // 督办
            supervise: false,
            manager_approve: false,
            row_list: [],
            column_list: [],
            charge_list: [],
            type_options: [
                {
                    value: 1,
                    label: "按行",
                },
                // {
                //     value: 2,
                //     label: "按列",
                // },
            ],
            fileListName:'未选择任何文件',
            showName: '全屏显示'
        };
    },
    methods: {
        request(){},
        handleInit() {
            if (this.id) {
                if (this.workData){
                    this.handleCreate({
                        json: this.workData,
                        name: this.workName,
                        type: "json",
                    });
                }else {
                    this.handleQuery();
                }
            } else {
                if (this.workData){
                    this.handleCreate({
                        json: this.workData,
                        name: this.workName,
                        type: "json",
                    });
                }else {
                    this.handleCreate();
                }
            }
            if (this.fullscreen){
                this.$nextTick(()=>{
                    this.handleFullscreenOption();
                    this.showName = '退出全屏'
                })
            }
        },
        returnList(){
            if (this.fullscreen){
                this.handleFullscreenOption()
                this.$emit("handleFullscreen", false)
            }
            this.$emit("save");
        },
        handleAllow() {
            //查看无法编辑
            return this.type=="view"?false:true;
        },
        addInputPlace(){
            this.$nextTick(()=>{
                let element = document.getElementById('luckysheet_info_detail_input');
                element.placeholder = '请输入标题'
                element.style['min-width'] = '120px'
            })
        },
        async handleQuery() {
            const {
                data: {
                    templateContent,
                    templateName,
                    state,
                },
            } = await this.$http({
                url: "/market/workLists/getWorkById",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {id:this.id},
            });
            this.state=state;
            this.handleCreate({
                json: templateContent ? JSON.parse(templateContent) : {},
                name: templateName,
                type: "json",
            });
        },
        async handleCreate({ file, json, type, name } = {}) {
            let that = this;
            if('add'== this.type){
                window.luckysheet.destroy();
                window.luckysheet.create({
                    container: "luckysheet",
                    lang: "zh",
                    showsheetbar: false,
                    data:[{"name": "777e1d91-2075-446f-b163-03c5e0ee0e0c"}],
                    plugins:['chart'],
                    userInfo:undefined,
                    title:""
                })
                this.addInputPlace();
                if (!this.fullscreen){
                    let interval = setInterval(()=>{
                        let elementById = document.getElementById("luckysheet-icon-morebtn-div");
                        if (elementById){
                            elementById.style.width = '55%'
                            clearInterval(interval)
                        }
                    },300)
                }
            }
            switch (type) {
                case "file":
                    if (file) {
                        await new Promise((resolve) => {
                            luckyexcel.transformExcelToLucky(file, (export_json) => {
                                let name = export_json.info.name;
                                if(!name.endsWith(".xlsx")){
                                    this.$message({
                                        type: "error",
                                        message: '导入失败！只支持.xlsx格式文件',
                                    });
                                }else {
                                    this.fileListName = name;
                                    let lastIndexOf = export_json.info.name.lastIndexOf('.');
                                    name = name.substring(0, lastIndexOf);
                                    window.luckysheet.destroy();
                                    export_json.sheets.name = '777e1d91-2075-446f-b163-03c5e0ee0e0c'
                                    window.luckysheet.create({
                                        container: "luckysheet",
                                        lang: "zh",
                                        plugins:['chart'],
                                        showsheetbar: false,
                                        data:export_json.sheets,
                                        title:name,
                                        userInfo:export_json.info.name.creater

                                    })
                                    this.addInputPlace();
                                    if (!this.fullscreen){
                                        let interval = setInterval(()=>{
                                            let elementById = document.getElementById("luckysheet-icon-morebtn-div");
                                            if (elementById){
                                                elementById.style.width = '55%'
                                                clearInterval(interval)
                                            }
                                        },300)
                                    }
                                }
                                resolve();
                            });
                        });
                    }
                    break;
                case "json":
                    if (json) {
                        window.luckysheet.destroy();
                        let data=[];
                        data[0]=json;
                        if('view'==this.type){
                            window.luckysheet.create({
                                container: "luckysheet",
                                lang: "zh",
                                plugins:['chart'],
                                showsheetbar: false,
                                data:data,
                                title:name,
                                userInfo:name.creater,
                                hook: {
                                    cellEditBefore: function ([
                                                                  { row_focus: row, column_focus: column },
                                                              ]) {
                                        if (!that.handleAllow({ row, column })) {
                                            that.$message.error("当前为【查看】状态，无法编辑！");
                                        }
                                    },
                                    // cellUpdated: function (row, column) {
                                    //   that.rowList.push(row);
                                    // },
                                    cellUpdateBefore: function (row, column) {
                                        console.log(row, column);
                                        if (!that.handleAllow({ row, column })) {
                                            return false;
                                        }
                                    },
                                    rangePasteBefore: function ([
                                                                    { row_focus: row, column_focus: column },
                                                                ]) {
                                        if (!that.handleAllow({ row, column })) {
                                            that.$message.error("当前为【查看】状态，无法编辑！");
                                            return false;
                                        }
                                    },
                                    updated: function ({ range }) {
                                        const middle = range.map((el) => {
                                            return that.paramsArr(el.row[0], el.row[1]);
                                        });
                                        let changedList = middle.join(",").split(",");
                                        that.rowList.push(...changedList);
                                    },
                                }
                            });
                        }else{
                            window.luckysheet.create({
                                container: "luckysheet",
                                lang: "zh",
                                plugins:['chart'],
                                showsheetbar: false,
                                data:data,
                                title:name,
                                userInfo:name.creater
                            });
                            this.addInputPlace();
                            if (!this.fullscreen){
                                let interval = setInterval(()=>{
                                    let elementById = document.getElementById("luckysheet-icon-morebtn-div");
                                    if (elementById){
                                        elementById.style.width = '55%'
                                        clearInterval(interval)
                                    }
                                },300)
                            }
                        }
                    }
                    break;
            }
        },
        async handleChange(response, fileList) {
            this.handleCreate({ file: response.raw, type: "file" });
        },
        handleDownload() {
            exportExcel(
                window.luckysheet.getAllSheets(),
                window.luckysheet.getWorkbookName()
            );
        },
        // 判断数组是否有值
        confirmArrayData(data) {
            if (data instanceof Array) {
                if (data.length) {
                    for (let i = 0; i < data.length; i++) {
                        if (data[i] instanceof  Array){
                            for (let j = 0; j < data[i].length; j++) {
                                if ((data[i][j] && data[i][j].v) || (data[i][j] && data[i][j].ct && data[i][j].ct.s && data[i][j].ct.s.length > 0 && data[i][j].ct.s[0].v)) {
                                    return true;
                                }
                            }
                        }else {
                            return false;
                        }
                    }
                    return false;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        },
        // 通用方法用于转化全局
        paramsArr(start, end) {
            const arr = [];
            console.log(start, end);
            for (let i = Number(start); i <= Number(end); i++) {
                arr.push(i);
            }
            return arr.join(",");
        },
        handleFullscreen() {
            const data = window.luckysheet.getSheet({name:"777e1d91-2075-446f-b163-03c5e0ee0e0c"});
            const workbook_name = window.luckysheet.getWorkbookName();
            this.$emit('saveData', workbook_name, data)
            if (this.fullscreen === false){
                this.$emit("handleFullscreen", true)
            }
            if (this.fullscreen === true){
                this.$emit("handleFullscreen", false)
            }
        },
        handleFullscreenOption(){
            const element = document.body;
            const is_fullscreen =
                document.fullScreen ||
                document.mozFullScreen ||
                document.webkitIsFullScreen;
            if (!is_fullscreen) {
                let elementById = document.getElementById("containerClass");
                elementById.style.height = 'calc(100vh - 100px)';
                //进入全屏,多重短路表达式
                (element.requestFullscreen && element.requestFullscreen()) ||
                (element.mozRequestFullScreen && element.mozRequestFullScreen()) ||
                (element.webkitRequestFullscreen &&
                    element.webkitRequestFullscreen()) ||
                (element.msRequestFullscreen && element.msRequestFullscreen());
            }else {
                let elementById = document.getElementById("containerClass");
                elementById.style.height = 'calc(100vh - 220px)';
               //退出全屏,三目运算符
               document.exitFullscreen
                 ? document.exitFullscreen()
                 : document.mozCancelFullScreen
                 ? document.mozCancelFullScreen()
                 : document.webkitExitFullscreen
                 ? document.webkitExitFullscreen()
                 : "";
            }
        },
        handleResave() {
            const sheet_name = window.luckysheet.getSheet().name;
            const data = window.luckysheet.getSheet(sheet_name);
            const workbook_name = window.luckysheet.getWorkbookName();
            let empty = this.confirmArrayData(data.data);
            if (!empty){
                this.$message({
                    type: "error",
                    message: '文档内容为空',
                });
                return;
            }
            if('请输入标题'== workbook_name || !workbook_name){
                this.$message({
                    type: "error",
                    message: '请输入标题',
                });
                return;
            }
            let value = {
                // templateId: this.id,
                templateContent: JSON.stringify(data), //文件内容
                templateName: workbook_name, //模板名称
                templateUrl: "", //文件链接
                state: this.state,
                mkdirId: this.mkdirId
            };
            if("edit" ==this.type){
                value.id=this.id;
            }
            this.$http({
                url: "/market/workLists/saveOrUpdate",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: value,
            }).then((res) => {
                console.log("----res",res);
                if(res.data.result==0){
                    this.$message({
                        type: "success",
                        message: "保存成功",
                    });
                }else{
                    this.$message({
                        type: "error",
                        message: res.data.body,
                    });
                }
                if (this.fullscreen){
                    this.handleFullscreenOption()
                    this.$emit("handleFullscreen", false)
                }
                this.$emit("save");
            });
        },
    },
    mounted() {
        this.handleInit();
        // this.handleChargeList();
    },
    destroyed() {
        window.luckysheet.destroy();
    },
};
</script>

<style lang="scss" scope>
.sheet-container {
    position: relative;
    width: 100%;
    height: 100%;
    &-block {
        overflow: hidden;
        position: absolute;
        width: 100%;
        height: 85%;
    }
    &-require {
        color: red;
    }
    .el-input {
        width: 200px;
        margin-right: 10px;
    }
}
.form {
    &-input {
        margin-top: 5px;
        .el-input {
            width: 150px;
            .el-input__inner {
                height: 30px !important;
                line-height: 30px !important;
            }
        }
    }
    &-content {
        margin: 0px 10px;
    }
    //&-select {
    //  .el-input {
    //    width: 100px;
    //    .el-input__inner {
    //      height: 30px !important;
    //      line-height: 30px !important;
    //    }
    //  }
    //}
}
.containerClass{
    background: #fff;
    border-radius: 5px;
    height: calc(100vh - 220px);
    width: calc(100% - 6px);
    float: left;
    display: inline-block;
    overflow: hidden;
}
.sheet-container-block_class{
    height: calc(100% - 96px);
    width: 100%;
}
.containerClass #luckysheet .luckysheet .fa{
    font:normal normal normal 14px/1 FontAwesome !important;
}
</style>
<style lang="scss">
body #luckysheet-modal-dialog-slider-pivot .fa{
    font:normal normal normal 14px/1 FontAwesome !important;
}
</style>
