import apiTools from '@/api'
import jwtDecode from 'jwt-decode'

export default {
    namespaced: true,
    state: {
        schoolCode: undefined,         //HBCN 學校代碼 (現在先寫死)
        userDetails: [],            // 使用者詳細資訊[]
        schoolUserList: undefined,  //學校所有使用者
        userList: undefined,        //從Core.ID取得的使用者
        schoolSettingAuthList: undefined,   //所有權限總列表
        userProfile: { // 老師個人設定黨
            defaultschool: undefined, // 老師預設的登入學校
            schools: undefined,     // 老師加入的學校清單
            blob_sas: undefined,    // 老師Blob金鑰，讀寫
            blob_uri: undefined,    // 老師Blob網址
            courses: undefined,     // 老師的個人課程
            syllabus: undefined,    // 老師的個人課綱
        },
        schoolProfile: { // 老師在學校的設定檔
            blob_uri: undefined,    // 學校Blob網址
            blob_sas: undefined,    // 學校Blob金鑰，讀
            periods: undefined,    // 學校的學制List
            grades: undefined,    // 學校的年級List
            school_base: undefined, // 区班校基础数据
            school_classes: undefined, // 学校班级
            school_courses: undefined, // 学校排课
            school_syllabus: undefined // 校本课纲
        },
        studentProfile: { // 學生在學校的設定檔
            blob_uri: undefined,
            blob_sas: undefined,
            classinfo: undefined,
            courses: undefined
        },
        authStatus: undefined, //(單數)老師權限總設定值
        authStatusMulti: undefined //(複數)老師權限總設定值
    },
    getters: {
        getSchoolUserAll: state => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList
            } else {
                return []
            }
        },
        getSchoolUserJoined: state => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList.filter(
                    user => user.status == 'join'
                )
            } else {
                return []
            }
        },
        getSchoolUserInvited: state => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList.filter(
                    user => user.status == 'invite'
                )
            } else {
                return []
            }
        },
        getSchoolUserRequested: state => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList.filter(
                    user => user.status == 'request'
                )
            } else {
                return []
            }
        },
        getSchoolUserRequestedCount: state => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList.filter(
                    user => user.status == 'request'
                ).length
            } else {
                return 0
            }
        },
        getSchoolUserInvitedOrRequested: state => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList.filter(
                    user => user.status == 'invite' || user.status == 'request'
                )
            } else {
                return []
            }
        },
        getSchoolUserByID: state => ID => {
            if (state.schoolUserList !== undefined) {
                return state.schoolUserList.filter(
                    user => user.id === ID
                )
            } else {
                return []
            }
        },
        getschoolSettingAuthList: state => {
            let result = new Object();
            let authListFormed = new Object();
            let authDisable = new Object();
            let authIdToPath = new Object();

            if (state.schoolSettingAuthList !== undefined) {
                //整形 
                state.schoolSettingAuthList.forEach(function (item) {
                    //第一層 (read)
                    if (typeof authListFormed[item.path] == 'undefined') {
                        authListFormed[item.path] = new Object();
                        authDisable[item.path] = true;
                    }
                    if (item.root) {
                        authListFormed[item.path]['rowKey'] = item.rowKey;
                        authListFormed[item.path]['mode'] = item.mode;
                        authListFormed[item.path]['category'] = item.category;
                        authIdToPath[item.rowKey] = item.path;
                    }
                    //第二層 (非read)
                    else {
                        if (typeof authListFormed[item.path]['subitem'] == 'undefined') {
                            authListFormed[item.path]['subitem'] = new Object();
                        }
                        if (typeof authListFormed[item.path]['subitem'][item.rowKey] == 'undefined') {
                            authListFormed[item.path]['subitem'][item.rowKey] = new Object();
                        }
                        authListFormed[item.path]['subitem'][item.rowKey]['rowKey'] = item.rowKey;
                        authListFormed[item.path]['subitem'][item.rowKey]['mode'] = item.mode;
                        authListFormed[item.path]['subitem'][item.rowKey]['category'] = item.category;
                    }
                });
            }
            result.authListFormed = authListFormed;
            result.authDisable = authDisable;
            result.authIdToPath = authIdToPath;
            return result
        },
        getTeacherAuthStatus: state => {
            return state.authStatus
        },
        getTeacherAuthStatusMulti: state => {
            return state.authStatusMulti
        },
        getLoginSchooCode: state => state.schoolCode,
        getPeriods: state => {
            return state.schoolProfile.periods
        },
        getGrades: state => {
            return state.schoolProfile.grades
        },
        getClasses: state => {
            return state.schoolProfile.school_classes
        },
        getRooms: state => {
            return state.schoolProfile.school_rooms
        }

    },
    mutations: {
        setSchoolUserList(state, data) {
            state.schoolUserList = data
        },
        //基础设置修改区班校数据后，更新vuex和localstorage
        setSchoolBase(state, data) {
            //更新localstorage
            let schoolStr = localStorage.getItem('school_profile')
            if (schoolStr) {
                schoolStr = decodeURIComponent(schoolStr, "utf-8")
                let schoolJson = JSON.parse(schoolStr)
                schoolJson.school_base = data
                schoolStr = encodeURIComponent(JSON.stringify(schoolJson), "utf-8")
                localStorage.setItem('school_profile', schoolStr)
            }
            //更新vuex
            state.schoolProfile.school_base = data
        },

        setUserList(state, data) {
            state.userList = data
        },
        resetSchoolUserList(state) {
            state.schoolUserList = undefined
        },
		resetSchoolProfile(state){
			state.schoolCode = undefined
			state.schoolProfile.blob_sas = undefined // 老師在學校的Blob金鑰，讀寫
			state.schoolProfile.blob_uri = undefined // 老師在學校的Blob網址
			state.schoolProfile.school_courses = undefined // 学校排课
			state.schoolProfile.school_syllabus = undefined // 校本课纲
			state.schoolProfile.school_classes = undefined // 学校班级
			state.schoolProfile.school_rooms = undefined // 学校教室
			state.schoolProfile.periods = undefined // 學制
			state.schoolProfile.grades = undefined // 年級
			state.schoolProfile.school_base = undefined // 区班校基础数据
		},
        setSchoolSettingAuthList(state, data) {
            state.schoolSettingAuthList = data
        },
        setUserProfile(state, data) {
            state.userProfile.blob_sas = data.blob_sas // 老師Blob金鑰，讀寫
            state.userProfile.blob_uri = data.blob_uri // 老師Blob網址
            state.userProfile.courses = data.courses // 老師的個人課程
            state.userProfile.defaultschool = data.defaultschool // 老師預設的登入學校
            state.userProfile.schools = data.schools // 老師加入的學校清單
            state.userProfile.syllabus = data.syllabus // 老師的個人課綱
        },
        setSchoolProfile(state, data) {
            state.schoolProfile.blob_sas = data.blob_sas // 老師在學校的Blob金鑰，讀寫
            state.schoolProfile.blob_uri = data.blob_uri // 老師在學校的Blob網址
            state.schoolProfile.school_courses = data.school_courses // 学校排课
            state.schoolProfile.school_syllabus = data.school_syllabus // 校本课纲
            state.schoolProfile.school_classes = data.school_classes // 学校班级
            state.schoolProfile.school_rooms = data.school_rooms // 学校教室
            state.schoolProfile.periods = data.fmtPeriods // 學制
            state.schoolProfile.grades = data.fmtGrades // 年級
            state.schoolProfile.school_base = data.school_base // 区班校基础数据
        },
        setStudentProfile(state, data) {
            state.studentProfile.blob_uri = data.blob_uri // 學生在學校的Blob網址
            state.studentProfile.blob_sas = data.blob_sas // 學生在學校的Blob金鑰，讀寫
            state.studentProfile.classinfo = data.classinfo // 學生在學校的的個人課程
            state.studentProfile.courses = data.courses // 學生在學校的的個人課綱
        },
        setAuthStatus(state, data) {
            state.authStatus = data;
        },
        setAuthStatusMulti(state, data) {
            state.authStatusMulti = data;
        },
        setSchoolCode(state, data) {
            state.schoolCode = data
        },
        addRoom(state, data) {
            let school_profile = localStorage.getItem('school_profile')
            if(school_profile){
                let schoolProfile = JSON.parse(decodeURIComponent(school_profile,"utf-8"))
                schoolProfile.school_rooms.unshift(data)
                state.schoolProfile.school_rooms = schoolProfile.school_rooms
                localStorage.setItem('school_profile', encodeURIComponent(JSON.stringify(schoolProfile), "utf-8"))
            }
        },
        delRoom(state, id) {
            let school_profile = localStorage.getItem('school_profile')
            if(school_profile){
                let schoolProfile = JSON.parse(decodeURIComponent(school_profile,"utf-8"))
                let orgIndex = -1;

                for (let i in schoolProfile.school_rooms) {
                    if (schoolProfile.school_rooms[i].id == id) {
                        orgIndex = i
                        break
                    }
                }
                schoolProfile.school_rooms.splice(orgIndex, 1) // 刪掉指定教室
                state.schoolProfile.school_rooms = schoolProfile.school_rooms
                localStorage.setItem('school_profile', encodeURIComponent(JSON.stringify(schoolProfile), "utf-8"))
            }
        },
    },
    actions: {
		// 获取学校基本信息
        getSchoolProfile(context) {
            return new Promise((resolve, reject) => {
                if (context.state.schoolProfile.school_base) {
                    resolve(context.state.schoolProfile)
                } else {
                    let login_schoolCode = localStorage.getItem('login_schoolCode')
                    let id_token = localStorage.getItem('id_token')
                    if (login_schoolCode && id_token) {
                        apiTools.login.getTeacherSchoolInfo({
                            id_token: id_token,
                            school_code: login_schoolCode
                        }).then(res => {
                            if (!res.error) {
                                context.dispatch('setSchoolProfile', res)
                                resolve(res)
                            }
                        }).catch(err => {
                            reject(err)
                        })
                    }else{
						resolve(context.state.schoolProfile)
					}
                }
            })
        },
        // 從DB取得所有該校的使用者 && commit to state.schoolUserList
        getSchoolTeacher(context) {
            return new Promise(
                (resolve, reject) => {
                    if (typeof context.state.schoolCode !== 'undefined' && context.state.schoolCode !== undefined) {
                        apiTools.schoolUser.getSchoolTeacherAll({
                            school_code: context.state.schoolCode
                        }).then(
                            res => {
                                //放入storage
                                if (res.hasOwnProperty('teachers') && res.teachers.length > 0) {
                                    context.commit('setSchoolUserList', res.teachers)
                                    resolve({
                                        code: 1,
                                        message: 'Get School user successful'
                                    })
                                }
                            },
                            err => {
                                reject({
                                    code: 0,
                                    data: [],
                                    message: 'Get School user API error!'
                                })
                            }
                        )
                    } else {
                        reject({
                            code: 0,
                            data: [],
                            message: 'No valid school code.'
                        })
                    }
                }
            )
        },

        // 設定使用者權限
        setSchoolUserPermission(context, params) {
            return new Promise(
                (resolve, reject) => {
                    let schoolCode = context.state.schoolCode
                    let ids = params.ids
                    if (typeof schoolCode !== 'undefined' && schoolCode !== undefined && typeof ids !== 'undefined' && ids !== undefined) {
                        apiTools.schoolUser.updPermissionByIds({
                            school_code: schoolCode,
                            ids: params.ids,
                            pmAdd: params.pmAdd,
                            pmRmv: params.pmRmv,
                            job: params.job,
                            mode: params.mode
                        }).then(
                            res => {
                                resolve({
                                    code: 1,
                                    message: 'Set permission successfully.'
                                })
                            },
                            err => {
                                reject({
                                    code: 0,
                                    data: [],
                                    message: 'Set authority API error!'
                                })
                            }
                        )
                    } else {
                        reject({
                            code: 0,
                            data: [],
                            message: 'No valid school code or TEAMModelIds.'
                        })
                    }
                }
            )
        },

        // 更新使用者資訊 輸入項：要更新的使用者資訊(array[object])
        updSchoolUserByList(context, params) {
            let schoolUserListNow = context.state.schoolUserList
            let schoolUserListUpd = params
            if (schoolUserListUpd.length > 0 && schoolUserListNow.length > 0) {
                schoolUserListUpd.forEach(function (userUpd) {
                    schoolUserListNow.forEach(function (userNow, indexNow) {
                        if (userUpd.id === userNow.id) {
                            schoolUserListNow[indexNow] = userUpd
                        }
                    })
                })
            }
            context.commit('setSchoolUserList', schoolUserListNow)
        },
        // 更新單一使用者資訊
        updSchoolUserInfo(context, params) {
            let id = params.id;
            let param = params.param;
            let schoolUserListNow = context.state.schoolUserList
            if (schoolUserListNow.length > 0) {
                schoolUserListNow.forEach(userinfo => {
                    if (userinfo.id == id) {
                        for (var prop in param) {
                            if (typeof userinfo[prop] !== 'undefined') {
                                userinfo[prop] = param[prop];
                            }
                        }
                    }
                });
            }
            context.commit('setSchoolUserList', schoolUserListNow)
        },

        // 將使用者從學校使用者列表中移除
        rmvFromSchoolUserByID(context, params) {
            return new Promise(
                (resolve, reject) => {
                    let school_code = context.state.schoolCode
                    let schoolUserListNow = context.state.schoolUserList
                    let rmvId = params.id
                    apiTools.schoolUser.rmvSchoolUser({
                        school_code: school_code,
                        id: rmvId
                    }).then(
                        res => {
                            // 更新 state.schoolUserList
                            let i = 0
                            while (i < schoolUserListNow.length) {
                                if (schoolUserListNow[i].id == rmvId) {
                                    schoolUserListNow.splice(i, 1)
                                } else {
                                    ++i
                                }
                            }
                            context.commit('setSchoolUserList', schoolUserListNow)
                            resolve({
                                code: 1,
                                message: 'Remove user successfully.'
                            })
                        },
                        err => {
                            reject({
                                code: 0,
                                data: [],
                                message: 'Remove user API error!'
                            })
                        }
                    )
                }
            )
        },

        // 清空 state.schoolUserList
        resetSchoolUser(context) {
            context.commit('resetSchoolUserList')
        },

        // 變更使用者加入狀態
        updSchoolUserStatus(context, params) {
            return new Promise(
                (resolve, reject) => {
                    let school_code = context.state.schoolCode
                    let id = params.id
                    let status = params.status
                    if (typeof school_code !== 'undefined' && school_code !== undefined && typeof id !== 'undefined' && id !== undefined) {
                        apiTools.schoolUser.updStatusToSchoolUser({
                            school_code: school_code,
                            id: id,
                            grant_type: status
                        }).then(
                            res => {
                                // 更新 state.schoolUserList
                                context.dispatch('updSchoolUserInfo', { id: id, param: { status: status } });
                                resolve({
                                    code: 1,
                                    message: 'Upd param successfully.'
                                })
                            },
                            err => {
                                reject({
                                    code: 0,
                                    data: [],
                                    message: 'Set authority API error!'
                                })
                            }
                        )
                    }
                }
            )
        },

        // 1.取得學校設定權限列表 2.設定老師權限值
        getSchoolAuthorityList(context) {
            return new Promise(
                (resolve, reject) => {
                    apiTools.schoolUser.getSchoolAuthorityList().then(
                        res => {
                            //設定權限總列表
                            context.commit('setSchoolSettingAuthList', res.authoritylist)
                            //設定老師權限值
                            let authStatus = {} //單數
                            let authStatusMulti = { //複數
                                'on': {},
                                'off': {}
                            }
                            if (res.authoritylist.length > 0) {
                                res.authoritylist.forEach(function (item) {
                                    //單數
                                    authStatus[item.rowKey] = false
                                    //複數
                                    authStatusMulti['on'][item.rowKey] = '0'
                                    authStatusMulti['off'][item.rowKey] = '0'
                                });
                            }
                            context.commit('setAuthStatus', authStatus)
                            context.commit('setAuthStatusMulti', authStatusMulti)
                            //回傳值
                            resolve({
                                code: 1,
                                message: 'Get school authority list successfully.'
                            })
                        },
                        err => {
                            reject({
                                code: 0,
                                data: [],
                                message: 'Get school authority list API error!'
                            })
                        }
                    )
                }
            )
        },
        // 重設(複數)老師權限值
        resetAuthStatusMulti(context) {
            let authStatusMultiNow = context.state.authStatusMulti;
            let authStatusMulti = {
                'on': {},
                'off': {}
            }
            for (var key in authStatusMultiNow['on']) {
                authStatusMulti['on'][key] = '0';
            }
            for (var key in authStatusMultiNow['off']) {
                authStatusMulti['off'][key] = '0';
            }
            context.commit('setAuthStatusMulti', authStatusMulti)
        },
        //追加老師為「邀請」者至資料庫後，追加至state.schoolUserList
        addSchoolUserToInvite(context, params) {
            return new Promise(
                (resolve, reject) => {
                    let schoolCode = context.state.schoolCode
                    if (typeof schoolCode !== 'undefined' && schoolCode !== undefined && params.length > 0) {
                        apiTools.schoolUser.addSchoolUserToInvite({
                            school_code: schoolCode,
                            user_list: params,
                            grant_type: 'invite'
                        }).then(
                            res => {
                                // 追加新使用者至 state.schoolUserList
                                context.dispatch('addSchoolUserToSchoolUserList', { user_list: params, grant_type: 'invite' })
                                resolve({
                                    code: 1,
                                    message: 'Add user to school successfully.'
                                })
                            },
                            err => {
                                reject({
                                    code: 0,
                                    data: [],
                                    message: 'Add user to school API error!'
                                })
                            }
                        )
                    } else {
                        reject({
                            code: 0,
                            data: [],
                            message: 'No valid school code or user info.'
                        })
                    }
                }
            )
        },
        // 追加使用者資訊至前端學校使用者列表 輸入項：追加的使用者資訊(array[object])
        addSchoolUserToSchoolUserList(context, params) {
            let addUserlist = params.user_list
            let status = params.grant_type
            let schoolUserListNow = context.state.schoolUserList
            if (addUserlist.length > 0) {
                addUserlist.forEach(function (userAdd) {
                    userAdd.status = status
                    userAdd.createTime = Math.round((new Date()).getTime() / 1000)
                    schoolUserListNow.push(userAdd)
                })
            }
            context.commit('setSchoolUserList', schoolUserListNow)
        },
        setUserProfile(context, data) {
            localStorage.setItem('user_profile', encodeURIComponent(JSON.stringify(data), "utf-8"))
            context.commit('setUserProfile', data)
        },
        checkUserProfile(context) {
            let user_profile = localStorage.getItem('user_profile')
            if (user_profile) {
                context.commit('setUserProfile', JSON.parse(decodeURIComponent(user_profile, "utf-8")))
            }
        },
        setSchoolProfile(context, data) {
            localStorage.setItem('school_profile', encodeURIComponent(JSON.stringify(data), "utf-8"))
            let fmtPeriods = [];
            let fmtGrades = [];

            data.school_base.period.forEach(item => {
                // 學制List
                fmtPeriods.push({ 'id': item.id, 'name': item.name })

                // 年級List
                item.grades.forEach((gradeItem,gradeIndex) => {
                    fmtGrades.push({ 'periodId': item.id, 'id': gradeIndex, 'name': gradeItem })
                    // fmtGrades.push({ 'periodId': item.id, 'id': gradeItem.id, 'name': gradeItem.name }) // grade结构调整
                })
            })
            data.fmtPeriods = fmtPeriods
            data.fmtGrades = fmtGrades

            //处理教室默认上课班级
            data.school_rooms.forEach(item=>{
                let classInfo = data.school_classes.find(classItem=>{
                    return item.id == classItem.room
                })
                item.classId = classInfo ? classInfo.id : undefined
                item.className = classInfo ? classInfo.name : undefined
            })
            console.log(data)
            context.commit('setSchoolProfile', data)
        },
        setStudentProfile(context, data) {
            localStorage.setItem('student_profile', encodeURIComponent(JSON.stringify(data), "utf-8"))
            context.commit('setStudentProfile', data)
        },
        async checkSchoolProfile(context) {
            let school_profile = localStorage.getItem('school_profile')
            if(school_profile){
                context.dispatch('setSchoolProfile', JSON.parse(decodeURIComponent(school_profile,"utf-8")))
            }

            let login_schoolCode = localStorage.getItem('login_schoolCode')
            let id_token = localStorage.getItem('id_token')

            if (login_schoolCode && id_token) {
                // 輸出暫存
                let result;

                let info = {
                    roles: '',
                    permissions: ''
                }

                await apiTools.login.getTeacherSchoolInfo({
                    id_token: id_token,
                    school_code: login_schoolCode
                }).then(res => {
                    // 沒有錯誤的話
                    if (!res.error) {
                        // 儲存大雲Token
                        localStorage.setItem("auth_token", res.auth_token)
                        context.dispatch('setSchoolProfile', res)
                        result = res
                    }
                }).catch(err => {
                    console.log(err)
                })

                let authBySchool = jwtDecode(result.auth_token)
                info.roles = authBySchool.roles
                info.permissions = authBySchool.permissions == null ? [] : authBySchool.permissions

                let userInfo = JSON.parse(decodeURIComponent(localStorage.getItem('userInfo'), "utf-8"))
                userInfo.roles = info.roles
                userInfo.permissions = info.permissions
                localStorage.setItem('userInfo', encodeURIComponent(JSON.stringify(userInfo), "utf-8"))

                let userAccess = JSON.parse(decodeURIComponent(localStorage.getItem('userAccess'), "utf-8"))
                userAccess.roles = info.roles
                userAccess.permissions = info.permissions
                localStorage.setItem('userAccess', encodeURIComponent(JSON.stringify(userAccess), "utf-8"))

                return true
            } else {
                return false
            }
        },
        checkStudentProfile(context) {
            let student_profile = localStorage.getItem('student_profile')
            if (student_profile) {
                context.commit('setStudentProfile', JSON.parse(decodeURIComponent(student_profile, "utf-8")))
            }
        },
        checkSchoolCode(context) {
            let login_schoolCode = localStorage.getItem('login_schoolCode')
            if (login_schoolCode) {
                context.commit('setSchoolCode', login_schoolCode)
            }
        },
        setSchoolCode(context, data) {
			context.rootState.userInfo.schoolCode = data
			context.rootState.userInfo.hasSchool = true
            localStorage.setItem('login_schoolCode', data)
            context.commit('setSchoolCode', data)
        },
        getGradeById(context, gradeId) {
            return new Promise((resolve) => {
                if (typeof context.state.schoolProfile !== 'undefined' && context.state.schoolProfile !== undefined) {
                    let gradeData = context.state.schoolProfile.grades.filter(function (item, index) {
                        return (item.id == gradeId)
                    })
                    resolve(gradeData[0])
                } else {
                    resolve([])
                }
            })
        },
        // 向ID系統取得使用者資料 輸入項：(array[])
        getUserFromCoreId(context, params) {
            return new Promise(
                (resolve, reject) => {
                    apiTools.schoolUser.getUserFromCoreId(
                        params
                    ).then(
                        res => {
                            resolve({
                                code: 1,
                                data: res,
                                message: ''
                            })
                        },
                        err => {
                            reject({
                                code: 0,
                                data: [],
                                message: 'Add user to school API error!'
                            })
                        }
                    )
                }
            )
        },
        
        // 新增教室
        addSchoolRoom(context, data) {
            context.commit('addRoom', data)
        },

        // 刪除教室
        delSchoolRoom(context, id) {
            context.commit('delRoom', id)
        },
    }
}
