package overseas_custom

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/overseas_custom"
	"hongze/hz_crm_api/utils"
	"time"
)

// @Title 获取海外客户列表数据
// @Description 获取海外客户列表数据
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Keywords	query	string	false	"关键词：客户名称/社会信用码/联系人手机号/邮箱"
// @Param   CompanyStatus	query	string	false	"状态：全部,正式,试用,关闭"
// @Param   SellerId	query	int		false	"销售ID"
// @Param   CustomType	query	int		false	"1:海外客户,2:隐藏客户"
// @Param   SortField	query	string		false	"排序字段:ViewTotal,RoadShowTotal,CreateTime"
// @Param   SortDesc	query	int		false	"1:降序,默认,2:升序"
// @Param   OverseasLabel	query	int		false	"海外客户试用子标签：1未分类、2  推进、3 跟踪、4 预备、"
// @Success 200 {object} models.EnglishCompanyPageListResp
// @router /custom/list [get]
func (this *OverseasCustomController) CustomList() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keywords := this.GetString("Keywords", "")
	sellerId, _ := this.GetInt("SellerId", 0)
	companyStatus := this.GetString("CompanyStatus")
	sortField := this.GetString("SortField")
	sortDesc, _ := this.GetInt("SortDesc")
	overseasLabel, _ := this.GetInt("OverseasLabel", 0)
	customType, _ := this.GetInt("CustomType", 0)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	page := paging.GetPaging(currentIndex, pageSize, 0)

	resp := new(overseas_custom.CustomListResp)

	obj := new(overseas_custom.Custom)

	var condition string
	var pars []interface{}
	if keywords != "" {
		k := "%" + keywords + "%"
		enCompanyIds, e := overseas_custom.GetEnCompanyIdsByKeyword(k)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取英文客户IDs失败, Err: " + e.Error()
			return
		}

		//获取中文客户

		companyIds, err := obj.GetCompanyIdsByKeyword(k)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取客户IDs失败, Err: " + err.Error()
			return
		}

		companyIds = append(companyIds, enCompanyIds...)

		if len(companyIds) > 0 {
			condition += fmt.Sprintf(` AND m.company_id IN (%s) `, utils.GetOrmInReplace(len(companyIds)))
			pars = append(pars, companyIds)
		}

		if len(companyIds) <= 0 {
			list := make([]*overseas_custom.Custom, 0)
			resp.Paging = page
			resp.List = list
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = resp
			return
		}
	}
	if sellerId > 0 {
		condition += ` AND m.seller_id=? `
		pars = append(pars, sellerId)
	}

	if overseasLabel > 0 {
		condition += ` AND m.overseas_label=? `
		pars = append(pars, overseasLabel)
	}

	if customType == 2 {
		condition += ` AND m.is_hide=? `
		pars = append(pars, 1)
	} else {
		condition += ` AND m.is_hide=? `
		pars = append(pars, 0)
	}

	if companyStatus == "试用" {
		condition += ` AND m.overseas_status='试用'`
	} else if companyStatus == "正式" {
		condition += ` AND m.overseas_status='正式' `
	} else if companyStatus == "关闭" {
		condition += ` AND m.overseas_status='关闭' `
	}

	total, err := obj.GetCustomListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败, Err: " + err.Error()
		return
	}

	list, err := obj.GetCustomList(condition, pars, sortField, startSize, pageSize, sortDesc)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败, Err: " + err.Error()
		return
	}

	for _, v := range list {
		if v.Source == 1 && v.OverseasStatus != "" {
			v.CompanyStatus = v.OverseasStatus
		}
	}
	page = paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	resp.List = list

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 客户隐藏
// @Description 客户隐藏
// @Param	request  body  overseas_custom.CustomHideReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /custom/hide [post]
func (this *OverseasCustomController) CustomHide() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req overseas_custom.CustomHideReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CompanyId <= 0 {
		br.Msg = "参数错误！"
		return
	}

	//if req.CompanyId > utils.EnCompanyIdStep {
	//	req.CompanyId = req.CompanyId - utils.EnCompanyIdStep
	//}

	obj := new(overseas_custom.Custom)
	item, err := obj.GetCustomByCompanyId(req.CompanyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "隐藏失败,客户信息不存在！"
			br.ErrMsg = "隐藏失败，Err:" + err.Error()
			return
		}
		br.Msg = "隐藏失败！"
		br.ErrMsg = "隐藏失败，Err:" + err.Error()
		return
	}
	//是否隐藏:0:不隐藏,1:隐藏
	var isHide int
	if item.IsHide == 1 {
		isHide = 0
	} else {
		isHide = 1
	}

	if req.CompanyId > 1000000 {
		enCompanyObj := new(models.EnglishCompany)
		// 更新客户
		nowTime := time.Now().Local()
		enCompanyObj.CompanyId = req.CompanyId - utils.EnCompanyIdStep
		enCompanyObj.IsHide = isHide
		enCompanyObj.ModifyTime = nowTime
		updateCols := []string{"IsHide", "ModifyTime"}
		if err = enCompanyObj.Update(updateCols); err != nil {
			br.Msg = "隐藏失败"
			br.ErrMsg = "更新英文客户隐藏状态失败, Err:" + err.Error()
			return
		}
	} else {
		obj := new(overseas_custom.Custom)

		updateParams := make(map[string]interface{})
		updateParams["is_hide"] = isHide
		whereParam := make(map[string]interface{})
		whereParam["company_id"] = req.CompanyId

		err := obj.UpdateCompany(updateParams, whereParam)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置客户标签状态失败, Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "隐藏成功"
}

// @Title 客户状态设置
// @Description 客户状态设置
// @Param	request  body  overseas_custom.CustomHideReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /custom/status_set [post]
func (this *OverseasCustomController) CustomStatusSet() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req overseas_custom.CustomHideReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CompanyId <= 0 {
		br.Msg = "参数错误！"
		return
	}

	obj := new(overseas_custom.Custom)
	item, err := obj.GetCustomByCompanyId(req.CompanyId)
	if err != nil {
		br.Msg = "设置失败！"
		br.ErrMsg = "设置失败，Err:" + err.Error()
		return
	}
	//是否隐藏:0:不隐藏,1:隐藏
	var overseasStatus string
	var resetBtn int

	if item.OverseasStatus == "正式" && item.ResetBtn == 2 { //重置，获取当前客户的状态
		overseasStatus = item.CompanyStatus
		resetBtn = 1
	} else if item.OverseasStatus == "试用" && (item.ResetBtn == 1 || item.ResetBtn == 0) { //转正式，获取当前客户的状态
		overseasStatus = "正式"
		resetBtn = 2
	}

	if req.CompanyId > 1000000 {
		enCompanyObj := new(models.EnglishCompany)
		// 更新客户
		nowTime := time.Now().Local()
		enCompanyObj.CompanyId = req.CompanyId - utils.EnCompanyIdStep
		enCompanyObj.OverseasStatus = overseasStatus
		enCompanyObj.ModifyTime = nowTime
		enCompanyObj.ResetBtn = resetBtn //转正式和重置按钮:同步过来默认为0:显示转正式为1:显示重置为2
		updateCols := []string{"OverseasStatus", "ResetBtn", "ModifyTime"}
		if err = enCompanyObj.Update(updateCols); err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "更新英文客户转正式状态失败, Err:" + err.Error()
			return
		}
	} else {
		obj := new(overseas_custom.Custom)

		updateParams := make(map[string]interface{})
		updateParams["overseas_status"] = overseasStatus
		updateParams["reset_btn"] = resetBtn
		updateParams["modify_time"] = time.Now()

		whereParam := make(map[string]interface{})
		whereParam["company_id"] = req.CompanyId

		err := obj.UpdateCompany(updateParams, whereParam)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置客户标签状态失败, Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 客户子标签设置
// @Description 客户子标签设置
// @Param	request  body  overseas_custom.CustomOverseasLabelSetReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /custom/overseas_label_set [post]
func (this *OverseasCustomController) CustomOverseasLabelSet() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	//海外客户试用子标签：1未分类、2  推进、3 跟踪、4 预备、
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req overseas_custom.CustomOverseasLabelSetReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CompanyId <= 0 {
		br.Msg = "参数错误！"
		return
	}

	nowTime := time.Now().Local()
	if req.CompanyId > 1000000 {
		enCompanyObj := new(models.EnglishCompany)
		// 更新客户
		enCompanyObj.CompanyId = req.CompanyId - utils.EnCompanyIdStep
		enCompanyObj.OverseasLabel = req.OverseasLabel
		enCompanyObj.ModifyTime = nowTime
		updateCols := []string{"OverseasLabel", "ModifyTime"}
		if err := enCompanyObj.Update(updateCols); err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置英文客户标签状态失败, Err:" + err.Error()
			return
		}
	} else {
		obj := new(overseas_custom.Custom)

		updateParams := make(map[string]interface{})
		updateParams["overseas_label"] = req.OverseasLabel
		updateParams["modify_time"] = time.Now()

		whereParam := make(map[string]interface{})
		whereParam["company_id"] = req.CompanyId
		whereParam["product_id"] = 1

		err := obj.UpdateCompanyProduct(updateParams, whereParam)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置客户标签状态失败, Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "设置成功"
}

// @Title 海外客户统计数据
// @Description 海外客户统计数据
// @Param   Keywords	query	string	false	"关键词：客户名称/社会信用码/联系人手机号/邮箱"
// @Param   SellerId	query	int		false	"销售ID"
// @Success 200 {object} models.EnglishCompanyPageListResp
// @router /custom/statistics [get]
func (this *OverseasCustomController) CustomStatistics() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	keywords := this.GetString("Keywords", "")
	sellerId, _ := this.GetInt("SellerId", 0)
	customType, _ := this.GetInt("CustomType", 0)

	obj := new(overseas_custom.Custom)

	var condition string
	var pars []interface{}
	if keywords != "" {
		k := "%" + keywords + "%"
		enCompanyIds, e := overseas_custom.GetEnCompanyIdsByKeyword(k)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取英文客户IDs失败, Err: " + e.Error()
			return
		}

		//获取中文客户

		companyIds, err := obj.GetCompanyIdsByKeyword(k)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取客户IDs失败, Err: " + err.Error()
			return
		}

		companyIds = append(companyIds, enCompanyIds...)

		if len(companyIds) > 0 {
			condition += fmt.Sprintf(` AND m.company_id IN (%s) `, utils.GetOrmInReplace(len(companyIds)))
			pars = append(pars, companyIds)
		} else {
			statisticsDataStatusList := make([]*overseas_custom.CustomTotal, 0)

			var statusArr = [3]string{"试用", "正式", "关闭"}

			for _, v := range statusArr {
				item := new(overseas_custom.CustomTotal)
				item.CompanyStatus = v
				statisticsDataStatusList = append(statisticsDataStatusList, item)
			}

			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = statisticsDataStatusList
			return
		}
	}
	if sellerId > 0 {
		condition += ` AND m.seller_id=? `
		pars = append(pars, sellerId)
	}

	if customType == 2 {
		condition += ` AND m.is_hide=? `
		pars = append(pars, 1)
	} else {
		condition += ` AND m.is_hide=? `
		pars = append(pars, 0)
	}

	list, err := obj.GetCustomTotal(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取各状态总数失败, Err: " + err.Error()
		return
	}

	//total, err := obj.GetCustomOverseasStatusTotal(condition, pars)
	//if err != nil && err.Error() != utils.ErrNoRow() {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取海外客户总计状态失败, Err: " + err.Error()
	//	return
	//}
	statisticsDataStatusList := make([]*overseas_custom.CustomTotal, 0)
	statisticsDataMap := make(map[string]int)
	for _, v := range list {
		statisticsDataMap[v.CompanyStatus] = v.Total
	}

	var statusArr = [3]string{"试用", "正式", "关闭"}

	for _, v := range statusArr {
		item := new(overseas_custom.CustomTotal)
		item.CompanyStatus = v
		if val, ok := statisticsDataMap[v]; ok {
			item.Total = val
		}
		statisticsDataStatusList = append(statisticsDataStatusList, item)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = statisticsDataStatusList
}

// @Title 海外客户标签统计数据
// @Description 海外客户标签统计数据
// @Param   Keywords	query	string	false	"关键词：客户名称/社会信用码/联系人手机号/邮箱"
// @Param   SellerId	query	int		false	"销售ID"
// @Success 200 {object} models.EnglishCompanyPageListResp
// @router /custom/label/statistics [get]
func (this *OverseasCustomController) CustomLabelStatistics() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	keywords := this.GetString("Keywords", "")
	sellerId, _ := this.GetInt("SellerId", 0)
	customType, _ := this.GetInt("CustomType", 0)

	obj := new(overseas_custom.Custom)

	var condition string
	var pars []interface{}

	condition += " AND m.overseas_status='试用' "
	if keywords != "" {
		k := "%" + keywords + "%"
		enCompanyIds, e := overseas_custom.GetEnCompanyIdsByKeyword(k)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取英文客户IDs失败, Err: " + e.Error()
			return
		}

		//获取中文客户

		companyIds, err := obj.GetCompanyIdsByKeyword(k)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取客户IDs失败, Err: " + err.Error()
			return
		}

		companyIds = append(companyIds, enCompanyIds...)

		if len(companyIds) > 0 {
			condition += fmt.Sprintf(` AND m.company_id IN (%s) `, utils.GetOrmInReplace(len(companyIds)))
			pars = append(pars, companyIds)
		} else {
			var labelArr = [4]int{1, 2, 3, 4}
			labelList := make([]*overseas_custom.OverseasLabelTotal, 0)
			for _, v := range labelArr {
				item := new(overseas_custom.OverseasLabelTotal)
				item.OverseasLabel = v
				labelList = append(labelList, item)
			}
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = labelList
			return
		}
	}
	if sellerId > 0 {
		condition += ` AND m.seller_id=? `
		pars = append(pars, sellerId)
	}

	if customType == 2 {
		condition += ` AND m.is_hide=? `
		pars = append(pars, 1)
	} else {
		condition += ` AND m.is_hide=? `
		pars = append(pars, 0)
	}

	overseasLabelDataList, err := obj.GetCustomOverseasLabelTotal(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取子标签总数失败, Err: " + err.Error()
		return
	}

	labelDataMap := make(map[int]int)
	for _, v := range overseasLabelDataList {
		labelDataMap[v.OverseasLabel] = v.Total
	}

	var labelArr = [4]int{1, 2, 3, 4}

	labelList := make([]*overseas_custom.OverseasLabelTotal, 0)

	for _, v := range labelArr {
		item := new(overseas_custom.OverseasLabelTotal)
		item.OverseasLabel = v
		if val, ok := labelDataMap[v]; ok {
			item.Total = val
		}
		labelList = append(labelList, item)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = labelList
}
