package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"encoding/json"
	"reflect"
	"time"

	"github.com/astaxie/beego"
)

type OrgInfoApiController struct {
	BaseAuthAPIController
}

func OrgInfoApiRegistRouters() {
	beego.Router("/api/orginfo/getinfo", &OrgInfoApiController{}, "get:GetOrgInfo")
	beego.Router("/api/orginfo/savegallery", &OrgInfoApiController{}, "post:SaveOrgGallery")
	beego.Router("/api/orginfo/deletegallery", &OrgInfoApiController{}, "delete:DeleteOrgGallery")
	beego.Router("/api/orginfo/edit", &OrgInfoApiController{}, "post:EditOrgInfo")

}

func (c *OrgInfoApiController) GetOrgInfo() {

	adminUserInfo := c.GetAdminUserInfo()

	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
	provinces, _ := service.GetDistrictsByUpid(0)
	var citys []*models.District
	var districts []*models.District
	if orgInfo.Province > 0 {
		citys, _ = service.GetDistrictsByUpid(orgInfo.Province)
	}
	if orgInfo.City > 0 {
		districts, _ = service.GetDistrictsByUpid(orgInfo.City)
	}

	orgtypes, _ := service.GetOrgTypes()

	illness, _ := service.GetIllnessList()

	c.ServeSuccessJSON(map[string]interface{}{
		"orginfo":   orgInfo,
		"provinces": provinces,
		"citys":     citys,
		"districts": districts,
		"orgtypes":  orgtypes,
		"illness":   illness,
	})
	return
}

func (c *OrgInfoApiController) EditOrgInfo() {
	adminUserInfo := c.GetAdminUserInfo()

	tempOrg, _ := service.GetOrgById(adminUserInfo.CurrentOrgId)

	if tempOrg != nil && adminUserInfo.AdminUser.Id != tempOrg.Creator {
		c.ServeFailJsonSend(enums.ErrorCodePermissionDenied, "权限不足")
		return
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
	org := *orgInfo

	if dataBody["org_name"] == nil || reflect.TypeOf(dataBody["org_name"]).String() != "string" {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:机构名称")
		return
	}
	orgName, _ := dataBody["org_name"].(string)
	if len(orgName) == 0 {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "机构名称不能为空")
		return
	}

	org.OrgName = orgName

	if dataBody["contact_name"] == nil || reflect.TypeOf(dataBody["contact_name"]).String() != "string" {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:联系人姓名")
		return
	}
	contactName, _ := dataBody["contact_name"].(string)
	if len(contactName) == 0 {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "联系人姓名不能为空")
		return
	}
	org.ContactName = contactName

	// if dataBody["org_short_name"] == nil || reflect.TypeOf(dataBody["org_short_name"]).String() != "string" {
	// 	c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:商家简称")
	// 	return
	// }
	// orgShortName, _ := dataBody["org_short_name"].(string)
	// if len(orgShortName) == 0 {
	// 	c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "商家简称不能为空")
	// 	return
	// }
	org.OrgShortName = orgName

	if dataBody["org_introduction"] == nil || reflect.TypeOf(dataBody["org_introduction"]).String() != "string" {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:机构介绍")
		return
	}
	orgIntroduction, _ := dataBody["org_introduction"].(string)
	if len(orgIntroduction) == 0 {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "机构介绍不能为空")
		return
	}
	org.OrgIntroduction = orgIntroduction

	if dataBody["org_logo"] == nil || reflect.TypeOf(dataBody["org_logo"]).String() != "string" {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:机构头像")
		return
	}
	orgLogo, _ := dataBody["org_logo"].(string)
	if len(orgLogo) == 0 {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "机构头像不能为空")
		return
	}
	org.OrgLogo = orgLogo

	if dataBody["province"] != nil || reflect.TypeOf(dataBody["province"]).String() == "float64" {
		province := int64(dataBody["province"].(float64))
		org.Province = province
	}

	if dataBody["city"] != nil || reflect.TypeOf(dataBody["city"]).String() == "float64" {
		city := int64(dataBody["city"].(float64))
		org.City = city
	}

	if dataBody["district"] != nil || reflect.TypeOf(dataBody["district"]).String() == "float64" {
		district := int64(dataBody["district"].(float64))
		org.District = district
	}

	if dataBody["address"] != nil || reflect.TypeOf(dataBody["address"]).String() == "string" {
		address, _ := dataBody["address"].(string)
		org.Address = address
	}

	if dataBody["org_type"] != nil || reflect.TypeOf(dataBody["org_type"]).String() == "float64" {
		orgType := int64(dataBody["org_type"].(float64))
		org.OrgType = orgType
	}

	if dataBody["telephone"] != nil || reflect.TypeOf(dataBody["telephone"]).String() == "string" {
		telephone, _ := dataBody["telephone"].(string)
		org.Telephone = telephone
	}

	if dataBody["operating_state"] != nil || reflect.TypeOf(dataBody["operating_state"]).String() == "float64" {
		operatingState := int64(dataBody["operating_state"].(float64))
		org.OperatingState = operatingState
	}

	if dataBody["business_week"] != nil || reflect.TypeOf(dataBody["business_week"]).String() == "string" {
		businessWeek, _ := dataBody["business_week"].(string)
		org.BusinessWeek = businessWeek
	}

	if dataBody["business_time"] != nil || reflect.TypeOf(dataBody["business_time"]).String() == "string" {
		businessTime, _ := dataBody["business_time"].(string)
		org.BusinessTime = businessTime
	}
	if dataBody["illness"] != nil || reflect.TypeOf(dataBody["illness"]).String() == "string" {
		illness, _ := dataBody["illness"].(string)
		org.Illness = illness
	}

	timeNow := time.Now().Unix()
	org.ModifyTime = timeNow
	org.OrgGallery = nil
	err = service.UpdateOrgInfo(&org)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	orgInfo.OrgName = orgName
	orgInfo.OrgShortName = orgName
	orgInfo.OrgIntroduction = orgIntroduction
	orgInfo.OrgLogo = orgLogo
	orgInfo.Province = org.Province
	orgInfo.District = org.District
	orgInfo.City = org.City
	orgInfo.OrgType = org.OrgType
	orgInfo.Telephone = org.Telephone
	orgInfo.OperatingState = org.OperatingState
	orgInfo.BusinessWeek = org.BusinessWeek
	orgInfo.BusinessTime = org.BusinessTime
	orgInfo.Illness = org.Illness
	orgInfo.ContactName = org.ContactName

	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return
}

func (c *OrgInfoApiController) SaveOrgGallery() {
	adminUserInfo := c.GetAdminUserInfo()

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if dataBody["type"] == nil || reflect.TypeOf(dataBody["type"]).String() != "float64" {
		utils.ErrorLog("type")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	galleryType := int64(dataBody["type"].(float64))
	if galleryType != 1 && galleryType != 2 {
		utils.ErrorLog("galleryType != 1&&2")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if dataBody["url"] == nil || reflect.TypeOf(dataBody["url"]).String() != "string" {
		utils.ErrorLog("url")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	url, _ := dataBody["url"].(string)
	if len(url) == 0 {
		utils.ErrorLog("len(url) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	timeNow := time.Now().Unix()
	var gallery models.OrgGallery
	gallery.Type = galleryType
	gallery.Url = url
	gallery.OrgId = adminUserInfo.CurrentOrgId
	gallery.Status = 1
	gallery.Ctime = timeNow
	gallery.Mtime = timeNow
	err = service.CreateOrgGalleryItem(&gallery)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
	orgInfo.OrgGallery = append(orgInfo.OrgGallery, &gallery)
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return

}

func (c *OrgInfoApiController) DeleteOrgGallery() {
	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	err := service.DeleteOrgGalleryItem(id)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
	for index, item := range orgInfo.OrgGallery {
		if item.ID == id {
			orgInfo.OrgGallery = append(orgInfo.OrgGallery[:index], orgInfo.OrgGallery[index+1:]...)
		}
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return

}