package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// @Title 设置共享客户
// @Description 设置共享客户接口
// @Param	request	body company.CompanyShareReq true "type json string"
// @Success Ret=200 设置成功
// @router /share [post]
func (this *CompanyController) CompanyShare() {
	br := new(models.BaseResponse).Init()
	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 company.CompanyShareReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CompanyId <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	if req.IsShare < 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "IsShare:" + strconv.Itoa(req.IsShare)
		return
	}
	productId := services.GetProductId(sysUser.RoleTypeCode)

	//查询该客户
	companyProductItem, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "查找客户失败"
		br.ErrMsg = "查找客户失败,Err:" + err.Error()
		return
	}

	//待更新字段
	updateCol := make([]string, 0)
	companyProductItem.IsShare = req.IsShare
	updateCol = append(updateCol, "IsShare")
	if req.IsShare == 0 {
		companyProductItem.ShareSeller = ""
		companyProductItem.ShareSellerId = 0
		companyProductItem.ShareGroupId = 0
		updateCol = append(updateCol, "ShareSeller", "ShareSellerId", "ShareGroupId")
	}

	err = companyProductItem.Update(updateCol)
	if err != nil {
		br.Msg = "修改客户信息失败"
		br.ErrMsg = "修改客户信息失败,Err:" + err.Error()
		return
	}
	//新增操作记录
	//{
	//	remark := "移动到：" + seller.RealName
	//	operation := "move_seller"
	//	services.AddCompanyOperationRecord(req.CompanyId, seller.AdminId, sysUser.AdminId, productId, sysUser.AdminId, cp.CompanyName,
	//		cp.ProductName, sysUser.RealName, remark, operation, "", sysUser.RealName, "", cp.Status)
	//}

	br.Ret = 200
	br.Success = true
	br.Msg = "设置成功"
}

// CompanyShareList
// @Title 共享客户列表
// @Description 共享客户列表接口
// @Param   SellerId   query   string  false       "选择的销售id"
// @Param   OriginalSellerId   query   string  false       "选择的原销售id"
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   ListParam   query   int  false       "筛选字段参数，用来筛选的字段， 枚举值：0:全部 、 1:已分配 、 2:未分配 、 3：未共享 "
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'viewTotal':总阅读次数 、 'viewTime':阅读时间 、 'roadShowTotal':累计路演次数 、`expireDay：到期时间` 、 `createTime：创建时间` 、 'formalTime': 转正时间 、 'freezeTime'：冻结时间 、'lossTime'：流失时间  、'tryOutDay'：试用天数"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success Ret=200 设置成功
// @router /share/list [get]
func (this *CompanyController) CompanyShareList() {
	br := new(models.BaseResponse).Init()
	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")
	sellerIds := this.GetString("SellerId")
	originalSellerIds := this.GetString("OriginalSellerId")
	keyword := this.GetString("Keyword")
	//排序参数
	sortParam := this.GetString("SortParam")
	listParam, _ := this.GetInt("ListParam")
	sortType := this.GetString("SortType")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}

	if keyword != "" {
		companyIdStr, err := company.GetCompanyIdByKeyWord(keyword)
		if err != nil {
			br.Msg = "获取客户信息失败"
			br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
			return
		}
		if companyIdStr != "" {
			condition += ` AND (a.company_name LIKE '%` + keyword + `%' OR a.credit_code LIKE '%` + keyword + `%' OR a.company_id IN(` + companyIdStr + `)) `
		} else {
			condition += ` AND (a.company_name LIKE '%` + keyword + `%' OR a.credit_code LIKE '%` + keyword + `%' ) `
		}
	}

	// 咨询组的分组id
	groupId := 0
	if utils.RunMode == "release" {
		groupId = 37
	} else {
		groupId = 61
	}

	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	//权限控制
	{
		//如果不是超级管理员或者财务
		if roleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && roleTypeCode != utils.ROLE_TYPE_CODE_FINANCE {
			//如果是部门管理员
			if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
				condition += ` AND b.product_id=? `
				pars = append(pars, productId)
			} else {
				condition += ` AND b.product_id=? `
				pars = append(pars, productId)
			}

			if sysUser.Authority == 2 && roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
				groupIdStr, sellerIdStr, err := services.GetFiccChildGroupIdsByGroupIds(sysUser.GroupId)
				if err != nil {
					br.Msg = "获取销售分组信息失败！"
					br.ErrMsg = "获取销售分组信息失败！Err:" + err.Error()
					return
				}
				if sysUser.GroupId == groupId {
					if sellerIdStr != "" {
						condition += ` AND b.share_seller_id IN (` + sellerIdStr + `) `
					}
				} else {
					if groupIdStr != "" {
						condition += ` AND b.group_id IN (` + groupIdStr + `) `
					}
				}
			} else if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
				//if sysUser.GroupId == groupId {
				sellerIdStr, err := services.GetFiccSellerIdsByGroupId(sysUser.GroupId)
				if err != nil {
					br.Msg = "获取销售分组信息失败！"
					br.ErrMsg = "获取销售分组信息失败！Err:" + err.Error()
					return
				}
				//权益销售组长可以查看自己的组员以及共享给组员的客户
				if sellerIdStr != "" {
					condition += ` AND ( b.share_seller_id IN (` + sellerIdStr + `)  OR   b.group_id= ? )`
					pars = append(pars, sysUser.GroupId)
				} else {
					condition += ` AND b.group_id=? `
					pars = append(pars, sysUser.GroupId)
				}
			} else if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.AdminId != 66 && sysUser.AdminId != 15 && roleTypeCode != utils.ROLE_TYPE_CODE_FICC_ADMIN && roleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN {
				if sysUser.GroupId == groupId {
					condition += ` AND b.share_seller_id=? `
					pars = append(pars, sysUser.AdminId)
				} else {
					// 在此页面销售只能看分配给自己的客户
					condition += ` AND (b.seller_id =? OR b.share_seller_id =? )`
					pars = append(pars, sysUser.AdminId, sysUser.AdminId)
				}
			}
		}
	}

	if listParam == 0 {
		if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP ||
			sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
			sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
			//非咨询组销售，那么默认查看“未共享”的客户
			if sysUser.GroupId != groupId {
				listParam = 3
				if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER {
					condition += ` AND b.seller_id = ? `
					pars = append(pars, sysUser.AdminId)
				}
			} else {
				condition += ` AND b.is_share=1 `
			}
		} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			// 管理员，默认查看“待分配”客户
			listParam = 2
		}
	}

	if listParam == 1 {
		condition += ` AND b.share_seller_id > 0 AND b.is_share=1 `
	} else if listParam == 2 {
		condition += ` AND b.share_seller_id = 0 AND b.is_share=1 `
	} else if listParam == 3 { // 未共享
		if productId == 1 {
			condition += ` AND b.is_share=0 and (b.status="正式" AND b.product_id = 1) `
		} else if productId == 2 {
			condition += ` AND b.is_share=0 and (b.status IN ("正式","试用","永续") AND b.product_id = 2) `
		} else {
			condition += ` AND b.is_share=0 and ((b.status="正式" AND b.product_id = 1) OR (b.status IN ("正式","试用") AND b.product_id = 2))`
		}
	}

	if sellerIds != "" {
		condition += ` AND b.share_seller_id IN (` + sellerIds + `) `
	}
	if originalSellerIds != "" {
		condition += ` AND b.seller_id IN (` + originalSellerIds + `) `
	}

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

	sortStr := ``
	if sortParam != "" && sortType != "" {
		if sortParam == "expireDay" {
			if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				if sortType == "asc" {
					sortStr = " ORDER BY min_end_date"
				} else {
					sortStr = " ORDER BY max_end_date"
				}
			} else {
				sortStr = " ORDER BY b.end_date "
			}
		} else if sortParam == "createTime" {
			sortStr = " ORDER BY a.created_time "
		} else if sortParam == "viewTotal" {
			if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				sortStr = " ORDER BY all_view_total"
			} else {
				sortStr = " ORDER BY b.view_total "
			}
		} else if sortParam == "viewTime" {
			if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				if sortType == "asc" {
					sortStr = " ORDER BY min_last_view_time"
				} else {
					sortStr = " ORDER BY max_last_view_time"
				}
			} else {
				sortStr = " ORDER BY b.last_view_time "
			}
		} else if sortParam == "roadShowTotal" {
			sortStr = " ORDER BY b.road_show_total "
		} else if sortParam == "formalTime" {
			sortStr = " ORDER BY b.formal_time "
		} else if sortParam == "freezeTime" {
			sortStr = " ORDER BY b.freeze_time "
		} else if sortParam == "lossTime" {
			sortStr = " ORDER BY b.loss_time "
		} else if sortParam == "todoCreateTime" {
			sortStr = " ORDER BY b.todo_create_time "
		} else if sortParam == "todoApproveTime" {
			sortStr = " ORDER BY b.todo_approve_time "
		} else if sortParam == "tryOutDay" {
			if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				sortStr = " ORDER BY all_try_out_day_total "
			} else {
				sortStr = " ORDER BY b.try_out_day_total "
			}
		} else if sortParam == "lastServiceTime" {
			// 最新服务时间
			sortStr = ` ORDER BY last_service_time `
		} else if sortParam == "serviceTimes" {
			// 服务次数
			sortStr = ` ORDER BY service_times `
		} else {
			br.Msg = "获取失败"
			br.ErrMsg = "排序字段传入数据异常:" + sortParam
			return
		}
		sortStr += fmt.Sprintf(` %s`, sortType)
	} else {
		if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
			//sortStr = " ORDER BY sort_status asc, all_view_total desc, a.created_time "
			sortStr = " ORDER BY start_date DESC, all_view_total desc, a.created_time "
		} else {
			//sortStr = " ORDER BY sort_status asc, b.view_total desc, a.created_time  "
			sortStr = " ORDER BY start_date DESC, b.view_total desc, a.created_time "
		}
		sortStr += " DESC "
	}

	sysUserList, err := system.GetAdminList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取admin列表失败, Err:" + err.Error()
		return
	}
	adminMap := make(map[int]*system.Admin, 0)
	for _, v := range sysUserList {
		adminMap[v.AdminId] = v
	}

	list, err := company.GetShareCompanyList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//企业用户数组切片
	companyIds := make([]int, 0)
	companyIdSlice := make([]string, 0)
	for _, v := range list {
		companyIds = append(companyIds, v.CompanyId)
		companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
	}

	//企业用户产品开通数
	companyIdStr := strings.Join(companyIdSlice, ",")
	companyProductTotalList, _ := company.GetCountProductByCompanyIds(companyIdStr)
	companyProductTotalMap := make(map[int]*company.CompanyProductTotalSlice)
	for _, companyProductTotal := range companyProductTotalList {
		companyProductTotalMap[companyProductTotal.CompanyId] = companyProductTotal
	}
	lenList := len(list)

	// 客户产品详细信息
	companyProductMap := make(map[string]*company.CompanyProduct)
	var companyProductCondition string
	var companyProductPars []interface{}

	companyProductList, err := company.GetCompanyProductsByCompanyIds(companyIdStr, companyProductCondition, companyProductPars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取客户产品数据失败，Err:" + err.Error()
		return
	}
	for _, companyProduct := range companyProductList {
		key := fmt.Sprint(companyProduct.CompanyId, "_", companyProduct.ProductId)
		companyProductMap[key] = companyProduct
	}

	// 查询当前销售是否有领取客户的权限
	//receiveEnabled, _ := services.CheckCompanyReceiveButton(sysUser.AdminId)
	for i := 0; i < lenList; i++ {
		item := list[i]

		//校验该客户是否存在多个产品，如果是，那么代表是共享客户
		if companyProductTotal, ok := companyProductTotalMap[int(item.CompanyId)]; ok {
			if companyProductTotal.Total > 1 {
				list[i].IsShared = true
			}
		}

		var expireDay string
		itemStatus := item.Status
		if itemStatus != "" {
			if !strings.Contains(item.Status, "/") {
				if strings.Contains(itemStatus, utils.COMPANY_STATUS_FOREVER) { //永续
					expireDay = "-"
				} else if strings.Contains(itemStatus, utils.COMPANY_STATUS_TRY_OUT) || strings.Contains(itemStatus, utils.COMPANY_STATUS_FORMAL) { //试用/正式
					if item.StartDate != "" && item.EndDate != "" {
						endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
						endDateTime = endDateTime.AddDate(0, 0, 1)
						sub := endDateTime.Sub(time.Now())
						if sub < 0 {
							sub = 0
						}
						expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
					} else {
						expireDay = "-"
					}
				} else if strings.Contains(itemStatus, utils.COMPANY_STATUS_LOSE) {
					expireDay = "-"
				} else if strings.Contains(itemStatus, utils.COMPANY_STATUS_FREEZE) {
					if item.StartDate != "" && item.EndDate != "" {
						endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
						endDateTime = endDateTime.AddDate(0, 0, 0)
						sub := endDateTime.Sub(time.Now())
						if sub < 0 {
							sub = 0
						}
						expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
					} else {
						expireDay = "-"
					}
				} else {
					expireDay = "-"
				}
			} else {
				tmpStatusArr := strings.Split(item.Status, "/")
				ficcStatus := tmpStatusArr[0]
				raiStatus := tmpStatusArr[1]
				var ficcEndDate, tryEndDate string
				var ficcExpireDay, tryExpireDay string
				if item.EndDate != "" {
					endDateArr := strings.Split(item.EndDate, "/")
					if len(endDateArr) == 1 {
						ficcEndDate = endDateArr[0]
					} else if len(endDateArr) > 1 {
						ficcEndDate = endDateArr[0]
						tryEndDate = endDateArr[1]
					}
					if strings.Contains(ficcStatus, utils.COMPANY_STATUS_FOREVER) { //永续
						ficcExpireDay = "-"
					} else if strings.Contains(ficcStatus, utils.COMPANY_STATUS_X_CLASS_TRY_OUT) || strings.Contains(ficcStatus, utils.COMPANY_STATUS_FORMAL) { //试用/正式
						if ficcEndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 1)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							ficcExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							ficcExpireDay = "-"
						}
					} else if strings.Contains(ficcStatus, utils.COMPANY_STATUS_LOSE) { //流失
						ficcExpireDay = "-"
					} else if strings.Contains(ficcStatus, utils.COMPANY_STATUS_FREEZE) { //冻结
						if item.StartDate != "" && item.EndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, ficcEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 0)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							ficcExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							ficcExpireDay = "-"
						}
					} else {
						ficcExpireDay = "-"
					}

					if strings.Contains(raiStatus, utils.COMPANY_STATUS_FOREVER) { //永续
						tryExpireDay = "-"
					} else if strings.Contains(raiStatus, utils.COMPANY_STATUS_X_CLASS_TRY_OUT) || strings.Contains(raiStatus, utils.COMPANY_STATUS_FORMAL) { //试用/正式
						if tryEndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 1)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							tryExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							tryExpireDay = "-"
						}
					} else if strings.Contains(raiStatus, utils.COMPANY_STATUS_LOSE) { //流失
						tryExpireDay = "-"
					} else if strings.Contains(raiStatus, utils.COMPANY_STATUS_FREEZE) { //冻结
						if item.StartDate != "" && item.EndDate != "" {
							endDateTime, _ := time.Parse(utils.FormatDate, tryEndDate)
							endDateTime = endDateTime.AddDate(0, 0, 0)
							sub := endDateTime.Sub(time.Now())
							if sub < 0 {
								sub = 0
							}
							tryExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
						} else {
							tryExpireDay = "-"
						}
					} else {
						tryExpireDay = "-"
					}
				}
				expireDay = ficcExpireDay + "/" + tryExpireDay
			}
		}
		list[i].ExpireDay = expireDay

		//按钮显示控制
		btnItem := new(company.ButtonPermission)
		if item.CompanyId != 1 {
			//*btnItem = services.GetCompanyPermissionButton(roleTypeCode, itemStatus, item.GroupIds, item.GroupIds, item.GroupId, sysUser.GroupId, item.SellerId, sysUser.AdminId, sysUser.Authority, item.ProductId, item.ShareSellerId)
			//根据销售"领取客户"的权限对部分按钮做限制
			//btnItem = services.GetCompanyPermissionButtonByReceiveEnabled(btnItem, receiveEnabled)

			// 13.6正式客户共享按钮显示控制
			btnItem = services.GetShareCompanyPermissionButton(roleTypeCode, itemStatus, item.ProductId, item, sysUser)
		}
		list[i].BtnItem = btnItem

		if item.FreezeStartDate != "" && item.FreezeEndDate != "" && strings.Contains(item.Status, utils.COMPANY_STATUS_FREEZE) {
			freezeEndDate, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
			if time.Now().Before(freezeEndDate) {
				expireDays := freezeEndDate.Sub(time.Now()).Hours() / 24
				list[i].FreezeExpireDays = int(expireDays) + 1
			}
		}

		ficcKey := fmt.Sprint(item.CompanyId, "_", 1)
		//ficc
		if tmpCompanyProduct, ok := companyProductMap[ficcKey]; ok {
			//套餐类型
			item.FiccPackageType = tmpCompanyProduct.PackageType

			//总试用天数
			item.FiccTryOutDay = tmpCompanyProduct.TryOutDayTotal

			//总阅读次数
			item.FiccView = tmpCompanyProduct.ViewTotal

			if !tmpCompanyProduct.LastViewTime.IsZero() {
				//最近一次阅读时间
				item.FiccLastViewTime = tmpCompanyProduct.LastViewTime.Format(utils.FormatDateTime)
			}
		}

		//权益
		raiKey := fmt.Sprint(item.CompanyId, "_", 2)
		if tmpCompanyProduct, ok := companyProductMap[raiKey]; ok {
			//总阅读次数
			item.RaiView = tmpCompanyProduct.ViewTotal
			//总试用天数
			item.RaiTryOutDay = tmpCompanyProduct.TryOutDayTotal

			if !tmpCompanyProduct.LastViewTime.IsZero() {
				//最近一次阅读时间
				item.RaiLastViewTime = tmpCompanyProduct.LastViewTime.Format(utils.FormatDateTime)
			}
		}
	}

	companyLists := make([]*company.CompanyListItem, 0)
	//查询阅读次数
	if list == nil {
		companyLists = make([]*company.CompanyListItem, 0)
	} else {
		for _, v := range list {
			//viewTotal:=GetviewTotal(v.CompanyId)

			//活跃（客户状态）
			if v.IsShare != 1 {
				if v.BtnItem.BtnModifySeller == true {
					v.BtnItem.BtnModifySeller = false
				}
			}

			if v.IsShare == 1 && v.BtnItem.BtnModifySeller == true && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				//如果已经是共享客户了，取消共享按钮全都显示，和修改销售权限一样
				v.BtnItem.BtnShare = true
			}
			//解决共享客户正式筛选下是否标红的问题
			if v.WeekViewActive == 0 && v.IsUserMaker == 1 {
				v.WeekViewActive = 1
			}

			companyList := &company.CompanyListItem{
				CompanyId:        v.CompanyId,
				CompanyName:      v.CompanyName,
				CreditCode:       v.CreditCode,
				CompanyCode:      v.CompanyCode,
				StartDate:        v.StartDate,
				EndDate:          v.EndDate,
				LoseReason:       v.LoseReason,
				RenewalReason:    v.RenewalReason,
				FreezeReason:     v.FreezeReason,
				LossTime:         v.LossTime,
				Status:           v.Status,
				CompanyType:      v.CompanyType,
				ApproveStatus:    v.ApproveStatus,
				SellerName:       v.SellerName,
				SellerId:         v.SellerId,
				SellerIds:        v.SellerIds,
				ExpireDay:        v.ExpireDay,
				FreezeTime:       v.FreezeTime,
				GroupId:          v.GroupId,
				GroupIds:         v.GroupIds,
				DepartmentId:     v.DepartmentId,
				IndustryName:     v.IndustryName,
				IsSuspend:        v.IsSuspend,
				CreatedTime:      v.CreatedTime,
				Source:           v.Source,
				Province:         v.Province,
				City:             v.City,
				Address:          v.Address,
				Reasons:          v.Reasons,
				FreezeStartDate:  v.FreezeStartDate,
				FreezeEndDate:    v.FreezeEndDate,
				FreezeExpireDays: v.FreezeExpireDays,
				BtnItem:          v.BtnItem,
				ProductId:        v.ProductId,
				FormalTime:       v.FormalTime,
				IsShared:         v.IsShared,
				RegionType:       v.RegionType,
				FiccPackageType:  v.FiccPackageType,
				FiccLastViewTime: v.FiccLastViewTime,
				RaiLastViewTime:  v.RaiLastViewTime,
				//FiccView:         viewTotal[0],
				//RaiView:          viewTotal[1],
				//FiccView: ficcViewTotal,
				//RaiView:  raiViewTotal,
				FiccView:        v.FiccView,
				RaiView:         v.RaiView,
				FiccTryOutDay:   v.FiccTryOutDay,
				RaiTryOutDay:    v.RaiTryOutDay,
				AllViewTotal:    v.AllViewTotal,
				RoadShowTotal:   v.RoadShowTotal,
				TryStageSlice:   v.TryStageSlice,
				Deadline:        v.Deadline,
				WeekViewActive:  v.WeekViewActive,
				IsShare:         v.IsShare,
				ShareSellerId:   v.ShareSellerId,
				LastServiceTime: v.LastServiceTime,
				ServiceTimes:    v.ServiceTimes,
				IsUserMaker:     v.IsUserMaker,
			}
			if v.ShareSellerIds != "" {
				shareSellerIds := strings.Split(v.ShareSellerIds, ",")
				for _, idStr := range shareSellerIds {
					shareSellerId, e := strconv.Atoi(idStr)
					if e != nil {
						err = e
						return
					}
					shareSeller := adminMap[shareSellerId]
					if shareSeller != nil {
						companyList.ShareSeller += shareSeller.RealName + "(" + shareSeller.GroupName + ")" + "/"
					}
				}
				companyList.ShareSeller = strings.TrimRight(companyList.ShareSeller, "/")
			}
			companyLists = append(companyLists, companyList)
		}
	}
	if companyLists == nil {
		companyLists = make([]*company.CompanyListItem, 0)
	}

	var isShareGroup bool
	if sysUser.GroupId == groupId {
		isShareGroup = true
	}

	page = paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyListResp)
	resp.List = companyLists
	resp.IsShareGroup = isShareGroup
	resp.Status = listParam
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp

}

// @Title 分配共享销售
// @Description 分配共享销售接口
// @Param	request	body company.MoveShareSellerReq true "type json string"
// @Success Ret=200 分配成功
// @router /share/moveSeller [post]
func (this *CompanyController) MoveShareSeller() {
	br := new(models.BaseResponse).Init()
	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 company.MoveShareSellerReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CompanyId <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "CompanyId:" + strconv.Itoa(req.CompanyId)
		return
	}
	if req.SellsId <= 0 {
		br.Msg = "参数异常！"
		br.ErrMsg = "SellsId:" + strconv.Itoa(req.SellsId)
		return
	}
	seller, err := system.GetSysAdminById(req.SellsId)
	if err != nil {
		br.Msg = "获取销售信息失败"
		br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
		return
	}
	productId := services.GetProductId(sysUser.RoleTypeCode)
	if productId == 0 {
		br.Msg = "该角色非ficc或权益角色"
		br.ErrMsg = "该角色非ficc或权益角色"
		return
	}
	//查询该客户
	companyProductItem, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "查找客户失败"
		br.ErrMsg = "查找客户失败,Err:" + err.Error()
		return
	}

	//待更新字段
	updateCol := make([]string, 0)
	companyProductItem.ShareSeller = seller.RealName
	companyProductItem.ShareSellerId = seller.AdminId
	companyProductItem.ShareGroupId = seller.GroupId
	updateCol = append(updateCol, "ShareSeller", "ShareSellerId", "ShareGroupId")

	err = companyProductItem.Update(updateCol)
	if err != nil {
		br.Msg = "修改客户信息失败"
		br.ErrMsg = "修改客户信息失败,Err:" + err.Error()
		return
	}
	//新增操作记录
	//{
	//	remark := "移动到：" + seller.RealName
	//	operation := "move_seller"
	//	services.AddCompanyOperationRecord(req.CompanyId, seller.AdminId, sysUser.AdminId, productId, sysUser.AdminId, cp.CompanyName,
	//		cp.ProductName, sysUser.RealName, remark, operation, "", sysUser.RealName, "", cp.Status)
	//}
	//变更销售员与联系人关系
	//_ = models.UpdateUserSellerRelationByCompanyId(req.CompanyId, productId, seller.AdminId, seller.RealName)

	br.Ret = 200
	br.Success = true
	br.Msg = "分配成功"
}

// CompanyShareAddRemark
// @Title 新增客户备注
// @Description 新增客户备注
// @Param	request	body company.RemarkReq true "type json string"
// @Success 200 编辑成功
// @router /share/remark/add [post]
func (this *CompanyController) CompanyShareAddRemark() {
	br := new(models.BaseResponse).Init()
	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 company.RemarkReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，客户编号未传！"
		return
	}
	if req.Remark == "" {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，备注说明未传！"
		return
	}
	var productId int
	groupFicc := []string{
		utils.ROLE_TYPE_CODE_FICC_SELLER, utils.ROLE_TYPE_CODE_FICC_TEAM, utils.ROLE_TYPE_CODE_FICC_GROUP,
		utils.ROLE_TYPE_CODE_FICC_DEPARTMENT, utils.ROLE_TYPE_CODE_FICC_ADMIN,
	}
	groupRai := []string{
		utils.ROLE_TYPE_CODE_RAI_SELLER, utils.ROLE_TYPE_CODE_RAI_GROUP, utils.ROLE_TYPE_CODE_RAI_GROUP,
		utils.ROLE_TYPE_CODE_RAI_DEPARTMENT, utils.ROLE_TYPE_CODE_RAI_ADMIN,
	}
	if utils.InArrayByStr(groupFicc, sysUser.RoleTypeCode) {
		productId = 1
	}
	if utils.InArrayByStr(groupRai, sysUser.RoleTypeCode) {
		productId = 2
	}
	if productId == 0 {
		br.Msg = "该角色不可添加备注"
		return
	}

	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "查询客户异常"
		br.ErrMsg = "查询客户异常，Err:" + err.Error()
	}
	remark := company.CompanyProductRemark{
		CompanyId:   companyProduct.CompanyId,
		ProductId:   companyProduct.ProductId,
		ProductName: companyProduct.ProductName,
		Remark:      req.Remark,
		CreateTime:  time.Now(),
		SysUserId:   sysUser.AdminId,
		SysRealName: sysUser.RealName,
	}
	var newId int64
	newId, err = company.AddCompanyRemark(&remark)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增共享客户备注失败, Err: " + err.Error()
		return
	}

	go func() {
		approveContent := req.Remark
		remark := "新增备注"
		operation := "add_remark"
		_ = services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, companyProduct.ProductId, sysUser.AdminId, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, sysUser.RealName, "", companyProduct.Status)
	}()

	//如果是权益的写入历史备注表
	if productId == utils.COMPANY_PRODUCT_RAI_ID {
		//权益客户新增历史备注总表
		itemRecord := new(company.CompanyHistoryRemark)
		itemRecord.CompanyId = req.CompanyId
		itemRecord.Content = req.Remark
		itemRecord.SysAdminId = sysUser.AdminId
		itemRecord.SysAdminName = sysUser.RealName
		itemRecord.CreateTime = time.Now().Local()
		itemRecord.ModifyTime = time.Now().Local()
		itemRecord.ShowTime = time.Now().Local()
		itemRecord.ProductId = 2
		itemRecord.TableName = "company_product_remark"
		itemRecord.TableId = int(newId)
		go services.AddCompanyHistoryRemark(itemRecord)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// CompanyShareMark
// @Title 新增客户标记
// @Description 新增客户标记
// @Param	request	body company.CompanyMarkReq true "type json string"
// @Success 200 编辑成功
// @router /share/mark [post]
func (this *CompanyController) CompanyShareMark() {
	br := new(models.BaseResponse).Init()
	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 company.CompanyMarkReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.CompanyServiceRecordId <= 0 {
		br.Msg = "参数缺失"
		br.ErrMsg = "参数缺失，备注ID未传！"
		return
	}

	err = company.UpdateCompanyServiceRecordMark(req.CompanyServiceRecordId, req.Status)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增共享客户备注失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// @Title 共享客户列表-同城
// @Description 共享客户列表接口
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   ListParam   query   int  false       "筛选字段参数，用来筛选的字段， 枚举值：0:全部 、 1:已分配 、 2:未分配  "
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'viewTotal':总阅读次数 、 'viewTime':阅读时间 、 'roadShowTotal':累计路演次数 、`expireDay：到期时间` 、 `createTime：创建时间` 、 'formalTime': 转正时间 、 'freezeTime'：冻结时间 、'lossTime'：流失时间  、'tryOutDay'：试用天数"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success Ret=200 设置成功
// @router /share/list/city [get]
func (this *CompanyController) CompanyShareListByCity() {
	br := new(models.BaseResponse).Init()
	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")
	keyword := this.GetString("Keyword")
	province := this.GetString("Province")
	city := this.GetString("City")
	//排序参数
	//sortParam := this.GetString("SortParam")
	//listParam, _ := this.GetInt("ListParam")
	//sortType := this.GetString("SortType")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}

	if keyword != "" {
		companyIdStr, err := company.GetCompanyIdByKeyWord(keyword)
		if err != nil {
			br.Msg = "获取客户信息失败"
			br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
			return
		}
		if companyIdStr != "" {
			condition += ` AND (a.company_name LIKE '%` + keyword + `%' OR a.credit_code LIKE '%` + keyword + `%' OR a.company_id IN(` + companyIdStr + `)) `
		} else {
			condition += ` AND (a.company_name LIKE '%` + keyword + `%' OR a.credit_code LIKE '%` + keyword + `%' ) `
		}
	}

	condition += ` AND b.is_share=1 `
	if province != "" {
		var provinceSql string
		slice := strings.Split(province, ",")
		for _, v := range slice {
			provinceSql += "'" + v + "'" + ","
		}
		provinceSql = strings.TrimRight(provinceSql, ",")
		condition += ` AND a.province IN (` + provinceSql + `) `
	}

	if city != "" {
		var citySql string
		slice := strings.Split(city, ",")
		for _, v := range slice {
			citySql += "'" + v + "'" + ","
		}
		citySql = strings.TrimRight(citySql, ",")
		condition += ` AND a.city IN (` + citySql + `) `
	}

	total, err := company.GetShareCompanyListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}
	sysUserList, err := system.GetAdminList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取admin列表失败, Err:" + err.Error()
		return
	}
	adminMap := make(map[int]*system.Admin, 0)
	for _, v := range sysUserList {
		adminMap[v.AdminId] = v
	}
	sortStr := ` `
	//if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
	//	sortStr = " ORDER BY sort_status asc, all_view_total desc, a.created_time "
	//} else {
	//	sortStr = " ORDER BY sort_status asc, b.view_total desc, a.created_time  "
	//}

	list, err := company.GetShareCompanyList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//企业用户数组切片
	companyIds := make([]int, 0)
	companyIdSlice := make([]string, 0)
	for _, v := range list {
		companyIds = append(companyIds, v.CompanyId)
		companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
	}

	//企业用户产品开通数
	companyIdStr := strings.Join(companyIdSlice, ",")
	companyProductTotalList, _ := company.GetCountProductByCompanyIds(companyIdStr)
	companyProductTotalMap := make(map[int]*company.CompanyProductTotalSlice)
	for _, companyProductTotal := range companyProductTotalList {
		companyProductTotalMap[companyProductTotal.CompanyId] = companyProductTotal
	}

	// 客户产品详细信息
	companyProductMap := make(map[string]*company.CompanyProduct)
	var companyProductCondition string
	var companyProductPars []interface{}

	companyProductList, err := company.GetCompanyProductsByCompanyIds(companyIdStr, companyProductCondition, companyProductPars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取客户产品数据失败，Err:" + err.Error()
		return
	}
	for _, companyProduct := range companyProductList {
		key := fmt.Sprint(companyProduct.CompanyId, "_", companyProduct.ProductId)
		companyProductMap[key] = companyProduct
	}

	companyLists := make([]*company.CompanyListItem, 0)
	//查询阅读次数
	if list == nil {
		companyLists = make([]*company.CompanyListItem, 0)
	} else {
		for _, v := range list {
			//viewTotal:=GetviewTotal(v.CompanyId)

			//活跃（客户状态）
			if v.IsShare != 1 {
				if v.BtnItem.BtnModifySeller == true {
					v.BtnItem.BtnModifySeller = false
				}
			}

			companyList := &company.CompanyListItem{
				CompanyId:        v.CompanyId,
				CompanyName:      v.CompanyName,
				CreditCode:       v.CreditCode,
				CompanyCode:      v.CompanyCode,
				StartDate:        v.StartDate,
				EndDate:          v.EndDate,
				LoseReason:       v.LoseReason,
				RenewalReason:    v.RenewalReason,
				FreezeReason:     v.FreezeReason,
				LossTime:         v.LossTime,
				Status:           v.Status,
				CompanyType:      v.CompanyType,
				ApproveStatus:    v.ApproveStatus,
				SellerName:       v.SellerName,
				SellerId:         v.SellerId,
				SellerIds:        v.SellerIds,
				ExpireDay:        v.ExpireDay,
				FreezeTime:       v.FreezeTime,
				GroupId:          v.GroupId,
				GroupIds:         v.GroupIds,
				DepartmentId:     v.DepartmentId,
				IndustryName:     v.IndustryName,
				IsSuspend:        v.IsSuspend,
				CreatedTime:      v.CreatedTime,
				Source:           v.Source,
				Province:         v.Province,
				City:             v.City,
				Address:          v.Address,
				Reasons:          v.Reasons,
				FreezeStartDate:  v.FreezeStartDate,
				FreezeEndDate:    v.FreezeEndDate,
				FreezeExpireDays: v.FreezeExpireDays,
				BtnItem:          v.BtnItem,
				ProductId:        v.ProductId,
				FormalTime:       v.FormalTime,
				IsShared:         v.IsShared,
				RegionType:       v.RegionType,
				FiccPackageType:  v.FiccPackageType,
				FiccLastViewTime: v.FiccLastViewTime,
				RaiLastViewTime:  v.RaiLastViewTime,
				//FiccView:         viewTotal[0],
				//RaiView:          viewTotal[1],
				//FiccView: ficcViewTotal,
				//RaiView:  raiViewTotal,
				FiccView:        v.FiccView,
				RaiView:         v.RaiView,
				FiccTryOutDay:   v.FiccTryOutDay,
				RaiTryOutDay:    v.RaiTryOutDay,
				AllViewTotal:    v.AllViewTotal,
				RoadShowTotal:   v.RoadShowTotal,
				TryStageSlice:   v.TryStageSlice,
				Deadline:        v.Deadline,
				WeekViewActive:  v.WeekViewActive,
				IsShare:         v.IsShare,
				ShareSellerId:   v.ShareSellerId,
				LastServiceTime: v.LastServiceTime,
				ServiceTimes:    v.ServiceTimes,
			}
			if v.ShareSellerIds != "" {
				shareSellerIds := strings.Split(v.ShareSellerIds, ",")
				for _, idStr := range shareSellerIds {
					shareSellerId, e := strconv.Atoi(idStr)
					if e != nil {
						err = e
						return
					}
					shareSeller := adminMap[shareSellerId]
					if shareSeller != nil {
						companyList.ShareSeller += shareSeller.RealName + "(" + shareSeller.GroupName + ")" + "/"
					}
				}
				companyList.ShareSeller = strings.TrimRight(companyList.ShareSeller, "/")
			}
			companyLists = append(companyLists, companyList)
		}
	}
	if companyLists == nil {
		companyLists = make([]*company.CompanyListItem, 0)
	}
	page = paging.GetPaging(currentIndex, pageSize, total)
	resp := new(company.CompanyListResp)
	resp.List = companyLists
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp

}
