import {
	post,
	corePost
} from '@/api/http'
import store from '@/store'
import jwtDecode from 'jwt-decode'

export default {
	// 登入Account驗證
	verification: function(item) {
		return new Promise((resolve, reject) => {
			let srvAdr = localStorage.getItem('srvAdr')
			let url = store.state.config[srvAdr].coreAPIUrl
			let nonceStr = 'habook' // 檢查項目
			if (item.id.indexOf(0) == 0) item.id = item.id.substr(1) //開頭有0要去0
			let data = {
				'client_id': store.state.config[srvAdr].clientID,
				'grant_type': 'account',
				'account': item.id,
				'password': item.pass,
				'nonce': nonceStr
			}
			corePost(url + '/oauth2/login', data).then(res => {
				if (res.error) {
					reject(res)
				} else {
					let t_data = jwtDecode(res.id_token)
					if (nonceStr === t_data.nonce) {
						resolve(res)
					} else {
						reject({
							error: 'nonce'
						})
					}
				}
			}, err => {
				reject(err)
			})
		})
	},
	// 老師資料初始化 
	getTeacherInfo: function(data) {
		return post('/teacher/init/get-teacher-info', data)
	},
	// 取得老師在該學校的資料
	getTeacherSchoolInfo: function(data) {
		return post('/teacher/init/get-school-info', data)
	},
	// 學生登入
	studLoginbyIES: function(data) {
		return post('/student/login', data)
	},
	// 固定登入流程
	loginIES: function(item, schoolcode) {
		return new Promise(async (resolve, reject) => {
			// 設定Token 和 保存時間
			localStorage.setItem("id_token", item.id_token)
			localStorage.setItem("access_token", item.access_token)
			localStorage.setItem("expires_in", item.expires_in)
			// 輸出暫存
			let result;

			// 取得登入者基本資訊
			let id_token = item.id_token
			let t_Data = jwtDecode(item.id_token)

			// 取得使用者的個人資料
			// 以IDToken取得初始化老師，並取得權限及blob資訊
			await this.getTeacherInfo({
				id_token: id_token
			}).then(res => {
				// 儲存大雲Token
				localStorage.setItem("auth_token", res.auth_token)
				store.dispatch('user/setUserProfile', res)
				result = res
			}).catch(err => {
				console.log(err)
			})
			let hasJoinSchool = result.schools && result.schools.length && result.schools.filter(i => i.status === 'join').length
			let joinSchools = hasJoinSchool ? result.schools.filter(i => i.status === 'join') : []
			let defaultschool = schoolcode != '' ? schoolcode : result.defaultschool ? result.defaultschool : (joinSchools.length ? joinSchools[0].schoolId : null)
			let authByUser = jwtDecode(result.auth_token)
			let info = {
				id: t_Data.sub,
				name: authByUser.name,
				roles: authByUser.roles,
				permissions: authByUser.permissions == null ? [] : authByUser.permissions,
				picture: t_Data.picture ? t_Data.picture : ''
			}

			if (defaultschool != null) {
				// 取得使用者的在該學校的設定檔
				await this.getTeacherSchoolInfo({
					id_token: id_token,
					school_code: defaultschool
				}).then(res => {
					// 沒有錯誤的話
					if (!res.error) {
						console.log(res)
						// 儲存大雲Token
						localStorage.setItem("auth_token", res.auth_token)
						store.dispatch('user/setSchoolCode', defaultschool)
						store.dispatch('user/setSchoolProfile', res)
						result = res
					}

				}).catch(err => {
					console.log(err)
				})

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

			resolve(info)
		})
	},
	studLogin: function(item) { // 學生登入
		return new Promise(async (resolve, reject) => {

			let result;
			let data = {
				school_code: item.schoolCode,
				id: item.id,
				pw: item.pw
			}

			let error = '';

			// 進行API呼叫
			await this.studLoginbyIES(data).then(res => {
				if (res.error == 0) {
					// 儲存大雲Token
					localStorage.setItem("auth_token", res.auth_token)
					store.dispatch('user/setSchoolCode', data.school_code)
					store.dispatch('user/setStudentProfile', res)
					result = res
				} else {
					error = res
				}
			}).catch(err=>{
                error = err
            })

			if(error == ''){
				let auth = jwtDecode(result.auth_token)
				// 一樣要存auth_token
				localStorage.setItem("auth_token", result.auth_token)
	
				// 預計返回內容
				let info = {
					id: result.id,
					roles: ['student'],
					permissions: auth.permissions == null ? [] : auth.permissions,
					picture: ''
				}
	
				resolve(info)
			} else {
				reject(error)
			}		
		})
	},
	// 取得學校名稱
	getSchoolName: function(item) {
		return new Promise((resolve) => {
			if (item.schoolCode == 'ydzt') {
				resolve({
					code: item.schoolCode,
					name: '成都師範銀都紫藤小學'
				})
			} else {
				resolve({
					code: '',
					name: ''
				})
			}
		})
	}
}
