<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="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="操作" width="200">
                        <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">
            <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">
            <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="请选择上级部门">
                            <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: [],
            ParentDepId: '',
            optionsCompanys: [],
            CompanyId: ''
        }
    },
    methods: {
        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.currentPage = 1;
            this.pageSize = val;
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.currentPage = val;

        },
        Department() {
            var url = "http://localhost:5256/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) {
                debugger
                console.log(res)

                if (res.data.code == 200) {
                    debugger
                    debugger
                    that.tableDatas = res.data.data;
                    that.tableData = that.tableDatas
                    that.tableDatas.forEach(function (item, index) {
                        that.optionsDepartment.push({
                            value: item.id,
                            label: item.depName
                        });
                    });
                }
            })
        },
        //公司下拉框绑定
        company() {
            var url = "http://localhost:5256/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)
                debugger
                if (res.data.code == 200) {
                    debugger
                    res.data.data.forEach(function (item, index) {
                        that.optionsCompanys.push({
                            value: item.id,
                            label: item.companyName
                        });
                    });

                }
            })
        },
        handleChange(event) {
            debugger
            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]);
                    }
                    if (this.tableData[i].companyName.indexOf(this.input) != -1) {
                        newarr.push(this.tableData[i]);
                    }
                }
            }
            this.tableDatas = newarr;
        },
        //#region  修改操作
        upDate(index, row) {
            debugger
            this.upDepVisible = true;
            this.upData.Id = row.id
            this.upData.CompanyId = row.companyId
            this.upData.DepCode = row.depCode
            this.upData.DepName = row.depName
            this.upData.ParentDepId = row.parentDepId
            this.upData.Remark = row.remark
        },
        upDateBtn() {
            debugger
            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
                    }
                    var url = "http://localhost:5256/api/System/EditDepartment"

                    that.$axios({
                        method: 'post',
                        url: url,
                        headers: {
                            Authorization: 'Bearer ' + that.token
                        },
                        data: that.upData
                    }).then(function (res) {
                        console.log(res)
                        debugger
                        if (res.data.code == 200) {
                            that.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            that.upDepVisible = false;
                            that.Department();
                        } else {
                            that.$message.error('修改失败！');
                        }
                    })
                } else {
                    this.$message.error('请完善信息在保存！');
                    return false;
                }
            })
        },
        //关闭修改框
        handleClose(done) {
            done();
        },
        //#endregion
        del(index, row) {
            debugger
            this.$confirm('此操作将取消订单, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var url = "http://localhost:5256/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)
                    debugger
                    if (res.data.code == 200) {
                        that.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        that.Department();
                    } else {
                        that.$message.error("删除失败，请稍后重试");
                    }
                })

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

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

        },
        Addbtn() {
            debugger
            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 = "http://localhost:5256/api/System/AddDepartment"

                    that.$axios({
                        method: 'post',
                        url: url,
                        headers: {
                            Authorization: 'Bearer ' + that.token
                        },
                        data: that.addData
                    }).then(function (res) {
                        console.log(res)
                        debugger
                        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('添加失败！');
                        }
                    })
                } else {
                    this.$message.error('请完善信息在保存！');
                    return false;
                }
            })
        },
        //#endregion

    },
    mounted() {
        debugger
        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>