package english_report

import (
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/services"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
)

// EnglishCompanyController 英文客户
type EnglishCompanyController struct {
	controllers.BaseAuthController
}

// List
// @Title 英文客户列表
// @Description 英文客户列表
// @Param   Keywords	query	string	false	"关键词：客户名称/联系人邮箱/联系人手机号"
// @Param   SortType	query	int		false	"点击量排序：1-降序; 2-升序"
// @Param   EnPermissionIds		query	string		false	"品种权限IDs(字符串)"
// @Success 200 {object} models.EnglishCompanyPageListResp
// @router /company/list [get]
func (this *EnglishCompanyController) List() {
	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 startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	keywords := this.GetString("Keywords", "")
	sortType, _ := this.GetInt("SortType", 0)
	sortParam := this.GetString("SortParam", "")
	strPermissionIds := this.GetString("EnPermissionIds", "")

	var cond, order string
	var pars []interface{}
	if keywords != "" {
		k := "%" + keywords + "%"
		companyIds, e := models.GetEnCompanyIdsByKeyword(k)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "关键词获取英文客户IDs失败, Err: " + e.Error()
			return
		}
		if len(companyIds) == 0 {
			page := paging.GetPaging(currentIndex, pageSize, 0)
			resp := &models.EnglishCompanyPageListResp{
				Paging: page,
				List:   make([]*models.EnglishCompanyResp, 0),
			}
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = resp
			return
		}
		cond += fmt.Sprintf(` AND c.company_id IN (%s) `, utils.GetOrmInReplace(len(companyIds)))
		pars = append(pars, companyIds)
	}
	// 品种权限
	if strPermissionIds != "" {
		permissionIdArr := strings.Split(strPermissionIds, ",")
		permissionIds := make([]int, 0)
		for _, s := range permissionIdArr {
			p, e := strconv.Atoi(s)
			if e != nil {
				br.Msg = "品种权限有误"
				br.ErrMsg = "品种权限筛选有误"
				return
			}
			permissionIds = append(permissionIds, p)
		}
		if len(permissionIds) == 0 {
			br.Msg = "品种权限有误"
			br.ErrMsg = "品种权限筛选ID为空"
			return
		}
		queryCond := fmt.Sprintf(` AND %s IN (%s)`, models.EnCompanyPermissionColumns.EnPermissionId, utils.GetOrmInReplace(len(permissionIds)))
		queryPars := make([]interface{}, 0)
		queryPars = append(queryPars, permissionIds)
		queryOB := new(models.EnCompanyPermission)
		queryList, e := queryOB.GetItemsByCondition(queryCond, queryPars, []string{"DISTINCT en_company_id"}, "")
		if e != nil {
			br.Msg = "品种筛选有误"
			br.ErrMsg = "品种筛选失败, Err: " + e.Error()
			return
		}
		companyIds := make([]int, 0)
		for _, q := range queryList {
			companyIds = append(companyIds, q.EnCompanyId)
		}
		if len(companyIds) == 0 {
			page := paging.GetPaging(currentIndex, pageSize, 0)
			resp := &models.EnglishCompanyPageListResp{
				Paging: page,
				List:   make([]*models.EnglishCompanyResp, 0),
			}
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = resp
			return
		}
		cond += fmt.Sprintf(` AND c.company_id IN (%s) `, utils.GetOrmInReplace(len(companyIds)))
		pars = append(pars, companyIds)
	}

	if sortParam == "" {
		if sortType == 1 {
			order = ` ORDER BY c.view_total DESC`
		}
		if sortType == 2 {
			order = ` ORDER BY c.view_total ASC`
		}
	} else if sortParam == "deadLine" {
		order = ` ORDER BY todo_end_time asc, c.view_total desc, c.company_id desc`
	} else if sortParam == "todoStatusStr" {
		order = ` ORDER BY FIELD (todo_status_str,'进行中','已完成','无任务'), c.view_total desc, c.company_id desc`
	}

	total, list, e := models.GetEnglishCompanyPageList(cond, pars, order, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文客户列表失败, Err: " + e.Error()
		return
	}
	// 客户列表TODO信息
	todoMap := services.GetEnglishCompanyListTodoMap(list, sysUser)

	// 品种权限
	permissionMap := make(map[int][]int)
	{
		companyIds := make([]int, 0)
		for _, v := range list {
			companyIds = append(companyIds, v.CompanyId)
		}
		if len(companyIds) > 0 {
			cond := fmt.Sprintf(` AND %s IN (%s)`, models.EnCompanyPermissionColumns.EnCompanyId, utils.GetOrmInReplace(len(companyIds)))
			pars := make([]interface{}, 0)
			pars = append(pars, companyIds)
			ob := new(models.EnCompanyPermission)
			items, e := ob.GetItemsByCondition(cond, pars, []string{}, "")
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取客户权限列表失败, Err: " + e.Error()
				return
			}
			for _, v := range items {
				if permissionMap[v.EnCompanyId] == nil {
					permissionMap[v.EnCompanyId] = make([]int, 0)
				}
				permissionMap[v.EnCompanyId] = append(permissionMap[v.EnCompanyId], v.EnPermissionId)
			}
		}
	}

	respList := make([]*models.EnglishCompanyResp, 0)
	for i := range list {
		respList = append(respList, &models.EnglishCompanyResp{
			CompanyId:     list[i].CompanyId,
			CompanyName:   list[i].CompanyName,
			CountryCode:   list[i].CountryCode,
			Country:       list[i].Country,
			SellerId:      list[i].SellerId,
			SellerName:    list[i].SellerName,
			ViewTotal:     list[i].ViewTotal,
			CreateTime:    list[i].CreateTime.Format(utils.FormatDateTime),
			Enabled:       list[i].Enabled,
			TodoInfo:      todoMap[list[i].CompanyId],
			EnPermissions: permissionMap[list[i].CompanyId],
		})
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &models.EnglishCompanyPageListResp{
		Paging: page,
		List:   respList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
