<template>
    <div id="personnel_info">
        <el-row type="flex" :gutter="20">
            <el-col :span="8">
                <el-input
                    v-model.trim="searchText"
                    clearable
                    prefix-icon="el-icon-search"
                    placeholder="请输入用户手机号"
                ></el-input>
            </el-col>
            <el-col :span="16">
                <el-button @click="handleSearch" type="primary">搜索</el-button>
                <el-button @click="handleAdd">新增人员</el-button>
            </el-col>
        </el-row>
        <br />
        <el-container>
            <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%"
                max-height="450"
            >
                <el-table-column
                    type="index"
                    :index="pageIndex"
                    align="center"
                    label="序号"
                    width="50"
                ></el-table-column>
                <el-table-column
                    prop="userName"
                    label="用户名称"
                ></el-table-column>
                <el-table-column
                    prop="userMobile"
                    label="用户手机号"
                ></el-table-column>
                <el-table-column
                    prop="userEmail"
                    label="用户邮箱"
                ></el-table-column>
                <el-table-column
                    prop="roleMemo"
                    label="用户角色"
                ></el-table-column>
                <el-table-column
                    prop="defaultChoose"
                    label="默认选择"
                ></el-table-column>
                <el-table-column label="操作" align="center" width="160">
                    <template slot-scope="scope">
                        <el-button @click="handleEdit(scope.row)" type="primary"
                            >编辑
                        </el-button>
                        <el-button @click="handleDelete(scope.row)" size="small"
                            >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-container>
        <br />
        <el-row type="flex" :gutter="20">
            <el-col :span="12"></el-col>
            <el-col :span="12">
                <div style="text-align: right">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-sizes="pagination.pageSizes"
                        :page-size="pagination.pageSize"
                        layout="total, sizes, prev, pager, next"
                        :total="pagination.total"
                    ></el-pagination>
                </div>
            </el-col>
        </el-row>
        <el-dialog
            :title="personnelSave.editMode ? '编辑人员信息' : '人员新增'"
            :visible.sync="personnelSave.visible"
            center
            width="60%"
            @opened="personnelSaveDialogOpened"
            @close="personnelSaveDialogClose"
        >
            <div
                v-loading="personnelSave.loading"
                element-loading-text="拼命加载中......请稍等"
            >
                <el-form
                    :model="personnelSave.form"
                    :rules="personnelSave.rules"
                    ref="personnelSaveForm"
                    label-position="top"
                >
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item
                                v-if="personnelSave.editMode"
                                label="员工姓名"
                                prop="name"
                            >
                                <el-input
                                    v-model="personnelSave.form.name"
                                    disabled
                                ></el-input>
                            </el-form-item>
                            <el-form-item v-else label="员工姓名" prop="name">
                                <el-input
                                    v-model="personnelSave.form.name"
                                    :disabled="personnelSave.existAccount"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <el-form-item
                                v-if="personnelSave.editMode"
                                label="手机号码"
                                prop="mobilePhone"
                            >
                                <el-input
                                    v-model="personnelSave.form.mobilePhone"
                                    disabled
                                    :clearable="true"
                                ></el-input>
                            </el-form-item>
                            <el-form-item
                                v-else
                                label="手机号码"
                                prop="mobilePhone"
                            >
                                <el-input
                                    v-model="personnelSave.form.mobilePhone"
                                    :clearable="true"
                                    @input="handleMobilePhoneChange"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-divider></el-divider>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <span>绑定企业</span>
                        </el-col>
                        <el-col :span="12">
                            <el-input
                                placeholder="请输入企业名称进行搜索"
                                suffix-icon="el-icon-search"
                                v-model="personnelSave.bindEnt.searchText"
                                :clearable="true"
                                @input="bindEntSearchTextChange"
                            >
                            </el-input>
                        </el-col>
                    </el-row>
                    <br />
                    <el-table
                        :data="personnelSave.bindEnt.resultList"
                        style="width: 100%"
                        max-height="350"
                    >
                        <el-table-column prop="entName" label="企业名称">
                        </el-table-column>
                        <el-table-column label="角色身份" align="center">
                            <el-table-column
                                v-for="item in personnelSave.entCategoryRoles"
                                :key="item.id"
                                prop="personnelRoleId"
                                width="180"
                                align="center"
                            >
                                <template slot="header">
                                    <span>{{ item.remark }}</span>
                                    <!-- <el-checkbox
                                        :indeterminate="
                                            personnelSave.bindEnt.checkAll[
                                                index
                                            ]
                                        "
                                        @change="
                                            handleAllCheckedChange(
                                                item.id,
                                                $event,
                                                index
                                            )
                                        "
                                        >{{ item.remark }}
                                    </el-checkbox> -->
                                </template>
                                <template slot-scope="scope">
                                    <el-radio
                                        v-model="scope.row.roleId"
                                        :label="item.id"
                                        @change="handleRoleChange(scope.row)"
                                        >&nbsp;
                                    </el-radio>
                                </template>
                            </el-table-column>
                        </el-table-column>
                    </el-table>
                    <br />
                    <el-row type="flex" :gutter="20">
                        <el-col :span="12">
                            <div>
                                <el-pagination
                                    layout="total, sizes, prev, pager, next"
                                    :current-page="
                                        personnelSave.bindEnt.resultPagination
                                            .currentPage
                                    "
                                    :page-sizes="
                                        personnelSave.bindEnt.resultPagination
                                            .pageSizes
                                    "
                                    :page-size="
                                        personnelSave.bindEnt.resultPagination
                                            .pageSize
                                    "
                                    :total="
                                        personnelSave.bindEnt.resultPagination
                                            .total
                                    "
                                    @size-change="handleBindEntResultSizeChange"
                                    @current-change="
                                        handleBindEntResultCurrentChange
                                    "
                                ></el-pagination>
                            </div>
                        </el-col>
                        <el-col :span="12" style="text-align: right">
                            <el-button @click="personnelSave.visible = false"
                                >取消</el-button
                            >
                            <el-button type="primary" @click="handleRolesSave"
                                >保存</el-button
                            >
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import cache from "@/utils/cache";
import USER_MANAGEMENT from "@/api/user-management";

export default {
    name: "UserManagement",
    data() {
        return {
            searchText: "",
            tableData: [],
            pagination: {
                currentPage: 1,
                pageSizes: [10, 30, 50, 100],
                pageSize: 10,
                total: 0,
            },
            personnelSave: {
                visible: false,
                loading: false,
                editMode: false, // 修改或新增
                entCategoryRoles: [], // 企业角色类别
                existAccount: false, // 是否存在账户
                mobilePhoneChangeTimer: "",
                form: {
                    name: "",
                    mobilePhone: "",
                    entUserEmail: "",
                },
                rules: {
                    name: [
                        {
                            required: true,
                            message: "请输入购方名称",
                            trigger: "blur",
                        },
                    ],
                    mobilePhone: [
                        {
                            required: true,
                            message: "请输入手机号码",
                            trigger: "blur",
                        },
                    ],
                },
                bindEnt: {
                    searchText: "",
                    serachTimer: "",
                    personnelEntList: [], // 根据开票员电话获取的绑定企业列表
                    resultList: [], // 当前登录用户可操作的企业列表
                    resultMultipleSelection: [],
                    resultPagination: {
                        currentPage: 1,
                        pageSizes: [10, 30, 50],
                        pageSize: 50,
                        total: 0,
                    },
                },
            },
        };
    },
    created() {
        this.callGetEntUserRoleInfo(
            this.pagination.currentPage,
            this.pagination.pageSize
        );
    },
    methods: {
        pageIndex(index) {
            let currentPage = this.pagination.currentPage; // 当前页码，具体看组件取值
            let pageSize = this.pagination.pageSize; // 每页条数，具体是组件取值
            return index + 1 + (currentPage - 1) * pageSize;
        },
        handleSearch() {
            this.callGetEntUserRoleInfo(1, this.pagination.pageSize);
        },
        personnelSaveDialogOpened() {
            let _this = this;
            _this.getEntCategoryRoles().then((val) => {
                _this
                    .getCurrentUserEntList(
                        1,
                        _this.personnelSave.bindEnt.resultPagination.pageSize
                    )
                    .then((val) => {
                        if (_this.personnelSave.editMode) {
                            _this.getPersonnelBindList(
                                _this.personnelSave.form.mobilePhone
                            );
                        }
                    });
            });
        },
        personnelSaveDialogClose() {
            this.personnelSave.existAccount = false;
            this.personnelSave.form.name = "";
            this.personnelSave.form.mobilePhone = "";
            this.personnelSave.form.entUserEmail = "";
            this.personnelSave.entCategoryRoles = [];
            this.personnelSave.bindEnt.personnelEntList = [];

            this.$refs["personnelSaveForm"].resetFields();

            this.callGetEntUserRoleInfo(
                this.pagination.currentPage,
                this.pagination.pageSize
            );
        },
        // 开票员电话号码改变时查询企业关联关系
        handleMobilePhoneChange() {
            let _this = this;
            clearTimeout(_this.personnelSave.mobilePhoneChangeTimer);
            _this.personnelSave.mobilePhoneChangeTimer = setTimeout(() => {
                console.log("开票员电话号码改变时查询");

                _this.personnelSave.loading = true;
                USER_MANAGEMENT.userEntBindInfo({
                    userMobile: _this.personnelSave.form.mobilePhone,
                    pageNum: 1,
                    pageSize: 2000,
                })
                    .then((val) => {
                        _this.personnelSave.existAccount = true;
                        _this.personnelSave.form.name = val.data.userName;
                        _this.personnelSave.bindEnt.personnelEntList =
                            val.data.records;
                        // 反显权限
                        _this.SetBindEntAuth();
                        _this.personnelSave.loading = false;

                        _this.getCurrentUserEntList(
                            1,
                            _this.personnelSave.bindEnt.resultPagination
                                .pageSize
                        );
                    })
                    .catch((err) => {
                        _this.personnelSave.existAccount = false;
                        _this.personnelSave.form.name = "";
                        _this.personnelSave.bindEnt.personnelEntList = [];
                        // 反显权限
                        _this.SetBindEntAuth();
                        _this.personnelSave.loading = false;

                        _this.getCurrentUserEntList(
                            1,
                            _this.personnelSave.bindEnt.resultPagination
                                .pageSize
                        );
                    });
            }, 1000);
        },
        // 角色修改根据企业名称查询企业
        bindEntSearchTextChange() {
            let _this = this;
            clearTimeout(_this.personnelSave.bindEnt.serachTimer);
            _this.personnelSave.bindEnt.serachTimer = setTimeout(() => {
                _this.getCurrentUserEntList(
                    1,
                    _this.personnelSave.bindEnt.resultPagination.pageSize
                );
            }, 1000);
        },
        // 获取企业的角色类别
        getEntCategoryRoles() {
            let _this = this;
            return new Promise(function (resolve, reject) {
                _this.personnelSave.loading = true;
                USER_MANAGEMENT.getEntCategoryRoles()
                    .then((val) => {
                        let roles = val.data;
                        for (let i = 0; i < roles.length; i++) {
                            // 移除 企业管理者
                            if (roles[i].remark === "企业管理者") {
                                roles.splice(i, 1);
                            }
                            roles[i].checked = false;
                        }
                        // 增加无效选项
                        roles.push({ remark: "无效", id: "" });

                        _this.personnelSave.entCategoryRoles = roles;
                        _this.personnelSave.loading = false;
                        resolve(val);
                    })
                    .catch((err) => {
                        _this.personnelSave.loading = false;
                        _this.$alert(
                            "数据获取失败窗口将关闭！请尝试重新操作。",
                            "提示",
                            {
                                confirmButtonText: "确定",
                                callback: (action) => {
                                    _this.personnelSave.visible = false;
                                },
                            }
                        );
                        reject(err);
                    });
            });
        },
        // 获取当前登陆用户可操作企业列表
        getCurrentUserEntList(pageNum, pageSize) {
            let mobile = JSON.parse(cache.getSession("user")).account;
            let _this = this;
            return new Promise(function (resolve, reject) {
                _this.personnelSave.loading = true;
                USER_MANAGEMENT.userEntBindInfo({
                    userMobile: mobile,
                    entName: _this.personnelSave.bindEnt.searchText,
                    pageNum: pageNum,
                    pageSize: pageSize,
                })
                    .then((val) => {
                        if (val.data.records) {
                            for (const item of val.data.records) {
                                item.roleId = "";
                            }
                        }
                        _this.personnelSave.bindEnt.resultPagination.total =
                            val.data.total;
                        _this.personnelSave.bindEnt.resultPagination.pageSize =
                            val.data.size;
                        _this.personnelSave.bindEnt.resultPagination.currentPage =
                            val.data.current;
                        _this.personnelSave.bindEnt.resultList =
                            val.data.records;

                        // 反显权限
                        _this.SetBindEntAuth();
                        _this.personnelSave.loading = false;
                        resolve(val);
                    })
                    .catch((err) => {
                        _this.personnelSave.loading = false;
                        reject(err);
                    });
            });
        },
        // 获取开票员已绑定企业列表
        getPersonnelBindList(mobile) {
            let _this = this;
            return new Promise(function (resolve, reject) {
                _this.personnelSave.loading = true;
                USER_MANAGEMENT.userEntBindInfo({
                    userMobile: mobile,
                    pageNum: 1,
                    pageSize: 2000,
                })
                    .then((val) => {
                        _this.personnelSave.bindEnt.personnelEntList =
                            val.data.records;
                        // 反显权限
                        _this.SetBindEntAuth();
                        _this.personnelSave.loading = false;
                    })
                    .catch((err) => {
                        _this.personnelSave.loading = false;
                    });
            });
        },
        // 设置绑定企业权限
        SetBindEntAuth() {
            if (
                this.personnelSave.bindEnt.resultList &&
                this.personnelSave.bindEnt.personnelEntList
            ) {
                console.log("设置绑定企业权限");
                const arrayI = this.personnelSave.bindEnt.resultList;
                const arrayJ = this.personnelSave.bindEnt.personnelEntList;
                for (let i = 0; i < arrayI.length; i++) {
                    const elementI = arrayI[i];
                    for (let j = 0; j < arrayJ.length; j++) {
                        const elementJ = arrayJ[j];
                        if (elementI.entTaxId === elementJ.entTaxId) {
                            // 覆盖写在当前登录企业可操作企业角色的 roleId 字段
                            elementI.roleId = elementJ.roleId;

                            this.$set(arrayI, i, elementI);
                            console.log("匹配到企业：");
                            console.log(elementI);
                        }
                    }
                }
            }
        },
        // 角色身份改变
        handleRoleChange(row) {
            console.log("角色身份改变：");
            console.log(row);
            const arrayI = this.personnelSave.bindEnt.personnelEntList;
            for (let i = 0; i < arrayI.length; i++) {
                const elementI = arrayI[i];
                if (elementI.entTaxId === row.entTaxId) {
                    elementI.roleId = row.roleId;
                    console.log("已记录角色身份变更：");
                    console.log(row);
                    break;
                }
            }
            // 如果没有找到，则添加角色身份信息
            arrayI.push(row);
        },
        // 保存角色身份
        handleRolesSave() {
            let _this = this;
            this.$refs["personnelSaveForm"].validate((valid) => {
                if (valid) {
                    let entUserRoleVOs = [];
                    const allEntRoleList =
                        _this.personnelSave.bindEnt.personnelEntList;
                    for (const item of allEntRoleList) {
                        if (item.roleId !== "") {
                            entUserRoleVOs.push({
                                entTaxId: item.entTaxId,
                                roleId: item.roleId,
                            });
                        }
                    }
                    _this.personnelSave.loading = false;
                    USER_MANAGEMENT.entUserSave({
                        entUserMobile: _this.personnelSave.form.mobilePhone,
                        entUserName: _this.personnelSave.form.name,
                        entUserEmail: _this.personnelSave.form.entUserEmail,
                        entUserRoleVOs: entUserRoleVOs,
                    })
                        .then((val) => {
                            _this.$message.success(val.msg);
                            _this.personnelSave.loading = false;
                            _this.personnelSave.visible = false;
                        })
                        .catch((err) => {
                            _this.$message.error(err);
                            _this.personnelSave.loading = false;
                        });
                } else {
                    _this.$message.error(
                        "输入信息不合法，请检查您的输入信息！"
                    );
                    return false;
                }
            });
        },
        // 全选或全部取消
        handleAllCheckedChange(roleId, checked, index) {
            console.log("checked");
            console.log(checked);
            const arrayI = this.personnelSave.bindEnt.resultList;
            if (arrayI) {
                console.log("批量设置绑定企业权限");
                for (let i = 0; i < arrayI.length; i++) {
                    const elementI = arrayI[i];
                    elementI.roleId = checked ? roleId : "";

                    this.handleRoleChange(elementI);
                }
            }

            const arrayCheckAll = this.personnelSave.bindEnt.checkAll;
            if (arrayCheckAll) {
                for (let i = 0; i < arrayCheckAll.length; i++) {
                    const element = arrayCheckAll[i];
                    element = i === index ? true : false;
                }
            }

            // 更新全选checkbox控件选中状态
            // const arrayRoles = this.personnelSave.entCategoryRoles;
            // console.log("更新前：");
            // console.log(arrayRoles);
            // if (arrayRoles) {
            //     for (let i = 0; i < arrayRoles.length; i++) {
            //         const element = arrayRoles[i];
            //         if (element.id !== roleId) {
            //             element.checked = false;
            //         } else {
            //             element.checked = true;
            //         }
            //         this.$set(arrayRoles, i, element);
            //     }
            // }
            // console.log("更新后：");
            // console.log(arrayRoles);
        },
        handleBindEntResultSizeChange(val) {
            this.getCurrentUserEntList(1, val);
        },
        handleBindEntResultCurrentChange(val) {
            this.getCurrentUserEntList(
                val,
                this.personnelSave.bindEnt.resultPagination.pageSize
            );
        },
        handleAdd() {
            this.personnelSave.editMode = false;
            this.personnelSave.form.name = "";
            this.personnelSave.form.mobilePhone = "";
            this.personnelSave.form.entUserEmail = "";
            this.personnelSave.bindEnt.personnelEntList = [];

            this.personnelSave.visible = true;
        },
        handleEdit(row) {
            if (row.roleMemo === "企业管理者") {
                this.$message({
                    message: "警告：企业管理者信息禁止编辑！",
                    type: "warning",
                });
            } else {
                this.personnelSave.editMode = true;
                this.personnelSave.form.name = row.userName;
                this.personnelSave.form.mobilePhone = row.userMobile;
                this.personnelSave.form.entUserEmail = row.entUserEmail;

                this.personnelSave.visible = true;
            }
        },
        handleDelete(row) {
            USER_MANAGEMENT.entUserDelete(row.userMobile)
                .then((val) => {
                    let index = this.tableData.indexOf(row);
                    if (this.tableData.indexOf(row) != -1) {
                        this.tableData.splice(index, 1);
                    }
                    this.$message.success(val.msg);
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },
        handleSizeChange(val) {
            this.callGetEntUserRoleInfo(1, val);
        },
        handleCurrentChange(val) {
            this.callGetEntUserRoleInfo(val, this.pagination.pageSize);
        },
        /**
         * 搜索当前登陆用户管理的用户列表
         * @param {Number} pageNum : 当前页码
         * @param {Number} pageSize : 每页数量
         */
        callGetEntUserRoleInfo(pageNum, pageSize) {
            let _this = this;
            USER_MANAGEMENT.getEntUserRoleInfo(
                this.searchText,
                pageNum,
                pageSize
            )
                .then((val) => {
                    _this.pagination.total = val.data.total;
                    _this.pagination.pageSize = val.data.size;
                    _this.pagination.currentPage = val.data.current;
                    _this.tableData = val.data.records;
                })
                .catch((_) => {
                    _this.$message.error(val.msg);
                });
        },
    },
};
</script>
