<style lang="scss">
@import '@/styles/index.scss'; //导入样式

.operator {
    width: 100%;
    margin: auto;

    &__item {
        width: 100%;
        display: flex;

        &-left {
            flex: 1;
        }

        &-right {
            flex: none;
            width: 100px;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            padding-left: 15px;
            text-align: right;
        }
    }
}
</style>

<template>
    <div class="operator">
        <app-search>
            <el-form :inline="true" :model="tableData.listData.search" :size="controlSize">
                <el-form-item label="登录账户">
                    <el-input v-model.trim="tableData.listData.search.user_name" auto-complete="off"
                        clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="tableData.listData.loading == true"
                        @click="getOperatorPageList">查询</el-button>
                    <el-button type="success" @click="openAddDlg">新增管理员</el-button>
                </el-form-item>
            </el-form>
        </app-search>
        <app-table pagination paginationAlign="right" table :tableData="tableData.listData"
            :handlePageSizeChange="handlePageSizeChange" :handlePageNumChange="handlePageNumChange">
            <template slot="table-column">
                <el-table-column label="操作" header-align="center" width="100" testalign="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <span class="el-dropdown-link">
                                操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu>
                                <el-dropdown-item @click.native="openUpdateDlg(scope.row)">修改管理员</el-dropdown-item>
                                <el-dropdown-item @click.native="deleteOperator(scope.row)"
                                    v-if="scope.row.user_type_id == 3">删除管理员</el-dropdown-item><!--平台管理员不能删除-->
                                <div v-if="scope.row.user_type_id == 3">
                                    <hr />
                                    <el-dropdown-item
                                        @click.native="openAssignRoleDlg(scope.row)">分配角色</el-dropdown-item>
                                    <el-dropdown-item
                                        @click.native="openAssignProjectDlg(scope.row)">分配项目</el-dropdown-item>
                                    <hr />
                                    <el-dropdown-item @click.native="hResetPwd(scope.row)">重置密码</el-dropdown-item>
                                </div>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </template>
        </app-table>

        <el-dialog width="50%" v-drag-dialog :title="dialogData.editData.title" center
            :visible.sync="dialogData.editData.show" :modal-append-to-body="false" custom-class="editDataDialog"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form :model="dialogData.editData.data" :rules="dialogData.editData.rules" ref="editDataForm"
                label-width="85px" :size="controlSize">
                <el-form-item label="登录账户" prop="user_name">
                    <el-input v-model="dialogData.editData.data.user_name" auto-complete="off"
                        :disabled="this.dialogData.editData.operation == 'update'"></el-input>
                </el-form-item>
                <el-form-item label="账户昵称" prop="nickname">
                    <el-input v-model="dialogData.editData.data.nickname" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-if="dialogData.editData.operation != 'update'">
                    <el-input type="password" v-model="dialogData.editData.data.password"
                        auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="职工姓名" prop="name">
                    <el-input v-model="dialogData.editData.data.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="dialogData.editData.data.telephone" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div style="padding-top: 10px;text-align:right">
                <el-button type="success" @click="onSubmit">确定</el-button>
                <el-button type="warning" @click="hClose">取消</el-button>
            </div>
        </el-dialog>

        <!--为管理员分配角色-->
        <el-dialog width="45%" v-drag-dialog :title="roleData.title" center :visible.sync="roleData.show"
            :modal-append-to-body="false" custom-class="editDataDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <assign-role-dlg :id="roleData.id" @closeAssign="hCloseAssign" v-if="roleData.show" />
        </el-dialog>

        <!--为管理员分配项目-->
        <el-dialog width="45%" v-drag-dialog :title="projectData.title" center :visible.sync="projectData.show"
            :modal-append-to-body="false" custom-class="editDataDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <assign-project-dlg :id="projectData.id" @getDataProject="hGetDataProject"
                @closeAssignProject="hCloseAssignProject" v-if="projectData.show" />
        </el-dialog>

        <!--重置管理员密码-->
        <el-dialog width="45%" v-drag-dialog :title="newPwdDlg.title" center :visible.sync="newPwdDlg.show"
            :modal-append-to-body="false" custom-class="editDataDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <h2>这是重置后的密码：{{ newPwdDlg.new_pwd }}</h2>
        </el-dialog>
    </div>
</template>


<script>
import { getProjectPageList } from "@/api/project"
import { addOperator, updateOperator, deleteOperator, getOperatorPageList, resetOperatorPwd } from "@/api/user"
import AssignRoleDlg from "./component/assignroledlg.vue"
import AssignProjectDlg from "./component/assignprojectdlg.vue"

export default {
    name: 'operator',
    components: {
        AssignRoleDlg,
        AssignProjectDlg
    },
    data: function () {
        return {
            pageData: {
                id: 0,
                name: '',
                pid: ''
            },
            tableData: {
                listData: {
                    loading: false,
                    disabled: false,
                    totalCount: 0,
                    pageNum: 1,
                    pageSize: this.$store.getters.pageSize,
                    search: {
                        user_name: '',
                    },
                    columns: [
                        { key: 'name', name: '员工姓名', width: 150 },
                        { key: 'user_name', name: '登录账户', width: 150 },
                        { key: 'user_type_id', name: '管理员类型', width: 150 },
                        { key: 'nickname', name: '账户昵称', width: 150 },
                        { key: 'telephone', name: '联系电话', width: 150 },
                        { key: 'project_id', name: '管理项目' },
                    ],
                    formatter: {
                        'user_type_id': this.formatUserTypeId,
                        'project_id': this.formatProjectId
                    },
                    items: [],
                }
            },
            dialogData: {
                editData: {
                    operation: 'add',
                    title: '新增管理员资料',
                    show: false,
                    data: {
                        project_id: null,
                        id: 0,
                        user_type_id: 0,
                        user_name: '',
                        password: '',
                        nickname: '',
                        name: '',
                        telephone: ''
                    },
                    rules: {
                        project_id: [
                            { required: true, message: '请选择管理项目', trigger: 'blur' },
                        ],
                        user_name: [
                            { required: true, message: '请输入登录账户', trigger: 'blur' },
                        ],
                        nickname: [
                            { required: true, message: '请输入账户昵称', trigger: 'blur' },
                        ],
                        password: [
                            { required: true, message: '请输入登录密码', trigger: 'blur' },
                        ],
                        name: [
                            { required: true, message: '请输入职工姓名', trigger: 'blur' },
                        ],
                    }
                }
            },
            mainData: {
                item: {
                    dataList: [],//项目列表
                }
            },
            roleData: {
                id: 0,//员工ID
                title: '',
                show: false,
            },
            projectData: {//项目数据
                id: 0,//公司ID
                title: '为管理员分配项目',
                show: false,
            },
            newPwdDlg: {
                title: '新改密码',
                show: false,
                new_pwd: ''
            }
        }
    },
    watch: {
        updateTime(val, old) { //监听到改变后，重新初始化组件
            this.init()
        }
    },
    computed: {
        controlSize() {
            return this.$store.getters.controlSize
        }
    },
    beforeMount() {
    },
    mounted() {
        this.$nextTick(function () {
            this.init()
        })
    },
    methods: {
        init() {
            this.getProjectPageList()
        },
        getProjectPageList() {//获得项目资料
            let pageNum = this.tableData.listData.pageNum
            let pageSize = 1000
            let param = { page_num: pageNum, page_size: pageSize, order_by: "id desc" }

            //查询数据
            getProjectPageList(param).then((res) => {
                this.mainData.item.dataList = res.data.items
                this.getOperatorPageList()
            }).catch((err) => {
                this.$message({
                    message: err,
                    type: 'error',
                    duration: 2 * 1000
                })
            })
        },
        getOperatorPageList() {//获得项目资料
            let pageNum = this.tableData.listData.pageNum
            let pageSize = this.tableData.listData.pageSize
            let query = []

            if (this.tableData.listData.search.user_name.length > 0) {
                const userName = "%" + this.tableData.listData.search.user_name + "%"
                let item = { key: "user_name", data: userName, opt: "like" }
                query.push(item)
            }
            let param = { page_num: pageNum, page_size: pageSize, query: query, order_by: "user_type_id" }

            //查询数据
            this.tableData.listData.loading = true
            getOperatorPageList(param).then((res) => {
                this.tableData.listData.totalCount = res.data.total_count
                this.tableData.listData.items = res.data.items
                this.tableData.listData.loading = false
            }).catch((err) => {
                this.tableData.listData.loading = false
            })
        },
        handlePageSizeChange(val) { // 每页记录条数改变的事件
            //保存修改的PageSize
            this.$store.commit('app/setPageSize', val)

            //如果（每页记录条数改变后重新计算的总页数>=当前页），表示每页记录条数改变后，当前页不会改变，此处需要刷新table数据
            //如果（当前页*每页记录条数<=总记录条数），表示每页记录条数改变后，当前页不会改变，此处需要刷新table数据
            //如果（当前页*每页记录条数>总记录条数），表示每页记录条数改变后，当前页会重新计算并改变，handlePageNumChange会被调用，此处不需要刷新table数据
            var totalCount = this.tableData.listData.totalCount
            var pageNum = this.tableData.listData.pageNum
            var pageSize = this.tableData.listData.pageSize
            var pageCount = totalCount % pageSize === 0 ? totalCount / pageSize : Math.floor((totalCount / pageSize) + 1)
            if ((pageCount >= pageNum) || (pageNum * pageSize <= totalCount)) {
                this.getOperatorPageList()
            }
        },
        handlePageNumChange(val) { // 当前页改变的事件，需要在此事件中刷新table数据
            this.tableData.listData.pageNum = val
            this.getOperatorPageList()
        },
        formatProjectId(row) {
            let strText = '待分配管理项目'
            this.mainData.item.dataList.forEach(element => {
                if (row.user_type_id == 1) {
                    strText = "平台管理员，不管理具体项目"
                } else if (row.user_type_id == 2) {
                    strText = "系统管理员，不管理具体项目"
                } else {
                    if (row.project_id === element.id) {
                        strText = element.name
                    }
                }
            })
            return strText
        },
        formatUserTypeId(row) {
            let strText = ""
            if (row.user_type_id === 1) {
                strText = '平台管理员'
            } else if (row.user_type_id === 2) {
                strText = '系统管理员'
            } else if (row.user_type_id === 3) {
                strText = '项目管理员'
            }

            return strText
        },
        openAddDlg() {//打开新增窗口
            this.dialogData.editData.data = {}
            this.dialogData.editData.operation = 'add'
            this.dialogData.editData.title = '新增项目管理员资料'
            this.dialogData.editData.show = true
        },
        openUpdateDlg(item) {//打开修改窗口
            this.dialogData.editData.data.id = parseInt(item.id)
            this.dialogData.editData.data.project_id = item.project_id
            this.dialogData.editData.data.user_type_id = parseInt(item.user_type_id)
            this.dialogData.editData.data.user_name = item.user_name
            this.dialogData.editData.data.nickname = item.nickname
            this.dialogData.editData.data.name = item.name
            this.dialogData.editData.data.telephone = item.telephone

            this.dialogData.editData.operation = 'update'
            this.dialogData.editData.title = '修改项目管理员资料'
            this.dialogData.editData.show = true
        },
        hClose() {//关闭对话框
            this.dialogData.editData.show = false
        },
        onSubmit() { //对话框确定按钮响应函数
            this.$refs.editDataForm.validate((valid) => {
                if (valid) {
                    if ('add' == this.dialogData.editData.operation) {
                        this.addOperator()
                    } else {
                        this.updateOperator()
                    }
                }
            })
        },
        addOperator() {//新增操作员
            if (this.dialogData.editData.data.project_id > 0) {
                this.$message.success('请选择项目编号', '提示')
                return
            }

            const data = this.dialogData.editData.data
            addOperator(data).then((res) => {
                this.dialogData.editData.data.id = res.data
                this.$message.success('新增成功', '提示')
                this.getOperatorPageList()
            }).catch((err) => {
                this.$message({ message: err, type: 'error' })
            })
        },
        updateOperator() {//修改操作员
            let data = {}
            data.id = parseInt(this.dialogData.editData.data.id)
            data.project_id = parseInt(this.dialogData.editData.data.project_id)
            data.nickname = this.dialogData.editData.data.nickname
            data.name = this.dialogData.editData.data.name
            data.telephone = this.dialogData.editData.data.telephone

            updateOperator(data).then((res) => {
                this.$message.success('修改成功', '提示')
                this.getOperatorPageList()
                this.dialogData.editData.show = false
            }).catch((err) => {
                this.$message({ message: err, type: 'error' })
            })
        },
        async deleteOperator(item) {//删除操作员
            let paramData = {}

            const res = await this.$confirm("确定要删除吗", "提示", { type: "warning" }).catch(err => err)
            if (res != 'confirm') {
                return
            }

            paramData["id"] = parseInt(item.id)
            deleteOperator(paramData).then((res) => {
                this.$message.success('删除成功', '提示')
                this.getOperatorPageList()
            }).catch((err) => {
                this.$message({ message: err, type: 'error' })
            })
        },
        //打开分配角色窗口
        openAssignRoleDlg(item) {
            this.roleData.id = parseInt(item.id)
            this.roleData.title = "为【" + item.name + "】分配角色"
            this.roleData.show = true
        },
        hCloseAssign() {
            this.roleData.show = false
        },
        //打开分配项目窗口
        openAssignProjectDlg(item) {
            this.projectData.id = parseInt(item.id)//操作员ID
            this.projectData.title = "为【" + item.user_name + "-" + item.name + "】分配项目"
            this.projectData.show = true
        },
        hCloseAssignProject() {
            this.projectData.show = false
        },
        hGetDataProject() {
            this.getOperatorPageList()
        },
        async hResetPwd() {//重置密码
            const res = await this.$confirm("确定要重置密码吗", "提示", {
                type: "warning",
                closeOnPressEscape: false,
                closeOnClickModal: false
            }).catch(err => err)
            if (res != 'confirm') {
                return
            }

            //重置密码
            resetOperatorPwd().then((res) => {
                this.$alert(res.data.password, '新改密码', {
                    confirmButtonText: '确定',
                    closeOnPressEscape: false,
                    closeOnClickModal: false
                })
            }).catch((err) => {
                this.$message({ message: err, type: 'error' })
            })
        }
    }
}

</script>