package mobile_api_controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"

	"github.com/astaxie/beego"
)

type LoginAPIController struct {
	MobileBaseAPIController
}

// /m/api/login/pwd [post] LoginByPwd
// @param mobile:string
// @param password:string
func (this *LoginAPIController) LoginByPwd() {
	mobile := this.GetString("mobile")
	pwd := this.GetString("password")
	//var mobile = "15089497668"
	//var pwd = "123456"
	if len(mobile) == 0 || len(pwd) == 0 || utils.CellPhoneRegexp().MatchString(mobile) == false {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	ip := utils.GetIP(this.Ctx.Request)
	ssoDomain := beego.AppConfig.String("sso_domain")
	//ssoDomain := "http://localhost:8091"
	api := ssoDomain + "/m/login/pwd"
	values := make(url.Values)
	values.Set("mobile", mobile)
	values.Set("password", pwd)
	values.Set("app_type", "3")
	values.Set("ip", ip)
	resp, requestErr := http.PostForm(api, values)

	if requestErr != nil {
		utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	defer resp.Body.Close()
	body, ioErr := ioutil.ReadAll(resp.Body)
	if ioErr != nil {
		utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	var respJSON map[string]interface{}
	utils.InfoLog(string(body))
	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
		utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	if respJSON["state"].(float64) != 1 {
		msg := respJSON["msg"].(string)
		utils.ErrorLog("SSO登录接口请求失败: %v", msg)
		if int(respJSON["code"].(float64)) == 609 {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
			return
		}
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else {
		utils.SuccessLog("SSO登录成功")
		// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
		userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
		userJSONBytes, _ := json.Marshal(userJSON)
		var adminUser models.AdminUser
		if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
			utils.ErrorLog("解析管理员失败：%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		var org models.Org
		if respJSON["data"].(map[string]interface{})["org"] != nil {
			orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
			orgJSONBytes, _ := json.Marshal(orgJSON)
			if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
				utils.ErrorLog("解析机构失败：%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
		}

		var app models.OrgApp

		if respJSON["data"].(map[string]interface{})["app"] != nil {
			appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
			appJSONBytes, _ := json.Marshal(appJSON)
			if err := json.Unmarshal(appJSONBytes, &app); err != nil {
				utils.ErrorLog("解析应用失败：%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
		}

		var appRole models.App_Role

		if respJSON["data"].(map[string]interface{})["app_role"] != nil {
			appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
			appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
			if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
				utils.ErrorLog("解析AppRole失败：%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
		}

		var subscibe models.ServeSubscibe
		if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
			subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
			subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
			if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
				utils.ErrorLog("解析Subscibe失败：%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

		}

		//service.GetOrgSubscibeState(&subscibe)
		templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
		mobileAdminUserInfo := &MobileAdminUserInfo{
			AdminUser:    &adminUser,
			Org:          &org,
			App:          &app,
			AppRole:      &appRole,
			Subscibe:     &subscibe,
			TemplateInfo: &templateInfo,
		}
		//设置seesion
		this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)

		//设置cookie
		mobile = mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
		token := utils.GenerateLoginToken(mobile)
		expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
		this.Ctx.SetCookie("token_cookie", token, expiration, "/")

		var configList interface{}
		var dict_config_list interface{}

		var FiledList []*models.FiledConfig

		if org.Id > 0 {
			dict_config_list, _ = service.GetDictConfigList(org.Id)

			configList, _ = service.GetConfigList(org.Id)
			FiledList, _ = service.FindFiledByOrgId(org.Id)
		}
		if len(FiledList) == 0 {
			var err error
			if org.Id > 0 {
				err = service.BatchInsertFiledConfig(org.Id)
				if err == nil {
					FiledList, _ = service.FindFiledByOrgId(org.Id)
				} else {
					utils.ErrorLog("字段批量插入失败：%v", err)
				}
			} else {
				FiledList = make([]*models.FiledConfig, 0)
			}
		}
		//产寻该机构是否有收缩压和舒张压
		pressure, err := service.GetDefaultSystolicPressure(org.Id)
		fmt.Println(err)
		if len(pressure) == 0 {
			err = service.BathInsertQualityControlTwo(org.Id)
		} else {
			utils.ErrorLog("字段批量插入失败：%v", err)
		}

		//批量插入质控达标统计配置
		major, requestErr := service.GetInspectionMajor(org.Id)
		if len(major) == 0 {
			QualityeList, err := service.FindQualityByOrgId(org.Id)
			if len(QualityeList) == 0 {
				err = service.BatchInsertQualityControl(org.Id)
			} else {
				utils.ErrorLog("字段批量插入失败：%v", err)
			}

			//批量插入检验检查统计配置
			InspectionList, err := service.FindeInspectionByOrgId(org.Id)
			if len(InspectionList) == 0 {
				err = service.BatchInspectionConfiguration(org.Id)
			} else {
				utils.ErrorLog("字段批量插入失败：%v", err)
			}
		} else {
			utils.ErrorLog("字段批量插入失败：%v", requestErr)
		}

		this.ServeSuccessJSON(map[string]interface{}{
			"admin": adminUser,
			"user":  appRole,
			"org":   org,
			"template_info": map[string]interface{}{
				"id":          templateInfo.ID,
				"org_id":      templateInfo.OrgId,
				"template_id": templateInfo.TemplateId,
			},
			"config_list":      configList,
			"dict_config_list": dict_config_list,

			"filed_list": FiledList,
		})
	}
}

// /m/api/login/code [post] LoginByCode
func (this *LoginAPIController) LoginByCode() {

}
