<template>
    <div>
        <van-nav-bar title="项目管理" left-text="返回" @click-left="back" :right-text="canEdit?新增项目:''" @click-right="openDialog(-1)" fixed left-arrow/>
        
        <div class="login_form">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                <van-list v-model="loading" :finished="finished" finished-text="没有更多了" :error.sync="error" error-text="请求失败，点击重新加载" @load="getProject">
                    <van-swipe-cell v-for="(item,index) in list" :key="index">
                        <van-cell :border="false" :title="item.projectName" :value="item.projectCode"/>
                        <template slot="right" v-if="canEdit">
                            <van-button square type="info" text="编辑" @click="openDialog(index)"/>
                            <van-button square type="danger" text="删除" @click="delPro(index)"/>
                        </template>
                    </van-swipe-cell>
                </van-list>
            </van-pull-refresh>

            <van-dialog v-model="show" :title="title" show-cancel-button :beforeClose="chargeBtn">
                <van-form style="margin: 0.4rem 0;">
                    <van-field v-model="form.projectCode" name="项目编号" label="项目编号" placeholder="请填写项目编号" />
                    <van-field v-model="form.projectName" name="项目名称" label="项目名称" placeholder="请填写项目名称" :rules="[{ required: true, message: '请填写项目名称' }]"/>
                    <van-field readonly clickable name="userNames" v-model="form.userNames"  label="参与人" 
                    placeholder="请选择参与人" @click="clickPicker()" />
                    <van-field readonly clickable  v-model="form.inchargerName"  label="负责人" 
                    placeholder="请选择负责人" @click="showPickerIncharger = true" />
                </van-form>
            </van-dialog>
            <van-popup v-model="showPickerUser" position="bottom">
                <van-search v-model="userName" placeholder="输入员工姓名搜索" @search="onSearch"></van-search>
                <div style="minHeight:300px;">
                <van-checkbox class="userCheckbox" v-for="(item) in userList" :key="item.id" v-model="item.isChecked" >{{item.name}}</van-checkbox>
                <van-button style="width:100%;" @click="refreshParticipate();showPickerUser=false">确定</van-button>
                </div>
            </van-popup>
            <van-popup v-model="showPickerIncharger" position="bottom">
                <van-picker show-toolbar :columns="inchargerUserList" value-key="name" @confirm="choseIncharger" @cancel="showPickerIncharger = false" />
            </van-popup>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                canEdit:false,
                user: JSON.parse(localStorage.userInfo),
                showPickerUser: false,
                showPickerIncharger: false,
                userName:null,
                total: 0,
                page: 1,
                size: 1000,
                list: [],
                loading: false,
                finished: false,
                error: false,
                refreshing: false,
                allUserList:[],
                userList:[],
                inchargerUserList:[],
                show: false,
                title: "修改项目",
                form: {
                    id: null,
                    projectName: "",
                }
            };
        },
        created() {
        },
        methods: {
            choseIncharger(value, index) {
                this.showPickerIncharger = false;
                this.form.inchargerName = value.name;
                this.form.inchargerId = value.id;
            },
            onSearch(val) {
                console.log(val);
                this.userList = [];
                this.allUserList.forEach(u=>{if (u.name.startsWith(val)) {
                    this.userList.push(u);
                }})
                
            },
            //刷新参与人
            refreshParticipate() {
                this.form.userNames = '';
                var that = this;
                that.inchargerUserList = [];
                that.form.userId = [];
                this.userList.filter(u=>u.isChecked).forEach(u=>{
                    that.form.userNames+=(u.name+',');
                    that.form.userId.push(u.id);
                    that.inchargerUserList.push(u);
                });
                if (this.form.userNames.length > 0) {
                    this.form.userNames = this.form.userNames.substring(0, this.form.userNames.length-1);
                }
            },
            onChange() {
                console.log('===');
            },
            choseUsers() {

            },
            clickPicker() {
                this.showPickerUser = true;
            },
            // 返回
            back() {
                history.back();
            },
            //获取用户列表
            getUsers() {
                this.$axios.post("/user/getEmployeeList", {
                    departmentId: -1,
                    pageIndex: 1,
                    pageSize: 99999
                })
                .then(res => {
                    if(res.code == "ok") {
                        this.loading = false;
                        this.userList = res.data.records;
                        this.allUserList = res.data.records;
                    } else {
                        this.$toast.fail('获取失败');
                    }
                }).catch(err=> {toast.clear();});
            },

            // 获取项目
            getProject() {
                if (this.refreshing) {
                    this.list = [];
                    this.refreshing = false;
                }
                if(this.total == this.list.length && this.list.length != 0) {
                    this.loading = false;
                    this.finished = true;
                    return false;
                }
                this.$axios.post("/project/getProjectPage", {
                    pageIndex: this.page,
                    pageSize: this.size,
                })
                .then(res => {
                    if(res.code == "ok") {
                        this.loading = false;
                        if (this.list.length == 0) {
                            this.finished = true;
                        }
                        
                        for(var i in res.data.records) {
                            this.list.push(res.data.records[i])
                        }
                        this.total = res.data.total;
                        this.page++;
                    } else {
                        this.$toast.fail('获取失败:'+res.msg);
                    }
                }).catch(err=> {toast.clear();});
            },

            onRefresh() {
                this.finished = false;
                this.loading = true;
                this.page = 1;
                this.getProject();
            },

            // 新增、编辑项目
            openDialog(i) {
                if(i == -1) {
                    this.title = "新增项目";
                    this.form = {
                        id: null,
                        projectName: "",
                        projectCode:null,
                        inchargerName:null,
                        inchargerId:null,
                        userId:null,
                        userNames:null
                    }
                    // this.userList.forEach(u=>u.isChecked=false);
                    // this.refreshParticipate();
                } else {
                    this.title = "修改项目";
                    this.form = {
                        id: this.list[i].id,
                        projectName: this.list[i].projectName,
                        projectCode: this.list[i].projectCode,
                        inchargerId: this.list[i].inchargerId,
                        inchargerName: this.list[i].inchargerName,
                    }
                    var part = this.list[i].participator;
                    
                    if (part.length>0) {
                        for (var j in part) {
                            this.userList.filter(u=>u.id == part[j].id)[0].isChecked = true;
                        }
                        this.refreshParticipate();
                    }
                }
                this.show = true;
            },

            chargeBtn(action, done) {
                if (action === 'confirm') {
                    this.show = false;
                    const toast = this.$toast.loading({
                        forbidClick: true,
                        duration: 0
                    });
                    let formData = new FormData();
                    formData.append("name", this.form.projectName);
                    formData.append("code", this.form.projectCode);
                    formData.append("inchargerId", this.form.inchargerId);
                    for (var j in this.form.userId) {
                        formData.append("userId", this.form.userId[j]);
                    }
                    
                    let form = {
                        name: this.form.projectName,
                        code:this.form.projectCode,
                        inchargerId: this.form.inchargerId,
                        userId:this.form.userId
                    }
                    if(this.form.id != null) {
                        // form.id = this.form.id;
                        formData.append("id", this.form.id);
                    }
                    const config = {
                        headers: {
                        'Content-Type': 'multipart/form-data'
                        }
                    }    
                    this.$axios.post("/project/editProject", formData, config)
                    .then(res => {
                        if(res.code == "ok") {
                            toast.clear();
                            this.$toast.success(this.form.id==null?'新增成功':'修改成功');
                            this.list = [];
                            this.page = 1;
                            this.getProject();
                        } else {
                            toast.clear();
                            this.$toast.fail(this.form.id==null?'新增失败':'修改失败');
                        }
                    }).catch(err=> {toast.clear();});
                } else {
                    this.show = false;
                }
                done();
            },

            // 删除项目
            delPro(i) {
                this.$dialog.confirm({
                    title: '删除项目',
                    message: '确定要项目'+this.list[i].projectName+'吗?'
                }).then(() => {
                    const toast = this.$toast.loading({
                        forbidClick: true,
                        duration: 0
                    });
                    this.$axios.post("/project/deleteProject", {id: this.list[i].id})
                    .then(res => {
                        if(res.code == "ok") {
                            toast.clear();
                            this.$toast.success('删除成功');
                            this.list = [];
                            this.page = 1;
                            this.getProject();
                        } else {
                            toast.clear();
                            this.$toast.fail(res.msg);
                        }
                    }).catch(err=> {toast.clear();});
                }).catch(() => {});
            },

        },

        mounted() {
            this.getUsers();
            this.canEdit = this.user.role==1||this.user.role==2||this.user.role==5
        }
    };
</script>

<style lang="less" scoped>
    .login_form {
        margin-top: 46px;
    }

    .one_report {
        margin-bottom: 15px;
    }

    .form_text {
        margin: 15px 0 30px;
        padding: 0 12px;
    }
    
    .form_btn {
        text-align: right;
    }

    .form_btn button {
        margin-left: 10px;
    }

    .one_report_data {
        margin-bottom: 20px;
        padding: 0 22px;
        div {
            line-height: 30px;
        }
    }
    .userCheckbox {
        padding: 10px;;
    }
</style>
<style lang="less">
    .van-nav-bar .van-icon , .van-nav-bar__text {
        color: #20a0ff;
    }
</style>
