package service

import (
	MC "app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/encrypt"
	"fmt"
	"jyBXCore/rpc/model/es"
	"jyBXCore/rpc/model/mysql"
	"jyBXCore/rpc/type/bxcore"
	"jyBXCore/rpc/util"
	"log"
	"strconv"
	"strings"
	"time"
)

// 我的参标项目|企业参标项目 列表
func ParticipateList(in *bxcore.ParticipateListReq) (*bxcore.ParticipateListRes, error) {
	defer MC.Catch()
	res := &bxcore.ParticipateListRes{Data: &bxcore.ParticipateData{}}
	b, entRoleId := util.IsAllowedParticipate(in.AppId, in.MgoUserId, in.NewUserId, in.AccountId, in.EntAccountId, in.EntId, in.EntUserId, in.PositionId, in.PositionType)
	if !b || (in.Identity == "ent" && entRoleId == 0) {
		res.ErrCode = 0
		res.ErrMsg = "没有权限"
		return res, nil
	}
	if in.PositionType > 0 {
		if entRoleId == 0 {
			in.EntUserIds = ""
		}
	}
	if in.PageNum < 1 {
		in.PageNum = 1
	}
	in.PageNum = (in.PageNum - 1) * in.PageSize
	if in.PageSize < 1 {
		in.PageSize = 10
	}
	log.Println(in.PageNum, "------", in.PageSize)
	switch in.Identity {
	case "mine": //员工|个人列表
		r, e := mysql.SingleParticipateList(in, mysql.ParticipateListSql(in))
		if e != nil {
			res.ErrCode = -1
			res.ErrMsg = e.Error()
			return res, nil
		}
		res.Data = r
	case "ent": //企业管理员
		r, e := mysql.AdminParticipateList(in, mysql.ParticipateListSql(in))
		if e != nil {
			res.ErrCode = -1
			res.ErrMsg = e.Error()
			return res, nil
		}
		res.Data = r
	}
	return res, nil
}

/*
已过投标截止日期项目
(1)	不显示终止投标倒计时
(2)	显示参标人信息
(3)	无终止参标操作入口
(4)	不能划转
(5)	不能参标
*/

// 参标动作：参标、终止参标、划转:in:参标；out:终止参标；transfer:划转
func ParticipateDo(in *bxcore.ParticipateActionReq) error {
	defer MC.Catch()
	b, entRoleId := util.IsAllowedParticipate(in.AppId, in.MgoUserId, in.NewUserId, in.AccountId, in.EntAccountId, in.EntId, in.EntUserId, in.PositionId, in.PositionType)
	if !b {
		return fmt.Errorf("暂无权限")
	}
	//企业版 判断是否是管理员
	//判断用户身份
	switch in.ActionType {
	case "in": //参标针对单个招标信息 或者 项目
		if in.BidIds == "" && in.ProjectIds == "" {
			return fmt.Errorf("缺少参数")
		}
		if err := GetProjectInfoByES(in); err != nil {
			return err
		}
		//是否允许多人参标
		if isAllow := mysql.IsALLow(in.EntId); !isAllow {
			if entUserName := mysql.IsParticipatedByBidId(in); entUserName != "" {
				return fmt.Errorf(fmt.Sprintf("该项目已被 %s 参标", entUserName))
			}
		}
		//保存参标信息  更新当前企业参标项目记录
		if err := mysql.SaveParticipateInfo(in); err != nil {
			return err
		}
	case "out": //终止参标
		if in.BidIds == "" && in.ProjectIds == "" {
			return fmt.Errorf("缺少参数")
		}
		if err := GetProjectInfoByES(in); err != nil {
			return err
		}
		if err := mysql.CancelParticipateInfo(in, entRoleId); err != nil {
			return err
		}
	case "transfer":
		//PC端 多个项目-》一个人
		//移动端  一个项目-》多个人
		if in.ProjectIds == "" {
			return fmt.Errorf("项目信息有误")
		}
		//个人版
		if in.PositionType == 0 {
			return fmt.Errorf("当前企业身份有误")
		}
		//非管理员
		if entRoleId == 0 { //1:企业管理员；2：部门管理员
			return fmt.Errorf("当前企业身份无权限")
		}
		//判断划转人
		if in.ToEntUserId == "" {
			return fmt.Errorf("划转对象不能为空")
		}
		//是否保留原跟踪人？
		isAllow := mysql.IsALLow(in.EntId)
		if (in.IsRetain || len(strings.Split(in.ToEntUserId, ",")) > 1) && !isAllow {
			//不允许多人参标，但是前端参数又是保留原参标人 互相矛盾
			return fmt.Errorf("当前项目只允许一人参标")
		}
		//in.ProjectIds //项目id
		projectIds := strings.Split(in.ProjectIds, ",")
		projectNum := 0
		for _, v := range projectIds {
			projectId := encrypt.DecodeArticleId2ByCheck(v)[0]
			if projectId == "" {
				continue
			}
			if err := mysql.TransferParticipateInfo(projectId, in); err != nil {
				log.Println(fmt.Sprintf("是否允许多人参标：%v, 项目id：%s，企业id：%d，划转对象entuserid：%s,划转异常：", isAllow, projectId, in.EntId, in.ToEntUserId))
				continue
			}
			projectNum += 1
		}
		if projectNum == 0 { //!= len(projectIds)
			return fmt.Errorf("划转失败")
		}
	}
	return nil
}

// 参标设置更新及设置内容
func GetParticipateSetInfo(in *bxcore.ParticipateSetUpInfoReq) (*bxcore.ParticipateSetUpInfoRes, error) {
	defer MC.Catch()
	res := &bxcore.ParticipateSetUpInfoRes{Data: &bxcore.ParticipateSetUpInfo{
		IsAllow:    0,
		BidType:    nil,
		RemindRule: nil,
	}}
	b, entRoleId := util.IsAllowedParticipate(in.AppId, in.MgoUserId, in.NewUserId, in.AccountId, in.EntAccountId, in.EntId, in.EntUserId, in.PositionId, in.PositionType)
	if !b {
		res.ErrMsg = "没有权限"
		res.Data = nil
		res.ErrCode = 0
	} else {
		switch in.SetAction {
		case "U": //update 更新设置信息
			res.Data = nil
			if entRoleId == 0 || entRoleId == 2 { //只有企业管理员有权限
				res.ErrCode = -1
				res.ErrMsg = "当前企业身份无权限"
			}
			if err := mysql.UpdateParticipateSetInfo(in); err != nil {
				res.ErrCode = -1
				res.ErrMsg = err.Error()
			}
		default: //默认查询对应设置信息
			//查询对应用户设置信息
			//未设置过 返回默认配置
			if info, err := mysql.GetParticipateSetInfo(in); err == nil {
				info.IsShow = MC.If(entRoleId == 1, entRoleId, int64(-1)).(int64)
				res.Data = info
			} else {
				res.ErrCode = -1
				res.ErrMsg = err.Error()
			}
		}
	}
	return res, nil
}

// 参标企业人员信息
func GetParticipatePersonInfo(in *bxcore.ParticipatePersonsReq) *bxcore.ParticipatePersonsRes {
	var (
		participateMap = map[int64]bool{}
	)
	if in.ProjectId != "" {
		in.ProjectId = encrypt.DecodeArticleId2ByCheck(in.ProjectId)[0]
		if in.ProjectId != "" {
			participateInfos := mysql.ParticipateProjectEnt(in.EntId, strings.Split(in.ProjectId, ","))
			if participateInfos != nil && len(*participateInfos) > 0 {
				participateInfo := (*participateInfos)[0]
				personIds := MC.ObjToString(participateInfo["personIds"])
				if personIds != "" {
					for _, p := range strings.Split(personIds, ",") {
						personId, _ := strconv.ParseInt(p, 10, 64)
						participateMap[personId] = true
					}
				}
			}
		}
	}
	//查询企业人员信息
	personInfos := mysql.GetPersonInfo(in.EntId, in.EntUserId, participateMap)
	return &bxcore.ParticipatePersonsRes{
		Data: personInfos,
	}
}

// 获取项目信息
func GetProjectInfoByES(in *bxcore.ParticipateActionReq) error {
	//参标和终止参标 单个项目；不进行批量操作
	in.ProjectIds = MC.If(in.ProjectIds != "", in.ProjectIds, in.BidIds).(string)
	var (
		tip = "参标"
	)
	switch in.ActionType {
	case "out":
		tip = "终止参标"
		//case "transfer":
		//	tip = "划转"
	}
	in.ProjectIds = strings.Split(in.ProjectIds, ",")[0]
	in.ProjectIds = encrypt.DecodeArticleId2ByCheck(in.ProjectIds)[0]
	if in.ProjectIds == "" {
		return fmt.Errorf("当前招标信息有误")
	}
	//当前项目是否符合参标条件
	//根据项目id查询project
	projectInfos := es.GetBidInfoByPId(in.ProjectIds)
	if projectInfos == nil || len(*projectInfos) == 0 {
		//当前项目是否符合参标条件
		//根据招标信息id 查询bidding
		projectInfos = es.GetProjectByInfoId(strings.Split(in.ProjectIds, ","))
		if projectInfos == nil || len(*projectInfos) == 0 {
			return fmt.Errorf(fmt.Sprintf("当前项目信息不满足%s条件", tip))
		}
	}
	if projectInfos != nil && len(*projectInfos) > 0 {
		//符合参标项目id
		projectInfo := (*projectInfos)[0]
		if projectInfo["_id"] != nil && MC.ObjToString(projectInfo["_id"]) != "" {
			bidEndTime := MC.Int64All(projectInfo["bidendtime"])           //1292126400:2010.12.12
			if bidEndTime > 1292126400 && bidEndTime < time.Now().Unix() { //招标结束时间已到期
				return fmt.Errorf("招标时间已结束")
			}
			//项目信息id
			in.ProjectIds = MC.ObjToString(projectInfo["_id"])
		} else {
			return fmt.Errorf("当前项目信息有误")
		}
	}
	return nil
}
