package new_mobile_api_controllers

import (
	"Xcx_New/controllers/mobile_api_controllers"
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
)

type ForgetPwdController struct {
	mobile_api_controllers.MobileBaseAPIController
}

func (this *ForgetPwdController) ModifyPassword() {
	mobile := this.GetString("mobile")
	code := this.GetString("code")
	password := this.GetString("password")
	checkErr := this.checkParams(mobile, code, password)
	if checkErr != nil {
		this.ServeFailJSONWithSGJErrorCode(checkErr.Code)
		return
	}

	adminUser, _ := service.GetValidAdminUserByMobileReturnErr(mobile)

	modifyErr := service.ModifyPassword(adminUser.Id, password)
	if modifyErr != nil {
		utils.ErrorLog("修改mobile=%v的用户的密码时失败: %v", mobile, modifyErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	} else {
		// 修改成功后验证码就要使其失效
		redisClient := service.RedisClient()
		defer redisClient.Close()
		redisClient.Del("code_msg_" + mobile)

		ip := utils.GetIP(this.Ctx.Request)
		ssoDomain := beego.AppConfig.String("sso_domain")
		api := ssoDomain + "/m/login/pwd"
		values := make(url.Values)
		values.Set("mobile", mobile)
		values.Set("password", password)
		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 := &mobile_api_controllers.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_configList interface{}

			var FiledList []*models.FiledConfig

			if org.Id > 0 {
				configList, _ = service.GetConfigList(org.Id)
				dict_configList, _ = service.GetDictConfigList(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)
				}
			}

			if org.Id > 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_configList,

				"filed_list": FiledList,
			})
		}

		//this.ServeSuccessJSON(map[string]interface{}{
		//	"msg":"修改成功",
		//})
		return
	}
}

func (this *ForgetPwdController) checkParams(mobile string, code string, password string) *enums.SGJError {
	if utils.CellPhoneRegexp().MatchString(mobile) == false {
		return &enums.SGJError{Code: enums.ErrorCodeMobileFormat}
	}
	if len(code) == 0 {
		return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong}
	}
	if len(password) == 0 {
		return &enums.SGJError{Code: enums.ErrorCodePasswordEmpty}
	}
	if service.IsMobileRegister(mobile) == false {
		return &enums.SGJError{Code: enums.ErrorCodeMobileNotExit}
	}
	redisClient := service.RedisClient()
	defer redisClient.Close()
	cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
	if cache_code != code {
		return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong}
	}
	return nil
}
