<template>
    <div class="container" id="container" v-loading="loading">
        <fullscreen :fullscreen.sync="fullscreen" class="container" style="margin: 0;width: 100%;">
            <iframe height="100%" width="100%" src="/marketfront/static/views/incomeTemplateExcel.html" frameborder="0"
                    ref="iframe" name="excelIframe" id="excelIframe"></iframe>
        </fullscreen>
        <el-dialog :title="'权限设置'" :visible.sync="authSettingStatus" width="70%" :destroy-on-close="true"
                   :modal-append-to-body="false" :close-on-click-modal="false">
            <el-form :model="testModel" ref="addInfoList">
                <div>
                    <div class="info-line">
                        <el-radio v-model="authType" label="1" style="margin: 10px">无特殊权限</el-radio>
                        <div id="noLimit" class="info-line">
                            <span style="margin-right: 20px;margin-left: 40px">负责人：</span>
                            <el-button type="primary" @click="noLimitUserAdd()">组织机构</el-button>
                            <span style="width: 80px;margin-right: 20px;margin-left: 20px">{{ noLimitUserName }}</span>
                        </div>
                    </div>
                    <div class="info-line">
                        <el-radio v-model="authType" label="2" style="margin: 10px">特殊权限</el-radio>
                        <div id="limit">
                            <div v-for="(item,index) in limitList">
                                <span style="margin-right: 20px;margin-left: 40px">负责人：</span>
                                <el-button type="primary" @click="limitUserAdd(index)">组织机构</el-button>
                                <span style="margin-right: 20px;margin-left: 20px">{{ item.userName }}</span>
                                <span style="margin-right: 10px;margin-left: 10px">可编辑行：从</span>
                                <el-input v-model="item.editStart" style="width: 80px;" type="number" min="1"
                                          oninput="value=value.replace('-','')"></el-input>
                                <span style="margin-right: 10px;margin-left: 10px">到</span>
                                <el-input v-model="item.editEnd" style="width: 80px;" type="number" min="1"
                                          oninput="value=value.replace('-','')"></el-input>
                                <br/><br/>
                            </div>
                            <el-button style="width: 80px;margin-right: 20px;margin-left: 40px"
                                       @click="addNewLimitAuth()">添加
                            </el-button>
                        </div>
                    </div>
                    <div slot="footer" style="text-align: right;padding-bottom: 20px;padding-top: 20px">
                        <el-button @click="authSettingStatus = false">取 消</el-button>
                        <el-button type="primary" @click="processAuth()">确 定</el-button>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog title="选择填报人" :visible.sync="noLimitDialog" width="50%" :destroy-on-close="true"
                   :modal-append-to-body="false" :close-on-click-modal="false">
            <div>
                <el-form :model="exaList" ref="addInfoList">
                    <el-form-item prop="processUserId" class="info-line online">
                        <span style="width: 80px;margin-right: 20px">审批人员</span>
                        <deptTreeUserNew class="tree" @treeCheck="treeCheckonly" :defaultList="defaultList"
                                         :type="depttype" :closeList="closeList"></deptTreeUserNew>
                        <div class="tree treeUser">
                            <p v-for="(item,index) in treeList" :key="index">{{ item.receiveName }}
                                <i @click="deletes(item,index)" class="el-icon-error"></i>
                            </p>
                        </div>
                        <el-form-item style="margin-bottom:0;display:none;">
                            <el-input></el-input>
                        </el-form-item>
                    </el-form-item>
                </el-form>

                <div slot="footer" style="text-align: right;padding-bottom: 20px">
                    <el-button @click="noLimitDialog = false">取 消</el-button>
                    <el-button type="primary" @click="processNoLimitUsers()">确 定</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog :title="'收入信息处理'" :visible.sync="authDialog" width="50%" :destroy-on-close="true"
                   :modal-append-to-body="false" :close-on-click-modal="false">
            <el-form :model="testModel" ref="addInfoList">
                <div>
                    <div class="info-line">
                        <span style="margin-right: 20px;margin-left: 40px">选择路径：</span>
                        <el-select v-model="auditForm.authType" placeholder="选择路径">
                            <el-option v-for="(item,index) in auditBoxList" :key="index" :label="item.name"
                                       :value="item.value"></el-option>
                        </el-select>
                    </div>
                    <br/>
                    <div class="info-line" v-if="auditForm.authType == 1">
                        <span style="margin-right: 20px;margin-left: 40px">下一步处理人：</span>
                        <el-button type="primary" @click="auditUserAdd()">选择处理人</el-button>
                        <span style="width: 80px;margin-right: 20px;margin-left: 20px">{{ auditUserName }}</span>
                    </div>
                    <br/>
                    <div class="info-line">
                        <span style="margin-right: 20px;margin-left: 40px;">意见内容：</span>
                        <el-input type="textarea" v-model="auditForm.auditRemark" style="width: 400px"></el-input>
                    </div>
                    <br/>
                    <div slot="footer" style="text-align: right;padding-bottom: 20px;padding-top: 20px">
                        <el-button @click="authDialog = false">取 消</el-button>
                        <el-button type="primary" @click="processAudit()">确 定</el-button>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog title="选择审批人" :visible.sync="checkexa" width="50%" :destroy-on-close="true"
                   :modal-append-to-body="false" :close-on-click-modal="false">
            <div>
                <el-form :model="addInfoList" ref="addInfoList">
                    <el-form-item prop="processUserId" class="info-line online">
                        <span style="width: 80px">审批人员&nbsp;</span>
                        <deptTreeOnly class="tree" @treeCheck="treeCheckonly" :defaultList="defaultList"
                                      :type="depttype" :closeList="closeList"></deptTreeOnly>
                        <div class="tree treeUser">
                            <p>{{ treeListonly.leaderAuditName }}
                                <i v-if="treeListonly.leaderAuditName" @click="treeDelete()"
                                   class="el-icon-error"></i>
                            </p>
                        </div>
                        <el-form-item style="margin-bottom:0;display:none;">
                            <el-input></el-input>
                        </el-form-item>
                    </el-form-item>
                </el-form>

                <div slot="footer" style="text-align: right;padding-bottom: 20px">
                    <el-button type="primary" @click="processAuditUser()">确 定</el-button>
                    <el-button @click="checkexa = false">取 消</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import myMessage from "../../../components/myMessage.vue"
import deptTreeUserNew from "../../../components/deptTreeUserNew";
import deptTreeOnly from "../../../components/deptTreeOnly.vue"

export default {
    components: {
        myMessage,
        deptTreeUserNew,
        deptTreeOnly,
    },
    data() {
        return {
            testModel: {},
            authSettingStatus: false,
            authType: '1',
            noLimitUserName: '',
            noLimitUsers: [],
            noLimitDialog: false,
            exaList: {},
            defaultList: [],
            treeList: [],
            closeList: false,
            depttype: 0,
            limitUserIndex: -1,
            limitList: [{}],
            type: '',
            loading: false,
            auditBoxList: [{}],
            authDialog: false,
            auditForm: {},
            auditUserName: '',
            auditUserId: '',
            //选择审批人
            checkexa: false,
            //审批人用到的
            treeListonly: {},
            excelData: {},
            fullscreen: false,
            addInfoList: []
        }
    },
    methods: {
        auditUserAdd() {
            this.checkexa = true;
        },
        processAuditUser() {
            console.log(this.treeListonly);
            this.auditUserId = this.treeListonly.leaderAuditNo;
            this.auditUserName = this.treeListonly.leaderAuditName;
            this.checkexa = false;
        },
        openAuditWindow(sheetName, excelData) {
            this.auditBoxList = [{
                name: '提交审核',
                value: '1'
            }, {
                name: '结束',
                value: '2'
            }];
            this.authDialog = true;
            this.excelData = excelData;
        },
        processAudit() {
            //检查选项
            if (this.auditForm.authType == null) {
                this.$message({
                    message: '请选择路径',
                    type: 'error'
                });
                return;
            }
            if (this.auditForm.authType == '1') {
                if (this.auditUserId == '') {
                    this.$message({
                        message: '请选择下一步处理人',
                        type: 'error'
                    });
                    return;
                }
            }
            if (this.auditForm.auditRemark
                && this.auditForm.auditRemark.length > 240) {
                this.$message({
                    message: '意见内容长度不能大于240字',
                    type: 'error'
                });
                return;
            }
            //提交
            var _this = this;
            var url = '/market/cIncomeExcelIssued/excelDataProcessAuth';
            this.loading = true;
            this.$http({
                url: url,
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    type: this.auditForm.authType,
                    excelData: this.excelData,
                    issuedUserId: this.getUrlKey("id"),
                    nextUserId: this.auditUserId,
                    auditRemark: this.auditForm.auditRemark
                },
            }).then((res) => {
                this.loading = false;
                if (res.data.result === 1) {
                    _this.$message({
                        message: res.data.desc,
                        type: 'error'
                    });
                } else {
                    this.authDialog = false;
                    _this.$message({
                        message: '处理成功',
                        type: 'success'
                    });
                    //没找到关闭标签页之前的临时处理措施
                    const newUrl = '#' + this.$route.path + '?type=4&id=' + this.getUrlKey("id");
                    console.log(newUrl);
                    window.history.replaceState('', '', newUrl);
                    document.getElementById('excelIframe').contentWindow.location.reload();
                    //关闭这个窗口，得找找怎么关闭
                    //this.$router.go(-1);
                }
            });

        },
        addNewTemplate(sheetName, excelData, templateType) {
            //console.log(sheetName);
            //console.log(excelData);
            //console.log(templateType);
            //处理一下数据，提交给后端
            var authUser = [];
            if (this.authType == '1') {
                this.noLimitUsers.map((o) => {
                    authUser.push({
                        userId: o,
                        type: 0
                    })
                });
            } else {
                //外层是权限组
                this.limitList.map((o) => {
                    //内层是权限用户
                    o.userIds.map((o1) => {
                        authUser.push({
                            userId: o1,
                            type: 1,
                            editStart: o.editStart,
                            editEnd: o.editEnd
                        })
                    })
                });
            }
            //console.log(authUser);
            //提交
            var _this = this;
            var url = '/market/cIncomeExcelTemplate/addNewTemplate';
            if (this.type == '2') {
                url = '/market/cIncomeExcelTemplate/updateTemplate';
            }
            this.loading = true;
            this.$http({
                url: url,
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    excelData: excelData,
                    excelName: sheetName,
                    userList: authUser,
                    templateType: templateType,
                    excelId: this.getUrlKey('id'),
                },
            }).then((res) => {
                this.loading = false;
                if (res.data.result === 1) {
                    _this.$message({
                        message: res.data.desc,
                        type: 'error'
                    });
                } else {
                    var msgText = '新增成功';
                    if (this.type == '2') {
                        msgText = '修改成功';
                    }
                    _this.$message({
                        message: msgText,
                        type: 'success'
                    });
                    const newUrl = '#' + this.$route.path + '?type=2&id=' + res.data.desc;
                    console.log(newUrl);
                    window.history.replaceState('', '', newUrl);
                    if (this.type == '1') {
                        this.type = '2';
                        document.getElementById('excelIframe').contentWindow.location.reload();
                    }
                    //this.$store.dispatch('tagsView/delView',this.$route)
                    //this.$router.go(-1);
                }
            });
        },
        showAuthDialog() {
            this.authSettingStatus = true;
        },
        processAuth() {
            console.log(this.limitList);
            //判断一下
            var success = true;
            if (this.authType == '1') {
                if (this.noLimitUsers.length == 0) {
                    this.$message({
                        message: '请选择无特殊权限的负责人',
                        type: 'error'
                    });
                    success = false;
                    return;
                }
            } else if (this.authType == '2') {
                this.limitList.map((o) => {
                    if (o.userIds == null) {
                        this.$message({
                            message: '请选择特殊权限的负责人',
                            type: 'error'
                        });
                        success = false;
                        return;
                    }
                    if (o.editStart == null || o.editEnd == null) {
                        this.$message({
                            message: '请填写可编辑行',
                            type: 'error'
                        });
                        success = false;
                        return;
                    }
                })
            }
            if (success) {
                if (this.type == '1') {
                    this.$refs.iframe.contentWindow.enableUpload('abc');
                } else if (this.type == '2') {
                    this.$refs.iframe.contentWindow.enableSave('def');
                }
                this.authSettingStatus = false;
            }
        },
        addNewLimitAuth() {
            var _this = this;
            if (this.authType == '2') {
                if (_this.limitList.length == 0) {
                    _this.limitList.push({
                        index: 1
                    });
                } else {
                    var lastLimitUserList = _this.limitList[_this.limitList.length - 1].userIds;
                    if (lastLimitUserList == null) {
                        _this.$message({
                            message: '请先选择上一条记录的负责人',
                            type: 'error'
                        });
                    } else {
                        _this.limitList.push({
                            index: 1
                        });
                    }
                }
            } else {
                _this.$message({
                    message: '请先选择特殊权限再添加',
                    type: 'error'
                });
            }

        },
        processNoLimitUsers() {
            var userNameString = '';
            if (this.authType == '1') {
                this.noLimitUsers = [];
                this.treeList.map((o) => {
                    this.noLimitUsers.push(o.receiveNo);
                    userNameString += o.receiveName += ' ';
                });
                this.noLimitUserName = userNameString;
            } else {
                this.limitList[this.limitUserIndex].userIds = [];
                this.treeList.map((o) => {
                    this.limitList[this.limitUserIndex].userIds.push(o.receiveNo);
                    userNameString += o.receiveName += ' ';
                });
                this.limitList[this.limitUserIndex].userName = userNameString;
            }
            this.exaList = {};
            this.defaultList = [];
            this.treeList = [];
            this.noLimitDialog = false;
        },
        noLimitUserAdd() {
            if (this.authType == '1') {
                this.noLimitDialog = true;
            } else {
                this.$message({
                    message: '请先选择无特殊权限，再添加负责人',
                    type: 'error'
                });
            }
        },
        limitUserAdd(index) {
            if (this.authType == '2') {
                this.limitUserIndex = index;
                this.noLimitDialog = true;
            } else {
                this.$message({
                    message: '请先选择特殊权限，再添加负责人',
                    type: 'error'
                });
            }
        },
        setAuth(id) {
            var _this = this;
            this.$http({
                url: '/market/cIncomeExcelTemplate/getAuthInfo',
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    excelId: id
                },
            }).then((res) => {
                if (res.data.result === 1) {
                    _this.$message({
                        message: '获取负责人信息失败',
                        type: 'error'
                    });
                } else {
                    console.log(res.data);
                    var authUsers = res.data.body;
                    var i = -1;
                    var nowStart = '';
                    var nowEnd = '';
                    this.limitList = [];
                    this.noLimitUsers = [];
                    this.noLimitUserName = '';
                    authUsers.map((o) => {
                        console.log(o);
                        //无特殊权限的简单一点，有特殊权限的，需要把相同可编辑行的放在一起
                        if (o.type == '0') {
                            this.authType = '1';
                            this.noLimitUsers.push(o.userId);
                            this.noLimitUserName += o.userName += ' ';
                        } else {
                            this.authType = '2';
                            if (o.editStart == nowStart && o.editEnd == nowEnd) {
                                var processLimitUser = this.limitList[i];
                                processLimitUser.userIds.push(o.userId);
                                processLimitUser.userName += o.userName += ' ';
                            } else {
                                var userIds = [o.userId];
                                var userName = o.userName += ' ';
                                this.limitList.push({
                                    userIds: userIds,
                                    userName: userName,
                                    editStart: o.editStart,
                                    editEnd: o.editEnd
                                })
                                nowStart = o.editStart;
                                nowEnd = o.editEnd;
                                i++;
                            }
                        }
                    });
                }
            });
        },
        //填报人相关
        deletes(val, index) {
            this.treeList.splice(index, 1);
            this.closeList = this.treeList;
        },
        treeCheckonly(v) {
            this.treeList = v;
            this.treeListonly = v;
        },
        treeDelete() {
            this.treeListonly = {};
            this.closeList = !this.closeList;
        },
        getUrlKey(name) {
            return (
                decodeURIComponent(
                    (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
                        location.href
                    ) || [, ""])[1].replace(/\+/g, "%20")
                ) || null
            );
        },
        processFullScreen() {
            this.fullscreen = !this.fullscreen;
        },
    },
    mounted() {
        this.type = this.getUrlKey("type")
    },
    created() {
        window['fullScreen'] = (rp) => {
            this.processFullScreen(rp);
        }
        window['showAuthDialog'] = (rp) => {
            this.showAuthDialog(rp);
        }
        window['addNewTemplate'] = (sheetName, excelData, templateType) => {
            this.addNewTemplate(sheetName, excelData, templateType);
        };
        window['setAuth'] = (id) => {
            this.setAuth(id);
        };
        window['openAuditWindow'] = (sheetName, excelData) => {
            this.openAuditWindow(sheetName, excelData);
        };
    }
}
</script>
<style lang="scss" scoped>
.online {
    width: 100%;

    .el-select {
        width: calc(100% - 100px);
    }

    span {
        vertical-align: top;
    }

    .el-textarea {
        width: calc(100% - 100px);
    }

    .tree {
        width: calc(50% - 60px);
        display: inline-block;
        margin-right: 20px;
        height: 300px;
        overflow-y: scroll;

        .el-icon-error {
            float: right;
            font-size: 20px;
            margin-top: 9px;
            cursor: pointer;
        }
    }

    .treeUser {
        margin: 0;
        border: 1px solid #ddd;

        p {
            background: #f4f4f4;
            padding: 0 20px;
            margin-bottom: 5px;
        }
    }

    .treeUserb {
        width: calc(100% - 100px);
        border: 1px solid #ddd;
        background: #f4f4f4;
        border-radius: 3px;
        height: auto;
        overflow: hidden;

        p {
            display: inline-block;
            padding: 0 20px;
            margin-bottom: 5px;
        }
    }
}
</style>
<style scoped>
.containerr {
    background: #fff;
    height: calc(100vh);
    width: calc(100vw);
    position: fixed;
    left: 0;
    top: 0;
    overflow: hidden;
}

span {
    width: 80px;
}
</style>
