import config from '../../config'
import {
    getToken,
    getUserInfo
} from '../../utils/auth'
import {
    findProjectInfo,
    findProjectDepts
} from '../../api/project'
import {
    findSubDeptsUsers,
    findDaysAttendanceView,
    findUsersAttendanceView,
    findSubDeptsAttendanceView
} from '../../api/attendance'
import {
    findMyTask
} from '../../api/flowable'
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        title: "项目详情",
        activeNames: ["base"],
        //项目信息
        projectInfo: {},
        projectDeptsList: [],
        deptTypes: [{
            "name": "建设单位",
            "iconSrc": "https://xiangguan.sxyanzhu.com/profile/icon/jsdw.png"
        }, {
            "name": "监理单位",
            "iconSrc": "https://xiangguan.sxyanzhu.com/profile/icon/jldw.png"
        }, {
            "name": "设计单位",
            "iconSrc": "https://xiangguan.sxyanzhu.com/profile/icon/sjdw.png"
        }, {
            "name": "检测单位",
            "iconSrc": "https://xiangguan.sxyanzhu.com/profile/icon/jcjg.png"
        }, {
            "name": "勘察单位",
            "iconSrc": "https://xiangguan.sxyanzhu.com/profile/icon/fbdw.png"
        }, {
            "name": "总包单位",
            "iconSrc": "https://xiangguan.sxyanzhu.com/profile/icon/zbdw.png"
        }],
        active: 0,
        projectId: '',
        projectName: '',
        initData: {},
        aqglDb: 0,
        zlglDb: 0,
        todoDb: 0,
        nactive: 0,
        labourData: [{
                name: "管理人员",
                total: 0,
                unit: "人",
                yesMonitor: 180
            },
            {
                name: "劳务人员",
                yesMonitor: 0,
                total: 0,
                unit: "人"
            },
            {
                name: "特殊工种",
                yesMonitor: 0,
                total: 0,
                unit: "人"
            },
        ],
        labourDataList: [],
        labourDays: [{
                name: "管理人员",
                total: 0,
                unit: "人",
                yesMonitor: 180
            },
            {
                name: "劳务人员",
                yesMonitor: 0,
                total: 0,
                unit: "人"
            },
            {
                name: "特殊工种",
                yesMonitor: 0,
                total: 0,
                unit: "人"
            },
        ],
        labourDaysTotal: 0,
        labourImg: "https://szgcwx.jhncidg.com/staticFiles/icon/zgry.png",
        labourName: "在岗人员",
        labourTotal: 0,
        labourTypeList: [{
            name: "在岗人员",
            total: 0,
            img: "https://szgcwx.jhncidg.com/staticFiles/icon/zgry.png"
        }, {
            name: "离岗人员",
            total: 0,
            img: "https://szgcwx.jhncidg.com/staticFiles/icon/rylg.png"
        }],
        animation: true,
        animationData: {},
        labourDatas: {
            unit: '人',
            legend: ['出勤人数', '当前在岗'],
            color: ['#2e6ed0', '#fb9300'],
            Xdata: ['01-01', '01-02', '01-03', '01-04', '01-05', '01-06', '01-07'],
            Ydata: [
                [0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0]
            ]
        },
        switchChart: false,
        attendanceListData: [],
        subDeptUserInfo: {},
        imgBaseUrl: config.baseImgUrl
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (!getToken()) {
            wx.redirectTo({
                url: '../login/login',
            })
        }
        wx.setStorageSync('nav-menu', "xmgk");
        const proUserInfo = getUserInfo();
        app.globalData.subDeptUserData = proUserInfo.projectUserInfo;
        this.initAnimationData();
        this.setData({
            labourImg: this.data.labourTypeList[this.data.nactive].img,
            projectId: app.globalData.useProjectId,
            projectName: app.globalData.useProjectName,
            initData: {
                id: app.globalData.useProjectId,
                text: app.globalData.useProjectName,
            },
            subDeptUserInfo: proUserInfo.projectUserInfo
        });
        //项目基本信息
        this.getProjectInfo(app.globalData.useProjectId);
        //用户项目信息
        this.getProUserDatas();
        //项目建设单位
        this.getProjectDepts(app.globalData.useProjectId);
    },

    /**
     * 统计劳务人员信息
     * @param {*} proId 
     */
    getSubDeptsUsers(proId) {
        findSubDeptsUsers(proId).then(res => {
            if (res.code == 200) {
                let zg = 0;
                let lg = 0;
                res.data.forEach(item => {
                    if (item.useStatus == '0') {
                        zg += item.total;
                    } else {
                        lg += item.total;
                    }
                });
                this.setData({
                    "labourTypeList[0].total": zg,
                    "labourTypeList[1].total": lg,
                    labourTotal: zg,
                    labourDataList: res.data || []
                })
                this.initSubDeptUsersCharts();
            }
        });
    },

    /**
     * 初始化动画
     */
    initAnimationData() {
        var animation = wx.createAnimation({
            duration: 1000,
            timingFunction: 'linear',
        })
        this.animation = animation;
        if (this.data.animation) {
            animation.translateY(-8).step();
        } else {
            animation.translateY(8).step();
        }
        this.setData({
            animation: this.data.animation ? false : true,
            animationData: animation.export()
        })
        setTimeout(() => {
            this.initAnimationData();
        }, 1200)
    },

    /**
     * 初始化统计图表
     */
    initSubDeptUsersCharts() {
        let labourDataList = this.data.labourDataList;
        if (labourDataList.length > 0) {
            let gl = 0;
            let ts = 0;
            let lw = 0;
            labourDataList.forEach(item => {
                if (this.data.nactive == 0) {
                    if (item.useStatus == '0') {
                        if (item.craftType == '2') {
                            ts += item.total;
                        } else if (item.craftType == '3') {
                            gl += item.total;
                        } else {
                            lw += item.total;
                        }
                    }
                } else {
                    if (item.useStatus != '0') {
                        if (item.craftType == '2') {
                            ts += item.total;
                        } else if (item.craftType == '3') {
                            gl += item.total;
                        } else {
                            lw += item.total;
                        }
                    }
                }
            });
            this.setData({
                "labourData[0].total": gl,
                "labourData[0].yesMonitor": gl,
                "labourData[1].total": ts,
                "labourData[1].yesMonitor": ts,
                "labourData[2].total": lw,
                "labourData[2].yesMonitor": lw,
                labourTotal: this.data.labourTypeList[this.data.nactive].total
            })
            if (this.data.switchChart) {
                let chats = this.selectComponent("#userChart");
                chats.initChart();
            }
        }
    },

    /**
     * 初始化
     * 今日考勤
     * @param {*} proId 
     */
    initSubDeptDaysCharts(proId) {
        findDaysAttendanceView(proId).then(res => {
            if (res.code == 200) {
                let gl = 0;
                let ts = 0;
                let lw = 0;
                res.data.forEach(item => {
                    if (item.craftType == '2') {
                        ts += item.total;
                    } else if (item.craftType == '3') {
                        gl += item.total;
                    } else {
                        lw += item.total;
                    }
                });
                this.setData({
                    "labourDays[0].total": gl,
                    "labourDays[0].yesMonitor": gl,
                    "labourDays[1].total": ts,
                    "labourDays[1].yesMonitor": ts,
                    "labourDays[2].total": lw,
                    "labourDays[2].yesMonitor": lw,
                    labourDaysTotal: gl + ts + lw
                })
                if (this.data.switchChart) {
                    let chats = this.selectComponent("#attsChart");
                    chats.initChart();
                }
            }
        });
    },

    /**
     * 统计
     * 最近出勤信息
     * @param {*} proId 
     */
    getSubDeptsAttendanceView(proId) {
        findSubDeptsAttendanceView(proId).then(res => {
            if (res.code == 200) {
                let xd = [];
                let yd1 = [];
                let yd2 = [];
                res.data.list.forEach(item => {
                    xd.push(item.attendanceTime);
                    yd1.push(item.total);
                });
                if (xd.length < 7) {
                    let n = 7 - xd.length;
                    for (let i = 0; i < n; i++) {
                        xd.push('-');
                        yd1.push(0);
                    }
                }
                for (let y = 0; y < 7; y++) {
                    yd2.push(res.data.user);
                }
                let yd = [];
                yd.push(yd1);
                yd.push(yd2);
                this.setData({
                    "labourDatas.Xdata": xd,
                    "labourDatas.Ydata": yd
                });
                if (this.data.switchChart) {
                    let chats = this.selectComponent("#chartBar");
                    chats.initChart();
                }
            }
        });
    },

    /**
     * 查询用户考勤
     * @param {*} proId 
     */
    getUsersAttendanceView(proId) {
        findUsersAttendanceView(proId).then(res => {
            if (res.code == 200) {
                this.setData({
                    attendanceListData: res.data
                });
            }
        })
    },

    /**
     * 单位人员信息
     * @param {*} proId 
     */
    getProUserDatas() {
        //劳务人员信息
        if ((app.globalData.subDeptUserData.subDeptType == '1' || app.globalData.subDeptUserData.subDeptType == '4' || app.globalData.subDeptUserData.subDeptType == '5') && app.globalData.subDeptUserData.userPost != '4' && app.globalData.subDeptUserData.userPost != '5' && app.globalData.subDeptUserData.userPost != '6' && app.globalData.subDeptUserData.userPost != '8') {
            //统计劳务人员信息
            this.getSubDeptsUsers(app.globalData.useProjectId);
            this.initSubDeptDaysCharts(app.globalData.useProjectId);
        }
        this.awaitTask();
        //今日出勤信息
        if (app.globalData.subDeptUserData.subDeptType == '1') {
            this.getSubDeptsAttendanceView(app.globalData.useProjectId);
        }
        //人员出勤信息
        if (app.globalData.subDeptUserData.userPost == '4' || app.globalData.subDeptUserData.userPost == '5' || app.globalData.subDeptUserData.userPost == '6' || app.globalData.subDeptUserData.userPost == '8') {
            //统计劳务人员信息
            this.getUsersAttendanceView(app.globalData.useProjectId);
        }
    },

    /**
     * 查询公众号消息授权
     */
    reUserOpenMsgId() {
        let userInfos = this.selectComponent("#userInfos");
        userInfos.loadUserInfo();
    },

    // 底部导航
    onChange(event) {
        // event.detail 的值为当前选中项的索引
        this.setData({
            active: event.detail
        });
    },

    /**
     * 初始化曲线图表
     */
    initLabourDatas() {
        findGroupAllByDays({
            projectId: app.globalData.projectId
        }).then(res => {
            if (res.code == 200) {
                let xd = [];
                let yd1 = [];
                let yd2 = [];
                res.data.list.forEach(item => {
                    xd.push(item.attendanceTime);
                    yd1.push(item.total);
                });
                if (xd.length < 7) {
                    let n = 7 - xd.length;
                    for (let i = 0; i < n; i++) {
                        xd.push('');
                        yd1.push(0);
                    }
                }
                for (let y = 0; y < 7; y++) {
                    yd2.push(res.data.user);
                }
                let yd = [];
                yd.push(yd1);
                yd.push(yd2);
                this.setData({
                    "labourDatas.Xdata": xd,
                    "labourDatas.Ydata": yd
                });
                if (this.data.switchChart) {
                    let chats = this.selectComponent("#chartBar");
                    chats.initChart();
                }
            }
        });
    },

    /**
     * 查询项目详情
     * @param {*} proId 
     */
    getProjectInfo: function (proId) {
        findProjectInfo(proId).then(res => {
            if (res.data.scheduledStartTime) {
                res.data.scheduledStartTime = res.data.scheduledStartTime.split("T")[0];
            } else {
                res.data.scheduledStartTime = " - ";
            }
            if (res.data.actualOperatingTime) {
                res.data.actualOperatingTime = res.data.actualOperatingTime.split("T")[0];
            } else {
                res.data.actualOperatingTime = " - ";
            }
            if (res.data.plannedCompletionTime) {
                res.data.plannedCompletionTime = res.data.plannedCompletionTime.split("T")[0];
            } else {
                res.data.plannedCompletionTime = " - ";
            }
            res.data.projectDeptsList.forEach(item => {
                this.data.deptTypes.forEach(_it => {
                    if (_it.name == item.deptType) {
                        item.iconSrc = _it.iconSrc;
                    }
                })
            });
            this.setData({
                projectInfo: res.data,
                projectDeptsList: res.data.projectDeptsList
            })
        });
    },

    /**
     * 查询
     * 项目建设单位
     * @param {*} proId 
     */
    getProjectDepts: function (proId) {
        findProjectDepts(proId).then(res => {
            this.setData({
                projectDeptsList: res.data
            })
        });
    },

    // 页签选中事件
    selectedTab(e) {
        this.setData({
            nactive: e.target.dataset.set,
            labourImg: this.data.labourTypeList[e.target.dataset.set].img,
        })
        this.initSubDeptUsersCharts();
    },

    //项目切换 返回值
    onProjectSelect(e) {
        let projectId = e.detail.id;
        let projectName = e.detail.text;
        app.globalData.useProjectId = projectId;
        app.globalData.useProjectName = projectName;
        this.setData({
            switchChart: true
        })
        this.onLoad();
    },

    // 手风琴
    onCollChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },

    /**
     * 拨打电话
     * @param {*} event 
     */
    calling: function (event) {
        let callPhone = event.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: callPhone,
            success: function () {
                console.log("拨打电话成功!")
            },
            fail: function () {
                console.log("拨打电话失败!")
            }
        })
    },

    showImg: function (e) {
        let paths = e.target.dataset.set;
        let path = [];
        paths.split(',').forEach(url => {
            path.push(config.baseImgUrl + url);
        });
        wx.previewImage({
            urls: path,
            current: path[0]
        })
    },

    /**
     * 劳务管理查看详细
     */
    goLWGL: function () {
        if (this.data.nactive == 2) {
            wx.redirectTo({
                url: '../../pageage/project_attendance/project_attendanceData/list/index'
            })
        } else {
            let type;
            if (this.data.nactive == 0) {
                type = 1;
            } else {
                type = 2;
            }
            wx.redirectTo({
                url: '../../pageage/project_attendance/project_attendanceUser/list/index?type=' + type
            })
        }
    },

    /**
     * 最近出勤
     */
    goZJCQ: function () {
        wx.redirectTo({
            url: '../../pageage/project_attendance/project_attendanceData/list/index'
        })
    },

    //跳转到安全管控
    XMSP: function () {
        wx.setStorageSync('nav-menu', "aqgl");
        wx.redirectTo({
            url: '../project_safety/index'
        })
    },

    //跳转到质量管理
    ZLGL: function () {
        wx.setStorageSync('nav-menu', "zlgl");
        wx.redirectTo({
            url: '../project_quality/index'
        })
    },

    //跳转到进度管理
    JDGL: function () {
        wx.setStorageSync('nav-menu', "xmgk");
        wx.redirectTo({
            url: '../project_schedule/list/index'
        })
    },

    //跳转到项目管理
    XMGL: function () {
        wx.setStorageSync('nav-menu', "xmgl");
        wx.redirectTo({
            url: '../project_more/index'
        })
    },

    //跳转到项目列表
    XMLB: function () {
        wx.redirectTo({
            url: '../project_list/index'
        })
    },

    /**
     * 统计代办
     */
    awaitTask() {
        let param = "proId=" + app.globalData.useProjectId;
        findMyTask(param).then(res => {
            if (res.code == 200) {
                let proUserInfo = this.data.subDeptUserInfo;
                this.setData({
                    todoDb: proUserInfo.subDeptType=="1"?(res.data.dwsh+res.data.rysh):res.data.todo,
                    aqglDb: proUserInfo.subDeptType=="1"?res.data.aqgl:0,
                    zlglDb: proUserInfo.subDeptType=="1"?res.data.zlgl:0
                })
            }
        });
    },
})