import { fetch, post, corePost } from '@/api/http'
import jwtDecode from 'jwt-decode'
import config from '@/store/module/config'
import ClassMgmt from './classMgmt'
import talMgmt from './talMgmt'
// import cloudApi from '../store/api/index'
import schoolSetting from './schoolSetting'
import totalAnalysis from './totalAnalysis'
import stuAccount from './stuAccount'
import syllabus from './syllabus'
import knowledge from './knowledge'
import teachContent from './teachContent'
import blob from './blob'
import courseMgmt from './courseMgmt'
import login from './login'
import schoolList from './schoolList'
import newEvaluation from './newEvaluation'
import learnActivity from './learnActivity'
import questionnaire from './questionnaire'
import teachMgmt from './teachMgmt'
import schoolUser from './schoolUser'
import accessToken from './accessToken'
import studentWeb from './studentWeb'
import regist from './regist'
import forgetPW from './forgetPW'
import classroom from './classroom'
import serviceDriveAuth from './serviceDriveAuth'
import spaceAuth from './spaceAuth'
import room from './room'
import mark from './mark'
import openMgmt from './openMgmt';

export default {
    accessToken,
    learnActivity,
    studentWeb,
	questionnaire,
    ClassMgmt,
    stuAccount,
    syllabus,
    knowledge,
    schoolSetting,
    totalAnalysis,
    talMgmt,
    teachContent,
    // cloudApi,
    blob,
    courseMgmt,
    newEvaluation,
    login,
    schoolList,
    teachMgmt,
    schoolUser,
    regist,
    forgetPW,
    classroom,
    serviceDriveAuth,
    spaceAuth,
    room,
    mark,
    openMgmt,

    // 获取登录跳转链接
    getLoginLink: function (data) {
        return post('api/login/login', data)
    },
    // 验证登录
    checkLogin: function (data) {
        return post('api/login/CheckLogin', data)
    },
    // 获取登录人员角色列表
    getLoginRoles: function (data) {
        return post('api/role/GetLoginRoles', data)
    },
    // 查找地区对应学校列表
    getSchoolList: function (data) {
        return post('api/School/getSchool', data)
    },
    // 根据当前登录用户获取已授权的AI智慧学校
    getAuthSchool: function (data) {
        return post('api/School/AuthorizedAISchool', data)
    },
    // 获取全部科目
    FindSubjectsByDict: function (data) {
        return post('api/subject/FindSubjectsByDict', data)
    },
    // 获取当前学校全部科目
    FindSchoolSubjectsByDict: function (data) {
        return post('api/subject/FindSchoolSubjectsByDict', data)
    },
    // 获取当前学校全部册别
    FindSchoolVolumesByDict: function (data) {
        return post('api/volume/FindSchoolVolumesByDict', data)
    },
    // 获取当前学校全部学段
    FindSchoolPeriodsByDict: function (data) {
        return post('api/period/FindSchoolPeriodsByDict', data)
    },
    // 获取当前学校全部年级
    FindSchoolGradesByDict: function (data) {
        return post('api/grade/FindSchoolGradesByDict', data)
    },
    // 获取当前学校全部学期
    FindSchoolTermsByDict: function (data) {
        return post('api/term/FindSchoolTermsByDict', data)
    },


    // 获取登录人员身份信息
    getLoginClaim: function (data) {
        return post('api/role/GetLoginClaim', data)
    },

    // 新建习题保存到题库
    SaveItemBank: function (data) {
        return post('api/evaluation/ItemBank', data)
    },

    // 新建试卷到试卷库
    SaveTestPaper: function (data) {
        return post('api/Evaluation/testPaper', data)
    },

    // 新建试卷到试卷库
    SaveAnalyzeHtml: function (data) {
        return post('/import/parse-html', data)
    },

    // 获取所有学校信息
    GetAllSchool: function (data) {
        return post('api/school/GetAllSchool', data)
    },

    // 取得所有學校(只取基本資料)
    GetAllSchoolBaesInfo: function (data) {
        return post('/school/init/get-all-school-base', data)
    },

    // 根据条件获取学段
    FindPeriodsByDict: function (data) {
        return post('api/period/FindPeriodsByDict', data)
    },

    // 根据条件获取年级
    FindGradesByDict: function (data) {
        return post('api/grade/FindGradesByDict', data)
    },
    // 根据条件获取学科
    FindSubjectsByDict: function (data) {
        return post('api/subject/FindSubjectsByDict', data)
    },


    /*
      *评测
      */
    // 上传图片
    UploadFile: function (data) {
        return post('/api/file/uploadFile', data)
    },

    /**
     * 通用查询接口
     */
    FindCollection: function (data) {
        return post('/api/Common/FindCollection', data)
    },

    /**
     * 發送驗證簡訊
     * @param {String} applyType - 寄信類型(email, phone)
     * @param {String} to - 寄信位置
     * @param {String} lang - 要傳送的語言代碼，請用標準zh-CN、zh-TW、en-US
     * @param {Boolean} hasUser - true，代表必須存在用戶，才能發送，false，代表用戶必須不存在，才能發送
     * @param {Number} country - 手機區碼，無須+號(有phone為必填)
     */
    SendPinCode: function(item) {
        return new Promise((resolve) => {
            let srvAdr = localStorage.getItem('srvAdr')
            let url = config.state[srvAdr].coreAPIUrl
            
            let data = {
                'to': item.to.toString(),
                'lang': item.lang,
                'HasUser': item.hasUser,
            }

            if(item.applyType == 'phone'){
                data.country= item.country.toString()
                url += '/service/sandsms/pin'
            } else {
                url += '/service/sandmail/pin'
            }
            corePost(url, data).then( res => {
                resolve(res)
            },err => {
                console.log(err)
            })
        })
    },

    /**
     * 組合呼叫第三方的網址
     * @param {String} provider - (必要)
     * @param {String} url - (必要)
     * @returns {String} - 網址
     */
    BuildOauthUrl: async function(provider, url){
        return new Promise((resolve) => {
            let result = ''
            let redirect_uri = encodeURIComponent(url)
            switch (provider) {
                case 'facebook':
                    result = 'https://www.facebook.com/v7.0/dialog/oauth?scope=public_profile,email&redirect_uri=' + redirect_uri + '&response_type=code&client_id=1382704845111595&display=popup&state=facebook'
                    break;
                case 'google':
                    result = 'https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&redirect_uri=' + redirect_uri + '&response_type=code&client_id=30604537950-2e6eojbqt5k1kjg43jdvdq6g3gp0eo33.apps.googleusercontent.com&display=popup&state=google'
                    break;
                case 'wechat':
                    result = 'https://open.weixin.qq.com/connect/qrconnect?appid=wx207be4d5a37eca4a&redirect_uri='+ redirect_uri +'&response_type=code&scope=snsapi_login&state=wechat#wechat_redirect'
                    break;
            }

            resolve(result)
        })
    },
    /**
     * 請求雲端協助第三方登入
     * @param {String} grant_type
     * @param {String} code
     * @param {String} redirect_uri
     */
    OauthLogin: function(grant_type, code, redirect_uri){
        return new Promise((resolve) => {
            let srvAdr = localStorage.getItem('srvAdr')
            let url = config.state[srvAdr].coreAPIUrl
            let nonceStr = 'habook'  // 檢查項目
            let data = {
            'client_id': config.state[srvAdr].clientID,
            'grant_type': grant_type,
            'nonce': nonceStr,
            'open_code': code,
            'redirect_uri': redirect_uri
            }

            corePost(url+'/oauth2/login', data).then( res => {
                if(res.error){
                    resolve(res)
                } else {
                    let t_data = jwtDecode(res.id_token)
                    if(nonceStr === t_data.nonce){
                        resolve(res)
                    } else {
                        resolve({error: 'nonce'})
                    }
                }
            },err => {
                console.log(err)
                if(err.status != 200){
                    resolve({error: 'Bad Request'})
                }
            })
        })
    },
    /**
     * 大雲快速登入
     * @param {String} code
     */
    SSOLogin: function(code){
        return new Promise((resolve, reject) => {
            let srvAdr = localStorage.getItem('srvAdr')
            let url = config.state[srvAdr].coreAPIUrl
            let nonceStr = 'habook'  // 檢查項目
            let data = {
            'grant_type': 'authorization_code',
            'client_id': config.state[srvAdr].clientID,
            'code': code,
            'nonce': nonceStr
            }

            corePost(url+'/oauth2/token', data).then( res => {
                resolve(res)
            },err => {
                console.log(err)
                if(err.status != 200){
                    resolve({error: 'Bad Request'})
                }
            })
        })
    },
    /**
     * 數據中心當前所有學校名單
     */
    getSchoolList: function () {
        return post('/teacher/init/get-school-list')
    },
}
