<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
                <el-col :span="3">
                    <el-form-item>
                        <el-select v-model="filters.companyId" clearable filterable placeholder="请选择公司">
                            <el-option v-for="item in allCompanies" :key="item.id" :label="item.companyName" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="3">
                    <el-form-item>
                        <el-select v-model="filters.flag" placeholder="请选择查询条件">
                            <el-option label="姓名" value="0"></el-option>
                            <el-option label="手机号" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-form-item>
                    <el-input v-model="filters.keyName" clearable placeholder="请输入姓名或手机号进行搜索" style="width:250px;"></el-input>
                </el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getUsers">查询</el-button>
				</el-form-item>
				<el-form-item style="float:right;" v-if="user.subordinateType == 0 || user.isManager == 1">
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="list" highlight-current-row :height="tableHeight" v-loading="listLoading" style="width: 100%;">
			<el-table-column type="index" width="60"></el-table-column>
			<el-table-column prop="username" label="姓名" width="120" sortable></el-table-column>
			<el-table-column prop="account" label="手机号" width="180" sortable></el-table-column>
			<!-- <el-table-column prop="mobile" label="联系方式" width="150" sortable></el-table-column> -->
            <el-table-column prop="projects" label="参与项目" sortable>
                <template slot-scope="scope">
                    <span class="info" v-for="(item, index) in scope.row.projects">
                        {{item.projectName}}
                        <span v-if="scope.row.projects != null && index != scope.row.projects.length-1">、</span>
                    </span>
                </template>
			</el-table-column>
            <el-table-column prop="roleName" label="备注" width="180" sortable></el-table-column>
            <el-table-column prop="teamName" label="类型" width="120" align="center" sortable></el-table-column>
			<el-table-column prop="companyName" label="所属公司" sortable></el-table-column>
			<el-table-column label="操作" align="left" width="230">
				<template slot-scope="scope" v-if="user.id == scope.row.parentId || user.isManager == 1 || (user.parentId == 1 && user.subordinateType == 0)">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                    <el-button type="primary" size="small" @click="invite(scope.$index, scope.row)" v-if="user.id != 1 && scope.row.projects != null && scope.row.projects.length == 1">邀请</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[20 , 50 , 80 , 100]"
                :page-size="20"
                layout="total, sizes, prev, pager, next"
                :total="total"
                style="float:right;">
            </el-pagination>
		</el-col>

        <!--新增界面-->
		<el-dialog title="新增人员" v-if="addFormVisible" :visible.sync="addFormVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-form :model="addForm" label-width="100px" :rules="formRules" ref="addForm" :inline="true" class="demo-form-inline">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="addForm.username" autocomplete="off" placeholder="请输入姓名"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="account">
					<el-input v-model="addForm.account" autocomplete="off" placeholder="请输入手机号（登录账号）"></el-input>
				</el-form-item>
                <el-form-item v-if="!(user.parentId == 1 && user.subordinateType == 0)" label="参与项目" prop="projectIds">
					<el-select v-model="addForm.projectIds" @change="choseProject" clearable filterable placeholder="请选择参与项目" style="width:202px">
                        <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id">
                        </el-option>
                    </el-select>
				</el-form-item>
                <el-form-item label="公司" prop="companyId">
					<el-select v-model="addForm.companyId" clearable filterable placeholder="请选择所属公司" style="width:202px">
                        <el-option v-for="item in company" :key="item.id" :label="item.companyName" :value="item.id">
                        </el-option>
                    </el-select>
				</el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addForm.roleName" autocomplete="off" placeholder="请输入备注"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
                <span style="color:#f00;float:left;margin-left:60px;">初始密码：000000</span>
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--编辑界面-->
		<el-dialog title="编辑人员" v-if="editFormVisible" :visible.sync="editFormVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-form :model="editForm" label-width="80px" :rules="formRules" ref="editForm" :inline="true" class="demo-form-inline">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="editForm.username" autocomplete="off" placeholder="请输入姓名"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="account">
					<el-input v-model="editForm.account" disabled autocomplete="off" placeholder="请输入手机号（登录账号）"></el-input>
				</el-form-item>
                <el-form-item label="公司" prop="companyId">
                    <el-input v-model="editForm.companyId" disabled autocomplete="off" placeholder="请选择所属公司"></el-input>
				</el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editForm.roleName" autocomplete="off" placeholder="请输入备注"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
                 <span style="color:#f00;float:left;margin-left:60px;">初始密码：000000</span>
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

        <!--邀请界面-->
		<el-dialog title="邀请" v-if="inviteVisible" :visible.sync="inviteVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-input placeholder="请复制邀请链接" v-model="inviteLink" class="input-with-select">
                <el-button slot="append" v-clipboard:copy="inviteLink" v-clipboard:success="copyLink" v-clipboard:error="onError" type="primary" icon="el-icon-share">复制链接</el-button>
            </el-input>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'

	export default {
		data() {
            var checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入联系方式'));
                } else {
                    const reg = /^1[0-9]\d{9}$/
                    if (reg.test(value)) {
                        callback();
                    } else {
                        return callback(new Error('请输入正确的联系方式'));
                    }
                }
            };
			return {
				filters: {
                    keyName: '',
                    roleName: '',
                    flag: '姓名',
                    companyId: ''
                },
                
                user: JSON.parse(sessionStorage.getItem('user')),
                company: [],
                projects: [],
                //搜索用 涉及到的所有公司
                allCompanies: [],

				list: [],
				total: 0,
                page: 1,
                size: 20,
                listLoading: false,
                tableHeight: 0,

                formRules: {
                    username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    account: [
                        { required: true, validator: checkPhone, trigger: 'blur'}
                    ],
                    teamName: [
						{ required: true, message: '请选择人员类型', trigger: ["blur",'change'] }
                    ],
                    projectIds: [
						{ required: true, message: '请选择参与项目', trigger: ["blur",'change'] }
					],
                    companyId: [
						{ required: true, message: '请选择所属公司', trigger: ["blur",'change'] }
					]
                },

                //新增界面是否显示
                addFormVisible: false,
				addLoading: false,
				//新增界面数据
				addForm: {
					username: '',
                    account: '',
                    projectIds: '',
                    companyId: '',
                    roleName: '',
                    flag: 0
				},

                //编辑界面是否显示
				editFormVisible: false,
				editLoading: false,
				//编辑界面数据
				editForm: {
					id: 0,
					username: '',
                    account: '',
                    companyId: '',
                    roleName: '',
                    flag: 1
                },
                
                //邀请
                inviteVisible: false,
                inviteLink: ''
			}
		},
		methods: {
            //获取基础数据
            getMsg(){
                if(this.user.parentId == 1 && this.user.subordinateType == 0) {
                    this.company = [];
                    this.allCompanies = [];
                    this.http.post(this.port.base.getCompanyList, {
                        id: this.user.id,
                        parentId: this.user.parentId
                    }, res => {
                        if (res.code == "ok") {
                            this.company = res.data;
                            this.allCompanies = res.data;
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    })
                } else if(this.user.parentId > 1 && this.user.isManager == 1) {
                    this.http.post(this.port.project.projectByUser, {}, 
                    res => {
                        if (res.code == "ok") {
                            this.projects = res.data;
                            //再获取一下公司列表
                            this.getAllCompanies();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    });
                }
            },  

            //新版获取所有公司
            getAllCompanies(){
                this.allCompanies = [];
                this.http.post(this.port.base.getInfo, {}, res => {
                    if (res.code == "ok") {
                        this.allCompanies = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                });
            },

            //分页
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
            },

            handleSizeChange(val) {
                this.size = val;
				this.getUsers();
            },

			//获取用户列表
			getUsers() {
				this.listLoading = true;
                this.http.post(this.port.project.userList, {
                    keyName: this.filters.keyName,
                    currentPage: this.page,
                    pageSize: this.size,
                    companyId: this.filters.companyId==''?-1:this.filters.companyId,
                    flag: this.filters.flag=='姓名'?0:this.filters.flag
                }, res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        this.list = res.data.list;
                        this.total = res.data.total;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },
            
            //显示新增界面
			handleAdd() {
                this.addFormVisible = true;
				this.addForm = {
                    parentId: this.user.id,
					username: '',
                    account: '',
                    mobile: '',
                    projectIds: '',
					companyId: '',
                    roleName: '',
                    flag: 0
				};
            },

            //新增
			addSubmit() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.addLoading = true;
                        this.http.post(this.port.project.addUser, this.addForm , res => {
                            this.addLoading = false;
                            if (res.code == "ok") {
                                this.addFormVisible = false;
                                this.$message({
                                    message: '创建成功',
                                    type: 'success'
                                });
                                this.getUsers();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            this.addLoading = false;
                            this.addFormVisible = false;
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
					}
				});
			},

			//删除
			handleDel(index, row) {
                this.$confirm('确认删除该人员吗?', '提示', {
					type: 'warning'
				}).then(() => {
                    this.http.post(this.port.project.delUser, {
                        id: row.id
                    }, res => {
                        if (res.code == "ok") {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getUsers();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    })
				});
            },
            
			//显示编辑界面
			handleEdit(index, row) {
                this.editFormVisible = true;
				this.editForm = {
                    id: row.id,
                    parentId: this.user.id,
					username: row.username,
                    account: row.account,
					companyId: row.companyName,
                    roleName: row.roleName,
                    flag: 1
                };
            },
            
			//编辑
			editSubmit() {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
                        this.editLoading = true;
                        this.http.post(this.port.project.addUser, {
                            id: this.editForm.id,
                            parentId: this.editForm.parentId,
                            username: this.editForm.username,
                            roleName: this.editForm.roleName,
                            flag: 1
                        } , res => {
                            this.editLoading = false;
                            if (res.code == "ok") {
                                this.editFormVisible = false;
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.getUsers();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            this.editLoading = false;
                            this.editFormVisible = false;
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
					}
				});
            },
            
            //修改
            choseProject() {
                if(this.addForm.projectIds == ""){
                    this.company = [];
                    this.addForm.companyId = null;
                }else{
                    this.http.post(this.port.base.getProduceCompany, {
                        projectId: this.addForm.projectIds
                    }, res => {
                        if (res.code == "ok") {
                            this.company = res.data;
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    })
                }
            },

            //邀请
            invite(index, row) {
                this.http.post(this.port.project.inviteUser, {
                    inviteeId: row.id,
                    projectId: row.projects[0].id,
                    operatorId: this.user.id
                } , res => {
                    if (res.code == "ok") {
                        this.inviteVisible = true;
                        this.inviteLink = res.data.addressUrl;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //复制链接
            copyLink() {
                //this.inviteVisible = false;
                this.$message({
                    message: "复制成功！",
                    type: 'success'
                });
            },

            onError(e) {
                //this.inviteVisible = false;
                this.$message({
                    message: "复制失败！",
                    type: 'error'
                });
            }
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 210;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 210;    
            };
        },
		mounted() {
            this.getMsg();
			this.getUsers();
        }
	}
</script>

<style scoped>
    .el-input-group__append button.el-button {
        background-color: #409EFF;
        border-color: #409EFF;
        color: #fff;
    }
</style>