<template>
    <div>

        <div class="communal-list">
            <div class="communal-title">
                <div>部门列表</div>
                <div class="communal-box">
                    <el-input @input="Inquireclick()" placeholder="请输入内容" v-model="input" clearable>
                    </el-input>
                    <el-button @click="Inquireclick()" type="primary"><i class="iconfont icon-sousuo"></i></el-button>
                    <el-button @click="addDepartment()" type="primary">新增</el-button>
                </div>
            </div>
            <template>
                <el-table :data="tableDatas.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border
                    style="width: 100%">
                    <el-table-column prop="num" label="序 号" width="55">
                        <template slot-scope="scope">
                            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="depCode" label="部门Code" width="100">
                    </el-table-column>
                    <el-table-column prop="depName" label="部门名称" width="200">
                    </el-table-column>
                    <el-table-column prop="companyName" label="所属公司" width="220">
                    </el-table-column>
                    <el-table-column prop="parentDepName" label="上级部门" width="100">
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" width="240">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="upDate(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="mini" type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <div class="block">
                <el-pagination align='center' @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[10, 15, 20]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next" :total="tableDatas.length">
                </el-pagination>
            </div>
        </div>
        <el-dialog title="添加部门" :visible.sync="addDepVisible" width="30%" :before-close="handleClose" :close-on-click-modal="false">
            <div>
                <el-form :model="addData" :rules="rules" ref="addData" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="部门code" prop="DepCode">
                        <el-input placeholder="请输入内容" v-model="addData.DepCode">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="部门名称" prop="DepName">
                        <el-input placeholder="请输入内容" v-model="addData.DepName">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="所属公司" prop="CompanyId">
                        <el-select v-model="addData.CompanyId" filterable placeholder="请选择所属公司" @change="handleChange">
                            <el-option v-for="item in optionsCompanys" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上级部门" prop="parentDepId">
                        <el-select v-model="addData.parentDepId" placeholder="请选择上级部门">
                            <el-option v-for="item in optionsDepartment" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="备 注" prop="Remark">
                        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="addData.Remark"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDepVisible = false">取 消</el-button>
                <el-button type="primary" @click="Addbtn">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="修改部门" :visible.sync="upDepVisible" width="30%" :before-close="handleClose" :close-on-click-modal="false">
            <div>
                <el-form :model="upData" :rules="rules" ref="upData" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="部门code" prop="DepCode">
                        <el-input placeholder="请输入内容" v-model="upData.DepCode">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="部门名称" prop="DepName">
                        <el-input placeholder="请输入内容" v-model="upData.DepName">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="所属公司" prop="CompanyId">
                        <el-select v-model="upData.CompanyId" filterable placeholder="请选择所属公司" @change="handleChange">
                            <el-option v-for="item in optionsCompanys" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上级部门" prop="parentDepId">
                        <el-select v-model="upData.parentDepId" placeholder="请选择上级部门" clearable>
                            <el-option v-for="item in optionsDepartment" :key="item.value" :label="item.label" 
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备 注" prop="Remark">
                        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="upData.Remark"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="upDepVisible = false">取 消</el-button>
                <el-button type="primary" @click="upDateBtn">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { co, el } from '@fullcalendar/core/internal-common';
import { del } from 'vue';
export default {
    data() {
        return {

            tableDatas: [],
            tableData: [],
            currentPage: 1, // 当前页码
            pageSize: 15,// 每页的数据条数
            input: '',
            token: '',
            userId: 0,
            addDepVisible: false,
            upDepVisible: false,
            upData: {
                Id: 0,
                CompanyId: '',
                DepCode: "",
                DepName: "",
                parentDepId: 0,
                Remark: ""
            },
            //添加参数
            addData: {
                CompanyId: '',
                DepCode: "",
                DepName: "",
                parentDepId: 0,
                CreateUserId: this.userId,
                Remark: ""
            },

            rules: {
                DepCode: [
                    { required: true, message: '请输入部门Code', trigger: 'blur' },
                ],
                DepName: [
                    { required: true, message: '请输入部门名称', trigger: 'blur' },
                ],
                CompanyId: [
                    { required: true, message: '请选择所属公司', trigger: 'change' }
                ],
            },
            optionsDepartment: [],
            optionsCompanys: [],
            CompanyId: ''
        }
    },
    methods: {
        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.currentPage = 1;
            this.pageSize = val;
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.currentPage = val;

        },
        Department() {
            var url = "/api/System/QueryDepartmentList"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    portType: 1,
                    CompanyId: 0
                }
            }).then(function (res) {

                console.log(res)

                if (res.data.code == 200) {


                    that.tableDatas = res.data.data;
                    that.tableData = that.tableDatas
                    that.tableDatas.forEach(function (item, index) {
                        that.optionsDepartment.push({
                            value: item.id,
                            label: item.depName
                        });
                    });
                    if (that.tableDatas.slice((that.currentPage - 1) * that.pageSize, that.currentPage * that.pageSize).length == 0) {
                        if (that.currentPage > 1) {
                            that.currentPage = that.currentPage - 1;
                        }
                    }
                }
            })
        },
        //公司下拉框绑定
        company() {
            var url = "/api/System/getCompanyList"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + this.token
                },
                data: {
                    portType: 1,
                }
            }).then(function (res) {
                console.log(res)

                if (res.data.code == 200) {

                    res.data.data.forEach(function (item, index) {
                        that.optionsCompanys.push({
                            value: item.id,
                            label: item.companyName
                        });
                    });

                }
            })
        },
        handleChange(event) {

            var comId = event;
            const that = this;
            that.optionsDepartment = [{
                value: 0,
                label: '请选择上级部门'
            }]

            that.tableDatas.forEach(function (item, index) {
                if (item.companyId == comId && comId != 0) {
                    that.optionsDepartment.push({
                        value: item.id,
                        label: item.depName
                    });
                } else if (comId == 0) {
                    that.optionsDepartment.push({
                        value: item.id,
                        label: item.depName
                    });
                }
            });


        },
        Inquireclick() {
            var newarr = [];
            if (this.input == "") {
                newarr = this.tableData;
            } else {
                for (var i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].depName.indexOf(this.input) != -1) {
                        newarr.push(this.tableData[i]);
                    } else if (this.tableData[i].companyName.indexOf(this.input) != -1) {
                        newarr.push(this.tableData[i]);
                    }
                }
            }
            this.tableDatas = newarr;
            this.currentPage = 1;
        },
        //#region  修改操作
        upDate(index, row) {
            this.upDepVisible = true;
            this.upData.Id = row.id
            this.upData.CompanyId = row.companyId
            this.upData.DepCode = row.depCode
            this.upData.DepName = row.depName
            if (row.parentDepId == 0) {
                this.upData.parentDepId = ''
            } else {
                this.upData.parentDepId = row.parentDepId
            }

            this.upData.Remark = row.remark
        },
        upDateBtn() {

            var that = this
            this.$refs.upData.validate((valid) => {
                if (valid) {
                    that.upData.CreateUserId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
                    if (that.upData.DepName == "" || that.upData.DepName == undefined) {
                        that.$message.error("部门名称不能为空");
                        return
                    }
                    if (that.upData.DepCode == '') {
                        that.$message.error("部门code不能为空");
                        return
                    }
                    if (that.upData.CompanyId == 0) {
                        that.$message.error("请选择所属公司");
                        return
                    }
                    
                    if(that.upData.parentDepId=="")
                    {
                        that.upData.parentDepId=0;
                    }
                    var url = "/api/System/EditDepartment"

                    that.$axios({
                        method: 'post',
                        url: url,
                        headers: {
                            Authorization: 'Bearer ' + that.token
                        },
                        data: that.upData
                    }).then(function (res) {
                        console.log(res)

                        if (res.data.code == 200) {
                            that.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            that.upDepVisible = false;
                            that.Department();
                        } else {
                            that.$message.error('修改失败！');
                        }
                    })
                }
            }).catch(function (error) {
                that.$message.error("网络错误，请稍后重试");
            });
        },
        //关闭修改框
        handleClose(done) {
            done();
        },
        //#endregion
        del(index, row) {

            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var url = "/api/System/DelDepartment"
                var that = this
                this.$axios({
                    method: 'post',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + this.token
                    },
                    data: {
                        Id: row.id,
                    }
                }).then(function (res) {
                    console.log(res)
                    if (res.data.code == 200) {
                        that.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        that.Department();
                    } else {
                        that.$message.error("删除失败，请稍后重试");
                    }
                }).catch(function (error) {
                    that.$message.error("网络错误，请稍后重试");
                });

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '操作已取消！'
                });
            });

        },
        //#region 添加
        addDepartment() {
            this.addDepVisible = true

        },
        Addbtn() {

            this.$refs.addData.validate((valid) => {
                if (valid) {
                    var that = this
                    that.addData.CreateUserId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
                    if (that.addData.DepName == "" || that.addData.DepName == undefined) {
                        that.$message.error("部门名称不能为空");
                        return
                    }
                    if (that.addData.DepCode == "") {
                        that.$message.error("部门code不能为空");
                        return
                    }
                    if (that.addData.CompanyId == 0) {
                        that.$message.error("请选择所属公司");
                        return
                    }
                    var url = "/api/System/AddDepartment"

                    that.$axios({
                        method: 'post',
                        url: url,
                        headers: {
                            Authorization: 'Bearer ' + that.token
                        },
                        data: that.addData
                    }).then(function (res) {
                        console.log(res)

                        if (res.data.code == 200) {
                            that.$message({
                                message: '添加成功！',
                                type: 'success'
                            });
                            that.addDepVisible = false;
                            that.Department();
                            that.addData.CompanyId = 0;
                            that.addData.DepCode = "";
                            that.addData.DepName = "";
                            that.addData.parentDepId = 0;
                            that.addData.CreateUserId = this.userId;
                            that.addData.Remark = "";
                        } else {
                            that.$message.error('添加失败！');
                        }
                    })
                }
            }).catch(function (error) {
                that.$message.error("网络错误，请稍后重试");
            });
        },
        //#endregion

    },
    mounted() {

        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
        console.log(this.token)
        this.Department();
        this.company();
    }
}
</script>
<style>
.communal-list {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
}

.communal-title {
    display: flex;
    font-size: 17px;
    font-weight: 600;
    color: #555;
    margin-top: 8px;
    margin-bottom: 2px;
    justify-content: space-between;
    align-items: center;
}

.communal-box {
    display: flex;
}

.communal-box>button {
    margin-left: 10px;
    padding: 8px 20px;
}
</style>