<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="$t('basic.chooseComp')">
                            <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="$t('base.choose')">
                            <el-option :label="$t('project.name')" value="0"></el-option>
                            <el-option :label="$t('project.mobile')" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-form-item>
                    <el-input v-model="filters.keyName" clearable :placeholder="$t('msg.nameSearch')" style="width:250px;"></el-input>
                </el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getUsers">{{$t('base.query')}}</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">{{$t('base.add')}}</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="$t('project.name')" width="120" sortable>
                <template slot-scope="scope">
                    <!-- <a :href="'/staffDetail?id=' + scope.row.id">{{scope.row.username}}</a> -->
                    <el-link :underline="false" type="primary" @click="toDetail(scope.row.id)">{{scope.row.username}}</el-link>
                </template>
            </el-table-column>
			<el-table-column prop="account" :label="$t('project.mobile')" width="180" sortable></el-table-column>
			<!-- <el-table-column prop="mobile" label="联系方式" width="150" sortable></el-table-column> -->
            <el-table-column prop="projects" :label="$t('project.partake')" width="300">
                <template slot-scope="scope">
                    <span class="info" v-for="(item, index) in scope.row.projects" :key="item.id">
                        {{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="$t('project.remark')" width="180" sortable></el-table-column>
            <el-table-column prop="teamName" :label="$t('project.type')" width="120" align="center" sortable></el-table-column>
			<el-table-column prop="companyName" :label="$t('project.company')" width="300" sortable></el-table-column>
			<el-table-column prop="corpUserId" label="绑定情况" width="300" sortable>
                <template slot-scope="scope" >
                    <span v-if="scope.row.corpUserId != null" style="color:green;">企业微信已绑定</span>
                    <span v-if="scope.row.openid != null" style="margin-left:10px;color:green;">个人微信已绑定</span>
                    <span v-if="scope.row.openid == null && scope.corpUserId == null">未绑定</span>
				</template>
            </el-table-column>
			<el-table-column :label="$t('base.operate')" 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)">{{$t('base.edit')}}</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">{{$t('el.upload.delete')}}</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">{{$t('base.invite')}}</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="$t('project.addPeo')" 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="$t('project.name')" prop="username">
					<el-input v-model="addForm.username" autocomplete="off" :placeholder="$t('project.inputName')" style="width:202px"></el-input>
				</el-form-item>
				<el-form-item :label="$t('project.mobile')" prop="account">
					<el-input v-model="addForm.account" autocomplete="off" :placeholder="$t('project.inputMobile')" style="width:202px"></el-input>
				</el-form-item>
                <el-form-item v-if="!(user.parentId == 1 && user.subordinateType == 0)" :label="$t('project.partake')" prop="projectIds">
					<el-select v-model="addForm.projectIds" @change="choseProject" clearable filterable :placeholder="$t('project.inputPartake')" 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="$t('project.company')" prop="companyId">
					<el-select v-model="addForm.companyId" clearable filterable :placeholder="$t('project.inputCompany')" style="width:202px">
                        <el-option v-for="item in allCompanies" :key="item.id" :label="item.companyName" :value="item.id">
                        </el-option>
                    </el-select>
				</el-form-item>
                <el-form-item :label="$t('project.remark')">
                    <el-input v-model="addForm.roleName" autocomplete="off" :placeholder="$t('project.inputRemark')" style="width:202px"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
                <span style="color:#f00;float:left;margin-left:60px;">{{$t('project.initial')}}：000000</span>
				<el-button @click.native="addFormVisible = false">{{$t('el.messagebox.cancel')}}</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">{{$t('el.messagebox.confirm')}}</el-button>
			</div>
		</el-dialog>

		<!--编辑界面-->
		<el-dialog :title="$t('project.editPeo')" v-if="editFormVisible" :visible.sync="editFormVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-form :model="editForm" label-width="100px" :rules="formRules" ref="editForm" :inline="true" class="demo-form-inline">
				<el-form-item :label="$t('project.name')" prop="username">
					<el-input v-model="editForm.username" autocomplete="off" :placeholder="$t('project.inputName')"></el-input>
				</el-form-item>
				<el-form-item :label="$t('project.mobile')" prop="account">
					<el-input v-model="editForm.account" autocomplete="off" :placeholder="$t('project.inputPartake')"></el-input>
				</el-form-item>
                <el-form-item :label="$t('project.company')" prop="companyId">
                    <!-- <el-input v-model="editForm.companyId" autocomplete="off" :placeholder="$t('project.inputCompany')"></el-input> -->
                    <el-select v-model="editForm.companyId" clearable filterable :placeholder="$t('project.inputCompany')" style="width:202px">
                        <el-option v-for="item in allCompanies" :key="item.id" :label="item.companyName" :value="item.id">
                        </el-option>
                    </el-select>

				</el-form-item>
                <el-form-item :label="$t('project.remark')">
                    <el-input v-model="editForm.roleName" autocomplete="off" :placeholder="$t('project.inputRemark')"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
                 <span style="color:#f00;float:left;margin-left:60px;">{{$t('project.initial')}}：000000</span>
				<el-button @click.native="editFormVisible = false">{{$t('el.messagebox.cancel')}}</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{$t('el.messagebox.confirm')}}</el-button>
			</div>
		</el-dialog>

        <!--邀请界面-->
		<el-dialog :title="$t('base.invite')" v-if="inviteVisible" :visible.sync="inviteVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-input :placeholder="$t('project.copyInv')" 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">{{$t('project.copy')}}</el-button>
            </el-input>
		</el-dialog>
	</section>
</template>

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

	export default {
		data() {
            const checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error(this.$t('project.inputMobile')));
                } else {
                    const reg = /^1[0-9]\d{9}$/
                    if (reg.test(value)) {
                        callback();
                    } else {
                        return callback(new Error(this.$t('project.inputTrueMobile')));
                    }
                }
            };
            const msg = (rule, value, callback) => {
                if (!value) {
                    switch(rule.field) {
                        case "username":
                            return callback(new Error(this.$t('project.inputName')));
                            break;
                        case "projectIds":
                            return callback(new Error(this.$t('project.inputPartake')));
                            break;
                        case "companyId":
                            return callback(new Error(this.$t('project.inputCompany')));
                            break;
                        default:
                            callback();
                    } 
                } else {
                    callback();
                }
            };
			return {
				filters: {
                    keyName: '',
                    roleName: '',
                    flag: this.$t('project.name'),
                    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, validator: msg, trigger: 'blur' }
                    ],
                    account: [
                        { required: true, validator: checkPhone, trigger: 'blur'}
                    ],
                    projectIds: [
						{ required: true, validator: msg, trigger: ["blur",'change'] }
					],
                    companyId: [
						{ required: true, validator: msg, 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: {
            toDetail(id) {
                this.$router.push('staffDetail?id='+id);
            },
            //获取基础数据
            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'
                        });
                    });
                } else {
                    this.getAllCompanies();
                }
            },  

            //新版获取所有公司
            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,
                    pageNum: this.page,
                    pageSize: this.size,
                    companyId: this.filters.companyId==''?-1:this.filters.companyId,
                    flag: this.filters.flag==this.$t('project.name')?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: this.$t('prompt.success2'),
                                    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(this.$t('project.delPeo'), this.$t('el.messagebox.title'), {
					confirmButtonText: this.$t('el.messagebox.confirm'),
                    cancelButtonText: this.$t('el.messagebox.cancel'),
                    type: 'warning'
				}).then(() => {
                    this.http.post(this.port.project.delUser, {
                        id: row.id
                    }, res => {
                        if (res.code == "ok") {
                            this.$message({
                                message: this.$t("prompt.success3"),
                                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.companyId,
                    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,
                            companyId: this.editForm.companyId,
                            account: this.editForm.account,
                            flag: 1
                        } , res => {
                            this.editLoading = false;
                            if (res.code == "ok") {
                                this.editFormVisible = false;
                                this.$message({
                                    message: this.$t("prompt.success"),
                                    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: this.$t('prompt.success6'),
                    type: 'success'
                });
            },

            onError(e) {
                //this.inviteVisible = false;
                this.$message({
                    message: this.$t('prompt.fail'),
                    type: 'error'
                });
            }
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 210;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 210;    
            };
        },
		mounted() {
            var staffName = this.$route.query.name;
            if (staffName != null) {
                this.filters.keyName = staffName;
            }
            this.getMsg();
			this.getUsers();
        }
	}
</script>

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