package mysql

import (
	"app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/date"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/util/gconv"
	IC "jyBXCore/rpc/init"
	"jyBXCore/rpc/util"
	"log"
	"strconv"
	"strings"
	"time"
)

type ParStage struct {
	EntId      int64
	EntUserId  int64
	PositionId int64
	ProjectId  string
}

func NewParStage(entId, entUserId, positionId int64, projectId string) *ParStage {
	return &ParStage{
		EntId:      entId,
		EntUserId:  entUserId,
		PositionId: positionId,
		ProjectId:  projectId,
	}
}

type StageInfo struct {
	Name  string `json:"name"`
	Value string `json:"value"`
	Date  string `json:"date"`
}

func (p *ParStage) UpdateStage() {
	var (
		recordsMap      = map[string]*StageInfo{}
		updateInsertMap = map[string]interface{}{
			"ent_id":     p.EntId,
			"project_id": p.ProjectId,
		}
		now                     = time.Now()
		createDate              string
		lastDate                int64 //最新一次更新时间
		entUserIdBool           = map[string]bool{}
		positionIdBool          = map[string]bool{}
		entUserIds, positionIds []string
		findSql                 = map[string]interface{}{
			"project_id": p.ProjectId,
			"ent_id":     p.EntId,
		}
		state         = "已完成"
		isParticipate bool
	)
	//个人版
	if p.EntId == 0 {
		findSql["position_id"] = p.PositionId
	}
	recordsContentData := IC.BaseMysql.Find(ParticipateBidRecordsTable, findSql, "", "create_date", -1, -1)
	//判断 当前企业或用户是否已参标
	findSql["state"] = 0
	if count := IC.BaseMysql.Count("participate_user", findSql); count > 0 {
		isParticipate = true
	}
	if recordsContentData != nil && len(*recordsContentData) > 0 {
		for _, rv := range *recordsContentData {
			var (
				recordContent = gconv.String(rv["record_content"])
				content, ok   = util.ConvertJSONString(recordContent)
				contentMap    = map[string]interface{}{}
				contentStr    string
				entUserId     = strconv.FormatInt(gconv.Int64(rv["ent_user_id"]), 10)
				positionId    = strconv.FormatInt(gconv.Int64(rv["position_id"]), 10)
				cdStr         = strings.Split(gconv.String(rv["create_date"]), " ")[0]
				cdTime, _     = time.ParseInLocation(date.Date_Full_Layout, gconv.String(rv["create_date"]), time.Local)
			)
			lastDate = common.If(cdTime.Unix() > lastDate, cdTime.Unix(), lastDate).(int64)
			createDate = common.If(cdStr != "", cdStr, createDate).(string)
			if createDate != "" {
				createDate = strings.ReplaceAll(createDate, "-", ".")
			}
			if ok {
				contentMap = gconv.Map(content)
				if contentMap["afterMap"] != nil {
					afterMap, _ := util.ConvertJSONString(gconv.String(contentMap["afterMap"]))
					afterM := gconv.Map(afterMap)
					if afterM != nil {
						if bidStage := gconv.Map(afterM["bidStage"]); bidStage != nil {
							status := gconv.String(bidStage["status"])
							values := gconv.SliceStr(bidStage["value"])
							if len(values) > 0 {
								for _, bv := range values {
									if status == "调整" || recordsMap[bv].Date == "" {
										recordsMap[bv] = &StageInfo{
											Name:  fmt.Sprintf("%s（阶段）", bv),
											Value: state,
											Date:  createDate,
										}
									}
								}
							}
						}
						if bidType := gconv.Map(afterM["bidType"]); bidType != nil {
							value := gconv.String(bidType["value"])
							if value != "" {
								recordsMap["投标类型"] = &StageInfo{
									Name:  "投标类型",
									Value: value,
									Date:  createDate,
								}
							}
						}
					}
				}
				afterMap, _ := util.ConvertJSONString(gconv.String(contentMap["after"]))
				afterM := gconv.Map(afterMap)
				if afterM != nil {
					updateInsertMap["bid_way"] = gconv.Int64(afterM["bidType"])
				}
			} else {
				contentStr = gconv.String(content)
				//参标：多人参标同一个项目，查看当前项目是否已被当前企业其他员工参标，如果已被其他员工参标，则参标时间不更新。
				//参标后 未被 终止参标
				if strings.TrimSpace(contentStr) == "参标" {
					recordsMap["参标状态"] = &StageInfo{
						Name:  "参标状态",
						Value: "已参标",
						Date:  createDate,
					}
				}
				//终止参标--
				if strings.Contains(contentStr, "终止参标") {
					if !isParticipate {
						recordsMap[contentStr] = &StageInfo{
							Name:  "终止参标",
							Value: "已终止",
							Date:  createDate,
						}
					}
				}
			}
			//entUserIds 操作和被操作企业用户id集合 408
			if !entUserIdBool[entUserId] {
				entUserIdBool[entUserId] = true
				entUserIds = append(entUserIds, entUserId)
			}
			//职位id
			if !positionIdBool[positionId] {
				positionIdBool[positionId] = true
				positionIds = append(positionIds, positionId)
			}
		}
	}
	if recordsMap != nil {
		var stages []*StageInfo
		for _, sv := range IC.C.Stages {
			v := strings.Split(sv, "##")[0]
			records := recordsMap[v]
			if records == nil {
				records = &StageInfo{
					Name:  strings.ReplaceAll(sv, "##", "（阶段）"),
					Value: "-",
				}
			}
			stages = append(stages, &StageInfo{
				Name:  records.Name,
				Value: records.Value,
				Date:  records.Date,
			})
		}
		// 转换结构体数组为JSON字符串
		jsonData, err := json.Marshal(stages)
		if err != nil {
			fmt.Println("Failed to marshal struct array to JSON:", err)
			return
		}
		updateInsertMap["stage"] = string(jsonData)
		updateInsertMap["ent_user_ids"] = strings.Join(entUserIds, ",")
		updateInsertMap["is_participate"] = common.If(isParticipate, 1, 0).(int)
		updateInsertMap["position_ids"] = strings.Join(positionIds, ",")
		updateSelectSlq := fmt.Sprintf(`SELECT * FROM %s WHERE ent_id = ? and project_id = ? `, ParticipateStage)
		if p.EntId == 0 {
			add := fmt.Sprintf(" and  FIND_IN_SET('%s', position_ids) > 0", strconv.FormatInt(p.PositionId, 10))
			updateSelectSlq = fmt.Sprintf("%s%s", updateSelectSlq, add)
		}
		if s := IC.BaseMysql.SelectBySql(updateSelectSlq, p.EntId, p.ProjectId); len(*s) > 0 {
			updateInsertMap["update_date"] = date.FormatDateByInt64(&lastDate, date.Date_Full_Layout)
			if ok := IC.BaseMysql.Update(ParticipateStage, map[string]interface{}{
				"id": gconv.Int64((*s)[0]["id"]),
			}, updateInsertMap); !ok {
				log.Println("参标操作记录 更新异常：", gconv.Int64((*s)[0]["id"]))
			}
		} else {
			updateInsertMap["create_date"] = date.FormatDate(&now, date.Date_Full_Layout)
			updateInsertMap["update_date"] = date.FormatDateByInt64(&lastDate, date.Date_Full_Layout)
			if i := IC.BaseMysql.Insert(ParticipateStage, updateInsertMap); i == 0 {
				log.Println("参标操作记录 插入异常：", updateInsertMap)
			}
		}
	}
}
