// nova-werun/pages/my/my-profile/index.js
const Parse = getApp().Parse;
const company = getApp().globalData.company;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        //屏幕高度
        statusBarHeight: 0, // 状态栏高度
        screenHeight: 0, // 屏幕高度
        customHeight: 0, // 自定义导航栏高度（如小程序右上角胶囊按钮）
        bottomNavHeight: 0, // 底部导航栏高度
        contentHeight: 0, // 可用内容高度
        contentpadding: 0, //顶部padding高度
        User1List: [],
        actions: [{
                name: '男',
            },
            {
                name: '女',
            },
        ],
        avatar: null,
        sex: '男',
        nickname: null,
        height: null,
        idnumber:null,//身份证号码
        //  选择部门
        // mainActiveIndex: 0,
        // activeId: null,
        // items: [],
        Departmentlist:[],
        departs:['1','2','3'],
        //显示遮罩层
        show: false,
        selectname: '', //部门名字
        departname: '', //工会名字
        selectobjectid: '',
        upiobjectid: '',
        // 图片
        fileList: [],
        uptokenURL: '',
        domain: '',
        uploadURL: '',
        title: '',

        //
        name: '',
        phone: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        // 计算
        const systemInfo = wx.getSystemInfoSync();
        const statusBarHeight = systemInfo.statusBarHeight || 0;
        const screenHeight = systemInfo.screenHeight || 0;
        const custom = wx.getMenuButtonBoundingClientRect();
        const customHeight = custom.height + 10 + 2 || 0;
        const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;

        const contentpadding = (statusBarHeight + customHeight) * 750 / systemInfo.windowWidth;
        const contentHeight = (screenHeight - bottomNavHeight - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
        this.setData({
            statusBarHeight,
            screenHeight,
            customHeight,
            bottomNavHeight,
            contentHeight,
            contentpadding
        });
        this.setData({
            title: options.type
        })
       await this.getname()
       await this.getdep()
        // this.getDepartment()
        this.getwritedep()
        this.getUptoken()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    //获取身高
    getHeight(e) {
        let height = e.detail.value;
        // 身高范围在 50 到 250 之间的正则表达式，允许浮点数
        let a = /^(?:[5-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|250)(\.\d)?$/;
        if (!height.match(a)) {
            wx.showToast({
                icon: "none",
                title: "请填写正确的身高格式",
            });
            return;
        } else {
            this.setData({
                height: height
            });
            console.log(this.data.height);
        }
    },
    //点击清空
    clearHeight() {
        this.setData({
            height: null
        })
        console.log('清空', this.data.height);
    },
    //获取头像名称
    async getname() {
        const currentUser = Parse.User.current();
        let Userquery = new Parse.Query('_User');
        Userquery.equalTo('company', company);
        Userquery.equalTo('objectId', currentUser.id);
        Userquery.notEqualTo('isDeleted', true)
        let P2 = await Userquery.find();
        let User1List = P2.map(item => item.toJSON());
        this.setData({
            User1List
        })
        this.setData({
            avatar: User1List[0].avatar || 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241120/95uip6030022742.png?imageView2/1/w/200/h/200',
            nickname: User1List[0].nickname || '微信用户',
            sex: User1List[0].sex || '男',

        })
        if (User1List[0].diyform) {
            this.setData({
                height: User1List[0].diyform.height
            })
        }
        console.log(this.data.User1List);
    },
    //获取填写部门信息
    async getwritedep() {
        let Userquery = new Parse.Query('Department');
        Userquery.equalTo('company', company); 
        Userquery.equalTo('isEnabled', true);
        // Userquery.equalTo('type', 'center');
        Userquery.notEqualTo('isDeleted', true);
        // Userquery.include('parent');

        let P2 = await Userquery.find();
        let Departmentlist = P2.map(item => item.toJSON());
        let departs=[]
        Departmentlist.forEach((item)=>{
            departs.push(item.name)
        })
        this.setData({
            departs,
            Departmentlist,
        })
        console.log('departs',this.data.Departmentlist);
    },
    //获取部门
    async getdep() {
        const currentUser = Parse.User.current();
        let Userquery = new Parse.Query('Profile');
        Userquery.equalTo('company', company);
        Userquery.equalTo('user', currentUser.id);
        // Userquery.equalTo('isCheck', true);
        Userquery.notEqualTo('isDeleted', true)
        Userquery.include('center');
        Userquery.include('department');
        let P2 = await Userquery.find();
        let dep = P2.map(item => item.toJSON());
        console.log('getdep', dep);
        if (dep.length!=0) {
            if (dep[0].isCheck == true) {
                this.setData({
                    name: dep[0].name,
                    phone: dep[0].mobile,
                    // departname: dep[0].department.name,//工会
                    selectname: dep[0].center.name,//部门
                    selectobjectid: dep[0].center.objectId,//部门
                    // upiobjectid: dep[0].department.objectId//工会
                })
            } else {
                this.setData({
                    name: dep[0].name,
                    phone: dep[0].mobile,
                    // departname: dep[0].department.name,
                    selectname: dep[0].center.name,
                    selectobjectid: dep[0].center.objectId,
                    // upiobjectid: dep[0].department.objectId
                })
                wx.showToast({
                    title: '您之前提交信息在审核当中',
                    icon: 'none',
                    duration: 2000
                })
            }
        }else{
            this.setData({
                phone:this.data.User1List[0].mobile
            })
        }
       
    },
    onSelect(event) {
        let {
            name
        } = event.detail
        this.setData({
            sex: name,
            show2: false
        })
        console.log(this.data.sex);
    },
    showSelect() {
        this.setData({
            show2: true
        })
    },
    //修改昵称
    changenickname(e) {
        this.setData({
            nickname: e.detail
        })
        console.log(this.data.nickname);
    },
    //上传信息
    async setinfo() {
        if (this.data.title == '资料认证') {
            if (!this.data.name || !this.data.sex || !this.data.selectobjectid || !this.data.height || !this.data.phone) {
                wx.showToast({
                    title: '请输入相关内容',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            const currentUser = Parse.User.current();
            let Userquery = new Parse.Query('_User');
            Userquery.equalTo('company', company);
            Userquery.equalTo('objectId', currentUser.id);
            Userquery.notEqualTo('isDeleted', true)
            let user = await Userquery.first();
            user.set('sex', this.data.sex)
            // user.set('avatar', this.data.avatar)
            let diyform = {
                height: this.data.height
            }
            user.set('diyform', diyform)
            // user.set('nickname', this.data.nickname)
            try {
                user.save()
                console.log('昵称保存成功');
            } catch {
                console.log('保存失败');
            }

            let Profilerquery = new Parse.Query('Profile');
            Profilerquery.equalTo('company', company);
            Profilerquery.equalTo('user', currentUser.id);
            Profilerquery.notEqualTo('isDeleted', true)
            let Profile = await Profilerquery.first();
            //工会
            // let Departmentquery = new Parse.Query('Department');
            // Departmentquery.equalTo('company', company);
            // Departmentquery.equalTo('objectId', this.data.upiobjectid);
            // Departmentquery.notEqualTo('isDeleted', true)
            // let Department = await Departmentquery.first();
            //部门
            let unionquery = new Parse.Query('Department');
            unionquery.equalTo('company', company);
            unionquery.equalTo('objectId', this.data.selectobjectid);
            unionquery.notEqualTo('isDeleted', true)
            let union = await unionquery.first();

            if (Profile) {
                // Profile.set('department', Department.toPointer())
                Profile.set('center', union.toPointer())
                Profile.set('name', this.data.name)
                Profile.set('mobile', this.data.phone)
                try {
                    Profile.save()
                    wx.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000
                    })
                    setTimeout(() => {
                        this.goback()
                    }, 2000);
                    console.log('部门保存成功');
                } catch {
                    console.log('部门保存失败');
                }
            } else {
                const currentUser = Parse.User.current();
                let Userquery = new Parse.Query('_User');
                Userquery.equalTo('company', company);
                Userquery.equalTo('objectId', currentUser.id);
                Userquery.notEqualTo('isDeleted', true)
                let P2 = await Userquery.first();

                let companyPointer = Parse.Object.extend('Company').createWithoutData(company);
                console.log(companyPointer);
                let Profile = new Parse.Object('Profile');
                Profile.set('company', companyPointer);
                Profile.set('isCheck', false);
                Profile.set('user', P2.toPointer());
                // Profile.set('department', Department.toPointer());
                Profile.set('center', union.toPointer());
                Profile.set('name', this.data.name)
                Profile.set('mobile', this.data.phone)
                try {
                    Profile.save()
                    wx.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000
                    })
                    setTimeout(() => {
                        this.goback()
                    }, 2000);
                    console.log('部门保存成功');
                } catch {
                    console.log('部门保存失败');
                }
            }
        }
        if (this.data.title == '完善资料') {
            if (!this.data.avatar || !this.data.nickname) {
                wx.showToast({
                    title: '请输入相关内容',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            const currentUser = Parse.User.current();
            let Userquery = new Parse.Query('_User');
            Userquery.equalTo('company', company);
            Userquery.equalTo('objectId', currentUser.id);
            Userquery.notEqualTo('isDeleted', true)
            let user = await Userquery.first();
            user.set('avatar', this.data.avatar)
            user.set('nickname', this.data.nickname)
            try {
                user.save()
                wx.showToast({
                    title: '提交成功',
                    icon: 'success',
                    duration: 2000
                })
                setTimeout(() => {
                    this.goback()
                }, 2000);
            } catch {
                console.log('保存失败');
            }
        }
    },
    // 获取部门信息
    // async getDepartment() {
    //     const currentUser = Parse.User.current();
    //     let Userquery = new Parse.Query('Department');
    //     Userquery.equalTo('company', company); // 假设 company 是你要查询的公司对象
    //     Userquery.equalTo('isEnabled', true);
    //     Userquery.notEqualTo('isDeleted', true);
    //     Userquery.include('parent');

    //     let P2 = await Userquery.find();
    //     let Departmentlist = P2.map(item => item.toJSON());

    //     // 创建一个以工会为键的对象，以便于匹配
    //     const unionsMap = {};
    //     console.log(Departmentlist);
    //     // 遍历部门列表，构建工会映射
    //     Departmentlist.forEach(department => {
    //         //有工会的部门
    //         if (department.parent && department.parent.objectId) {
    //             const unionId = department.parent.objectId; //工会id

    //             // 如果工会还没有在映射中，创建一个新的工会对象
    //             if (!unionsMap[unionId]) {
    //                 unionsMap[unionId] = {
    //                     text: department.parent.name, // 工会名称
    //                     objectId: department.parent.objectId,
    //                     children: [] // 初始化子部门数组
    //                 };
    //             }
    //             // 将部门添加到对应的工会子项中
    //             unionsMap[unionId].children.push({
    //                 text: department.name, // 部门名称
    //                 id: department.objectId, // 部门 ID
    //                 upid: department.parent.objectId
    //             });
    //         } else {
    //             if (!unionsMap[department.objectId]) {
    //                 unionsMap[department.objectId] = {
    //                     text: department.name, // 工会名称
    //                     objectId: department.objectId,
    //                     children: [] // 初始化子部门数组
    //                 };
    //             }
    //         }
    //     });

    //     // 将映射转换为数组
    //     const result = Object.values(unionsMap);

    //     console.log(result);
    //     this.setData({
    //         items: result
    //     })
    //     console.log(this.data.items);
    // },
    //点击工会
    // onClickNav({
    //     detail = {}
    // }) {
    //     this.setData({
    //         mainActiveIndex: detail.index || 0,
    //     });
    //     console.log(detail);
    // },
    //点击部门
    onClickItem(
        {
        detail = {}
    }
    ) {
        // const activeId = this.data.activeId === detail.id ? null : detail.id;
        // this.data.items.forEach((item) => {
        //     if (item.objectId == detail.upid) {
        //         this.setData({
        //             departname: item.text
        //         })
        //     }
        // })
       const id =  this.data.Departmentlist[detail.index].objectId

        this.setData({
            // activeId,
            selectname: detail.value,
            selectobjectid:id
            // selectobjectid: detail.id,
            // upiobjectid: detail.upid
        });
        this.onClickHide()
        console.log(this.data.selectobjectid);
    },
    //显示遮罩层
    onClickShow() {
        this.setData({
            show: true
        });
    },
    //关闭遮罩层
    onClickHide() {
        this.setData({
            show: false
        });
    },
    //返回上一页
    async goback() {
        let pages = getCurrentPages(); //页面对象
        let prevpage = pages[pages.length - 2]; //上一个页面对象
        console.log(prevpage);
        await prevpage.updateCom3()
        wx.navigateBack({
            delta: 1 // 返回上一页
        });
    },
    //删除头像
    deleteavater() {
        this.setData({
            avatar: ''
        })
    },
    async getUptoken() {
        let res = await Parse.Cloud.run('qiniu_uptoken', {
            company: company
        })
        this.setData({
            uptokenURL: res.uptoken,
            domain: res.domain,
            uploadURL: res.zoneUrl
        })
        console.log(this.data.uptokenURL, this.data.domain, this.data.uploadURL);
    },
    //本地上传头像
    picture(event) {
        console.log('event', event);
        let FileList = event.detail
        let url = []
        for (let i = 0; i < FileList.length; i++) {
            url.push(FileList[i].url)
        }
        this.setData({
            fileList: url
        })
        this.setData({
            avatar: this.data.fileList[0]
        })
        console.log('图片', this.data.fileList);
    },
    //修改姓名
    changename(e) {
        this.setData({
            name: e.detail
        })
        console.log(this.data.name);
    },
    //修改电话
    changephone(e) {
        const mobileNumber = e.detail.value; // 假设手机号是通过 e.detail.value 传递的
        console.log(mobileNumber);
        // 正则表达式：匹配中国大陆手机号
        const mobilePattern = /^1[3-9]\d{9}$/;

        // 验证手机号格式
        if (mobilePattern.test(mobileNumber)) {
            this.setData({
                phone: mobileNumber
            })
            console.log("手机号格式正确");
            // 这里可以执行其他操作，比如保存手机号或进行下一步操作
        } else {
            wx.showToast({
                title: '手机号格式不正确',
                icon: 'none',
            })
            console.log("手机号格式不正确");
            // 这里可以提示用户手机号格式不正确
        }
        console.log(this.data.phone);
    },
    //身份证号码
    changeidnumber(e){
        const idnumber = e.detail;
        this.setData({
            idnumber,
        })
        console.log(idnumber);
    },
})