<!--
 * @Author       : yuanrunwei
 * @Date         : 2021-12-04 14:23:58
 * @LastEditors  : yuanrunwei
 * @LastEditTime : 2021-12-24 10:05:55
 * @FilePath     : \spfm-market-front\src\pages\main\performance\components\sheet.vue
-->

<template>
    <div class="sheet-container">
        <div class="flex-justify-align-end margin-bottom-20">
            <el-button type="primary" @click="handleVisible"
                >权限设置</el-button
            >
            <el-button type="primary" @click="handleDownload">导出</el-button>
            <el-button type="primary" @click="handleFullscreen()"
                >全屏显示</el-button
            >
            <template v-if="type === 'edit'">
                <el-upload
                    class="margin-right-10 margin-left-10"
                    action
                    :on-change="handleChange"
                    :show-file-list="false"
                >
                    <el-button type="primary">上传</el-button>
                </el-upload>
                <el-button
                    type="primary"
                    @click="handleSave"
                    :disabled="handleForbid()"
                    >保存</el-button
                >
            </template>
        </div>
        <div id="luckysheet" class="sheet-container-block"></div>
        <simple-dialog
            title="权限设置"
            :visible="visible"
            :modal="false"
            width="700px"
            @confirm="handlePower"
            @cancel="handleVisible"
        >
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item
                    label="可编辑列"
                    prop="array"
                    :rules="{
                        required: true,
                        message: '可编辑列不能为空',
                        trigger: 'change',
                    }"
                    ><el-select
                        v-model="form.array"
                        placeholder="可编辑列"
                        multiple
                    >
                        <el-option
                            v-for="(value, index) in 10"
                            :key="index"
                            :label="index"
                            :value="index"
                        >
                        </el-option> </el-select
                ></el-form-item>
                <el-form-item
                    label="权限规则"
                    prop="type"
                    :rules="{
                        required: true,
                        message: '权限规则不能为空',
                        trigger: 'change',
                    }"
                >
                    <el-select v-model="form.type">
                        <el-option
                            v-for="item in type_options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option> </el-select
                ></el-form-item>
                <el-form-item
                    label="负责人"
                    prop="charge"
                    :rules="{
                        required: true,
                        message: '负责人不能为空',
                        trigger: 'blur',
                    }"
                >
                    <div
                        class="flex-justify-start"
                        v-for="(item, index) in form.charge"
                        :key="index"
                    >
                        <el-select
                            v-model="item.key"
                            class="margin-bottom-20 margin-right-10 flex-1"
                            placeholder="请选择指定列/行"
                            multiple
                        >
                            <el-option
                                v-for="(value, index) in 10"
                                :key="index"
                                :label="index"
                                :value="index"
                            >
                            </el-option>
                        </el-select>
                        <el-select
                            class="margin-bottom-20"
                            placeholder="请选择负责人"
                            v-model="item.value"
                            filterable
                        >
                            <el-option
                                v-for="({ label, value }, index) in charge_list"
                                :key="index"
                                :label="label"
                                :value="value"
                            ></el-option>
                        </el-select>
                    </div>

                    <div>
                        <el-button @click.prevent="handleCharge('add')"
                            >添加</el-button
                        >
                        <el-button
                            v-if="form.charge.length - 1"
                            @click.prevent="handleCharge('delete')"
                            >删除</el-button
                        >
                    </div>
                </el-form-item>
            </el-form>
        </simple-dialog>
    </div>
</template>

<script>
import luckyexcel from "luckyexcel";
import { exportExcel } from "../common/export";
import simpleDialog from "./dialog.vue";
export default {
    components: {
        simpleDialog,
    },
    props: {
        type: {
            type: String,
            default: "view",
        },
        id: {
            type: Number,
            default: null,
        },
    },
    data() {
        return {
            form: {
                charge: [{ value: "" }],
            },
            visible: false,
            row_list: [],
            column_list: [],
            charge_list: [],
            type_options: [
                {
                    value: 1,
                    label: "按行",
                },
                {
                    value: 2,
                    label: "按列",
                },
            ],
        };
    },
    methods: {
        handleInit() {
            if (this.id) {
                this.handleQuery();
            } else {
                this.handleCreate();
            }
        },
        handleAllow({ row, column }) {
            return (
                this.row_list.includes(row) && this.column_list.includes(column)
            );
        },
        async handleQuery() {
            const {
                data: { templateContent, templateName },
            } = await this.$http({
                url: "/market/CMKFileTemplate/QueryCMKFileTemplateById",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    templateId: this.id,
                },
            });
            this.handleCreate({
                json: JSON.parse(templateContent),
                name: templateName,
                type: "json",
            });
        },
        handleForbid() {
            const object = {};
            const { array, type, charge } = this.form;
            charge.map(({ key, value }) => {
                if (key && value) {
                    object[key] = value;
                }
            });
            return !(Object.keys(object).length && array.length && type);
        },
        async handleCreate({ file, json, type, name } = {}) {
            let that = this;
            const options = {
                container: "luckysheet",
                lang: "zh",
                showsheetbar: false,
                hook: {
                    cellEditBefore: function ([
                        { row_focus: row, column_focus: column },
                    ]) {
                        if (!that.handleAllow({ row, column })) {
                            that.$message.error("您没有编辑权限");
                        }
                    },
                    cellUpdateBefore: function (row, column) {
                        if (!that.handleAllow({ row, column })) {
                            return false;
                        }
                    },
                    cellRenderAfter: function (cell, position) {
                        const { r: row, c: column } = position;
                        if (!that.handleAllow({ row, column })) {
                            if (cell) {
                                cell.bg = "#d5d5d5";
                            }
                        }
                    },
                },
            };
            switch (type) {
                case "file":
                    if (file) {
                        await new Promise((resolve) => {
                            luckyexcel.transformExcelToLucky(
                                file,
                                (export_json) => {
                                    options.data = [
                                        ...export_json.sheets.map(
                                            (element) => ({
                                                ...element,
                                                zoomRatio: 0.75,
                                            })
                                        ),
                                    ];
                                    options.title = export_json.info.name;
                                    resolve();
                                }
                            );
                        });
                    }
                    break;
                case "json":
                    if (json) {
                        options.data = [
                            {
                                ...json,
                                zoomRatio: 0.75,
                            },
                        ];
                        options.title = name;
                    }
                    break;
            }

            window.luckysheet.create(options);
        },
        async handleChange(response) {
            this.handleCreate({ file: response.raw, type: "file" });
        },
        handleDownload() {
            exportExcel(
                window.luckysheet.getAllSheets(),
                window.luckysheet.getWorkbookName()
            );
        },
        async handleSave() {
            const sheet_name = window.luckysheet.getSheet().name;
            const data = window.luckysheet.getSheet(sheet_name);
            const workbook_name = window.luckysheet.getWorkbookName();
            const {
                data: { body },
            } = await this.$http({
                url: "/market/CMKFileTemplate/CMKFileTemplateAdd",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    templateContent: JSON.stringify(data),
                    templateName: workbook_name,
                },
            });
            const object = {};
            const { array, charge, type } = this.form;
            charge.map(({ key, value }) => {
                if (key && value) {
                    object[key] = value;
                }
            });
            await this.$http({
                url: "/market/CMKFileTemplateAuthority/CMKFileTemplateAuthorityAdd",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    allowEditingColumns: array.join(","),
                    auth: JSON.stringify(object),
                    templateId: body,
                    type,
                },
            });
            this.$message.success("保存成功");
        },
        handlePower() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.handleForbid()) {
                        this.$message.error("请选择负责人编辑权限");
                        return false;
                    }
                    this.handleVisible();
                    this.$message.success("设置成功");
                }
            });
        },
        handleCharge(type) {
            switch (type) {
                case "add":
                    this.form.charge.push({
                        value: "",
                    });
                    break;
                case "delete":
                    this.form.charge.pop();
                    break;
            }
        },
        handleVisible() {
            this.visible = !this.visible;
        },
        handleFullscreen() {
            const element = document.body;
            const is_fullscreen =
                document.fullScreen ||
                document.mozFullScreen ||
                document.webkitIsFullScreen;
            if (!is_fullscreen) {
                //进入全屏,多重短路表达式
                (element.requestFullscreen && element.requestFullscreen()) ||
                    (element.mozRequestFullScreen &&
                        element.mozRequestFullScreen()) ||
                    (element.webkitRequestFullscreen &&
                        element.webkitRequestFullscreen()) ||
                    (element.msRequestFullscreen &&
                        element.msRequestFullscreen());
            } else {
                //退出全屏,三目运算符
                document.exitFullscreen
                    ? document.exitFullscreen()
                    : document.mozCancelFullScreen
                    ? document.mozCancelFullScreen()
                    : document.webkitExitFullscreen
                    ? document.webkitExitFullscreen()
                    : "";
            }
        },
        handleChargeList() {
            this.$http({
                url: "/market/techcentergj/queryLeaderList",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {},
            }).then((response) => {
                this.charge_list = response.data.map((element) => ({
                    label: `${element.ou} ${element.secLeaderName}`,
                    value: `${element.secLeaderLogin},${element.secLeaderName}`,
                }));
            });
        },
    },
    mounted() {
        this.handleInit();
        this.handleChargeList();
    },
};
</script>

<style lang="scss" scope>
.sheet-container {
    position: fixed;
    width: calc(100% - 40px);
    height: 100%;
    &-block {
        overflow: hidden;
        position: absolute;
        width: 100%;
        height: 75%;
    }
}
</style>
