<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="addcompany()" 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="companyCode" label="公司code" width="100">
                    </el-table-column>
                    <el-table-column prop="companyName" label="公司名称" width="200">
                    </el-table-column>
                    <el-table-column prop="address" label="公司所在地" width="220">
                    </el-table-column>
                    <el-table-column prop="contactUserName" label="负责人" width="100">
                    </el-table-column>
                    <el-table-column prop="tel" label="联系方式" width="120">
                    </el-table-column>
                    <el-table-column prop="parentCompanyName" label="父级公司名称" width="200">
                    </el-table-column>
                    <!-- <el-table-column prop="remark" label="备注" width="200">
                    </el-table-column> -->
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="upDateOp(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>
            <el-dialog title="修改公司信息" :visible.sync="upDataVisible" width="50%" :before-close="handleClose">
                <div>
                    <div>
                        <el-form :model="updata" :rules="rules" ref="updata" label-width="100px" class="demo-ruleForm">
                            <el-form-item label="公司名称" prop="CompanyName">
                                <el-input placeholder="请输入内容" v-model="updata.CompanyName">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="公司Codel" prop="CompanyCode">
                                <el-input placeholder="请输入内容" v-model="updata.CompanyCode">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="公司地址" prop="Address">
                                <el-input placeholder="请输入内容" v-model="updata.Address">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="公司负责人" prop="ParentDepId">
                                <el-select v-model="valueUserValue" placeholder="请选择负责人">
                                    <el-option v-for="item in optionsUsers" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="负责人电话" prop="Tel">
                                <el-input placeholder="请输入内容" v-model="updata.Tel">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="上级公司" prop="ParentDepId">
                                <el-select v-model="valueCompanyValue" placeholder="请选择负责人">
                                    <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="Remark">
                                <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="updata.Remark"
                                    style="width: 80%;"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="upDataVisible = false">取 消</el-button>
                    <el-button type="primary" @click="upDateBtn">保 存</el-button>
                </span>
            </el-dialog>

            <el-dialog title="添加公司" :visible.sync="addDataVisible" width="50%" :before-close="handleClose">
                <div>
                    <div>
                        <el-form :model="adddata" :rules="rules" ref="adddata" label-width="100px" class="demo-ruleForm">
                            <el-form-item label="公司名称" prop="CompanyName">
                                <el-input placeholder="请输入内容" v-model="adddata.CompanyName">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="公司Codel" prop="CompanyCode">
                                <el-input placeholder="请输入内容" v-model="adddata.CompanyCode">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="公司地址" prop="Address">
                                <el-input placeholder="请输入内容" v-model="adddata.Address">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="公司负责人" prop="ParentDepId">
                                <el-select v-model="valueUserValue" placeholder="请选择负责人">
                                    <el-option v-for="item in optionsUsers" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="负责人电话" prop="Tel">
                                <el-input placeholder="请输入内容" v-model="adddata.Tel">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="上级公司" prop="ParentDepId">
                                <el-select v-model="valueCompanyValue" placeholder="请选择负责人">
                                    <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="Remark">
                                <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="adddata.Remark"
                                    style="width: 80%;"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDataVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addDateBtn">保 存</el-button>
                </span>
            </el-dialog>
        </div>

    </div>
</template>
<script>
import { co, el } from '@fullcalendar/core/internal-common';
import { del } from 'vue';
export default {
    data() {
        var isnumber = (rule, value, callback) => {

            var reg = /^1[3456789]\d{9}$/;//小数点左边最高16位，小数点右边最多4位
            if (reg.test(value)) {
                callback();
            } else
                callback(new Error("请输入正确的手机号"));


        };
        return {

            tableDatas: [],
            tableData: [],
            currentPage: 1, // 当前页码
            pageSize: 15,// 每页的数据条数
            input: '',
            token: '',
            userId: 0,
            upDataVisible: false,
            addDataVisible: false,
            updata: {
                Id: 0,
                CompanyCode: "",
                CompanyName: "",
                Address: "",
                ContactUserId: 0,
                Tel: "",
                ParentCompanyId: 0,
                Remark: ""
            },
            adddata: {
                CreateUserId: this.userId,
                CompanyCode: "",
                CompanyName: "",
                Address: "",
                ContactUserId: 0,
                Tel: "",
                ParentCompanyId: 0,
                Remark: ""
            },
            optionsUsers: [{
                value: 0,
                label: '请选择公司负责人'
            }],
            valueUserValue: 0,
            optionsCompanys: [{
                value: 0,
                label: '请选择上级公司'
            }],
            valueCompanyValue: 0,
            //验证

            rules: {
                CompanyName: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' },
                ],
                CompanyCode: [
                    { required: true, message: '请输入公司Code', trigger: 'blur' },
                ],
                Address: [
                    { required: true, message: '公司地址不能为空', trigger: 'change' }
                ],
                ContactUserId: [
                    { required: true, message: '负责人不能为空', trigger: 'change' }
                ],
                Tel: [
                    { validator: isnumber, message: '请输入正确的手机号', trigger: 'change' }
                ],
            },
        }
    },
    methods: {
        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.currentPage = 1;
            this.pageSize = val;
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.currentPage = val;
        },
        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) {
                if (res.data.code == 200) {
                    that.tableDatas = res.data.data;
                    that.tableData = that.tableDatas
                    that.tableDatas.forEach(function (item, index) {
                        that.optionsCompanys.push({
                            value: item.id,
                            label: item.companyName
                        });
                    });
                    if (that.tableDatas.slice((that.currentPage - 1) * that.pageSize, that.currentPage * that.pageSize).length == 0) {
                        if (that.currentPage > 1) {
                            that.currentPage = that.currentPage - 1;
                        }
                    }
                }
            }).catch(function (error) {
                that.$message.error("网络错误，请稍后重试");
            });
        },
        Inquireclick() {
            var newarr = [];
            if (this.input == "") {
                newarr = this.tableData;
            } else {
                for (var i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].companyName.indexOf(this.input) != -1) {
                        newarr.push(this.tableData[i]);
                    }
                }
            }
            this.tableDatas = newarr;
            this.currentPage = 1;
        },
        //#region  修改操作
        upDateOp(index, row) {
            this.upDataVisible = true;
            this.updata.Id = row.id
            this.updata.CompanyCode = row.companyCode
            this.updata.CompanyName = row.companyName
            this.updata.Address = row.address
            this.updata.Tel = row.tel
            this.updata.ContactUserId = row.contactUserId
            this.updata.ParentCompanyId = row.parentCompanyId
            this.updata.Remark = row.remark
            this.valueUserValue = row.contactUserId
            this.valueCompanyValue = row.parentCompanyId


        },
        upDateBtn() {
            this.$refs.updata.validate((valid) => {
                if (valid) {
                    var that = this
                    if (that.updata.Id != 0) {
                        this.updata.ContactUserId = this.valueUserValue
                        this.updata.ParentCompanyId = this.valueCompanyValue
                        if (that.updata.CompanyName == "" || that.updata.CompanyName == undefined) {
                            that.$message.error("公司名称不能为空");
                            return
                        }
                        if (that.updata.CompanyCode == "") {
                            that.$message.error("公司code不能为空");
                            return
                        }
                        if (that.updata.Address == "") {
                            that.$message.error("公司地址不能为空");
                            return
                        }
                        if (that.updata.ContactUserId == 0) {
                            that.$message.error("请选择公司负责人");
                            return
                        }

                        ;
                        var url = "/api/System/EditCompany"
                        var that = this
                        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.upDataVisible = false
                                that.company();
                            } 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/DelCompany"
                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.company();
                    } else {
                        that.$message.error("删除失败，请稍后重试");
                    }
                })

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

        },
        //#region 添加
        addcompany() {
            this.addDataVisible = true

        },

        addDateBtn() {

            this.$refs.adddata.validate((valid) => {
                if (valid) {
                    var that = this
                    this.adddata.ContactUserId = this.valueUserValue
                    this.adddata.ParentCompanyId = this.valueCompanyValue
                    this.adddata.CreateUserId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
                    if (that.adddata.CompanyName == "" || that.updata.CompanyName == undefined) {
                        that.$message.error("公司名称不能为空");
                        return
                    }
                    if (that.adddata.CompanyCode == "") {
                        that.$message.error("公司code不能为空");
                        return
                    }
                    if (that.adddata.Address == "") {
                        that.$message.error("公司地址不能为空");
                        return
                    }
                    if (that.adddata.ContactUserId == 0) {
                        that.$message.error("请选择公司负责人");
                        return
                    }
                    if (that.adddata.Tel == "") {
                        that.$message.error("请输入手机号");
                        return
                    } else {
                        var reg = /^1[3456789]\d{9}$/;
                        if (!reg.test(that.adddata.Tel)) {
                            that.$message.error("请输入有效的手机号");
                            return
                        }
                    }

                    var url = "/api/System/AddCompany"

                    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.addDataVisible = false;
                            that.adddata.CreateUserId = 0
                            that.adddata.CompanyCode = ""
                            that.adddata.CompanyName = ""
                            that.adddata.Address = ""
                            that.adddata.ContactUserId = 0
                            that.adddata.Tel = ""
                            that.adddata.ParentCompanyId = 0
                            that.adddata.Remark = ""
                            that.valueUserValue = 0
                            that.valueCompanyValue = 0
                            that.company();
                        } else {
                            that.$message.error('添加失败！');
                        }
                    })
                }
            }).catch(function (error) {
                that.$message.error("网络错误，请稍后重试");
            });
        },
        //#endregion
        //绑定负责人下拉框
        optionsUser() {
            var url = "/api/System/QueryUserList"
            var that = this
            that.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.token
                },
                data: {
                    portType: 1,
                    CompanyId: 0,
                    DepId: 0,
                    JobPostId: 0
                }
            }).then(function (res) {
                console.log(res)

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

                    const data = res.data.data;
                    data.forEach(function (item, index) {
                        that.optionsUsers.push({
                            value: item.id,
                            label: item.cnName
                        });
                    });
                    that.optionUserValue = '4'
                }
            })
        },
    },
    mounted() {

        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId
        console.log(this.token)
        this.company();
        this.optionsUser();
    }
}
</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>