package db

import (
	"context"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"
	"youngee_b_api/model/common_model"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
	"youngee_b_api/util"

	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
	"github.com/tidwall/gjson"
)

// 新增
func CreateLogistics(ctx context.Context, logistics gorm_model.YoungeeTaskLogistics, RecruitStrategyID int64) (*int64, error) {
	db := GetReadDB(ctx)
	err := db.Create(&logistics).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call CreateLogistics error,err:%+v", err)
		return nil, err
	}

	return &logistics.LogisticsID, nil
}

// 修改接口
func UpdateLogistics(ctx context.Context, logistics gorm_model.YoungeeTaskLogistics) (*int64, error) {
	db := GetReadDB(ctx)
	err := db.Model(&logistics).Where("task_id = ?", logistics.TaskID).Updates(logistics).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call UpdateLogistics error,err:%+v", err)
		return nil, err
	}
	return &logistics.LogisticsID, nil
}

// 更改签收时间
func SignForReceipt(ctx context.Context, taskID string) error {
	db := GetReadDB(ctx)
	t := time.Now()
	err := db.Model(gorm_model.YoungeeTaskLogistics{}).Where("task_id = ?", taskID).Updates(gorm_model.YoungeeTaskLogistics{
		Status:     1,
		SignedTime: &t,
	}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call UpdateLogistics error,err:%+v", err)
		return err
	}
	return nil
}

// 查询包含物流信息的task list
func GetTaskLogisticsList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskLogisticsInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询Task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2")
	// 根据Project条件过滤
	conditionType := reflect.TypeOf(conditions).Elem()
	conditionValue := reflect.ValueOf(conditions).Elem()
	var platform_nickname string = ""
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platform_nickname = fmt.Sprintf("%v", value.Interface())
				continue
			} else {
				db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
			}
		}
	}
	var taskInfos []gorm_model.YoungeeTaskInfo
	db = db.Model(gorm_model.YoungeeTaskInfo{})
	// 查询总数
	var totalTask int64
	if err := db.Count(&totalTask).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	db.Order("task_id").Find(&taskInfos)

	// 查询任务id
	var taskIds []string
	taskMap := make(map[string]gorm_model.YoungeeTaskInfo)
	for _, taskInfo := range taskInfos {
		taskIds = append(taskIds, taskInfo.TaskID)
		taskMap[taskInfo.TaskID] = taskInfo
	}
	db1 := GetReadDB(ctx)
	db1 = db1.Debug().Model(gorm_model.YoungeeTaskLogistics{})

	var logisticsInfos []gorm_model.YoungeeTaskLogistics
	db1 = db1.Model(gorm_model.YoungeeTaskLogistics{}).Where("task_id IN ?", taskIds).Find(&logisticsInfos)
	logisticsMap := make(map[string]gorm_model.YoungeeTaskLogistics)
	for _, logisticsInfo := range logisticsInfos {
		logisticsMap[logisticsInfo.TaskID] = logisticsInfo
	}
	// 查询总数
	var totalLogistics int64
	if err := db1.Count(&totalLogistics).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalLogistics > totalTask {
		misNum = totalLogistics - totalTask
	} else {
		misNum = totalTask - totalLogistics
	}
	logrus.Println("totalLogistics,totalTalent,misNum:", totalLogistics, totalTask, misNum)

	// 查询该页数据
	limit := pageSize + misNum
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("task_id").Limit(int(limit)).Offset(int(offset)).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskLogisticss []*http_model.TaskLogistics
	var taskLogisticss []*http_model.TaskLogisticsInfo
	var newTaskLogisticss []*http_model.TaskLogisticsInfo
	for _, taskId := range taskIds {
		TaskLogistics := new(http_model.TaskLogistics)
		TaskLogistics.Talent = taskMap[taskId]
		TaskLogistics.Logistics = logisticsMap[taskId]
		TalentPostAddrSnap := TaskLogistics.Talent.TalentPostAddrSnap
		regionCode, _ := strconv.Atoi(conv.MustString(gjson.Get(TalentPostAddrSnap, "region_code")))
		TaskLogistics.Region = GetRegion(ctx, regionCode)
		TaskLogisticss = append(TaskLogisticss, TaskLogistics)
	}

	taskLogisticss = pack.TaskLogisticsToTaskInfo(TaskLogisticss)

	for _, v := range taskLogisticss {
		if platform_nickname == "" {
			newTaskLogisticss = append(newTaskLogisticss, v)
		} else if strings.Contains(v.PlatformNickname, platform_nickname) {
			newTaskLogisticss = append(newTaskLogisticss, v)
		} else if strings.Contains(conv.MustString(v.TaskID), platform_nickname) {
			newTaskLogisticss = append(newTaskLogisticss, v)
		} else {
			totalTask--
		}
	}
	return newTaskLogisticss, totalTask, nil
}

// 修改任务表的物流状态
func ChangeLogisticsStatus(ctx context.Context, taskIds []string) error {
	db := GetReadDB(ctx)
	err := db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ?", taskIds).Update("logistics_status", 3).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[ChangeTaskStatus] error query mysql total, err:%+v", err)
		return err
	}
	return nil
}

func GetRegion(ctx context.Context, regionCode int) string {
	db4 := GetReadDB(ctx)
	var infoRegion *gorm_model.InfoRegion
	fmt.Printf("regionCode: %+v", regionCode)
	db4.Debug().Model(gorm_model.InfoRegion{}).Where("self_code = ?", regionCode).First(&infoRegion)

	provinceCode := conv.MustString(regionCode, "")[0:2] + "0000"
	var province *gorm_model.InfoRegion
	db4.Debug().Model(gorm_model.InfoRegion{}).Where("self_code = ?", conv.MustInt(provinceCode, 0)).First(&province)

	cityCode := conv.MustString(regionCode, "")[0:4] + "00"
	var city *gorm_model.InfoRegion
	db4.Debug().Model(gorm_model.InfoRegion{}).Where("self_code = ?", conv.MustInt(cityCode, 0)).First(&city)
	fmt.Printf(province.RegionName + city.RegionName + infoRegion.RegionName)
	return province.RegionName + city.RegionName + infoRegion.RegionName
}

// GetSpecialTaskLogisticsList 查询专项包含物流信息的task list
func GetSpecialTaskLogisticsList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskLogisticsInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询Task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2 and project_id = ?", projectID)
	// 根据Project条件过滤
	conditionType := reflect.TypeOf(conditions).Elem()
	conditionValue := reflect.ValueOf(conditions).Elem()
	var platformNickname string = ""
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platformNickname = fmt.Sprintf("%v", value.Interface())
				continue
			} else {
				db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
			}
		}
	}
	var taskInfos []gorm_model.YoungeeTaskInfo
	db = db.Model(gorm_model.YoungeeTaskInfo{})
	// 查询总数
	var totalTask int64
	if err := db.Count(&totalTask).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetSpecialTaskLogisticsList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	db.Order("task_id").Find(&taskInfos)

	// 查询任务id
	var taskIds []string
	taskMap := make(map[string]gorm_model.YoungeeTaskInfo)
	for _, taskInfo := range taskInfos {
		taskIds = append(taskIds, taskInfo.TaskID)
		taskMap[taskInfo.TaskID] = taskInfo
	}
	db1 := GetReadDB(ctx)
	db1 = db1.Debug().Model(gorm_model.YoungeeTaskLogistics{})

	var logisticsInfos []gorm_model.YoungeeTaskLogistics
	db1 = db1.Model(gorm_model.YoungeeTaskLogistics{}).Where("task_id IN ?", taskIds).Find(&logisticsInfos)
	logisticsMap := make(map[string]gorm_model.YoungeeTaskLogistics)
	for _, logisticsInfo := range logisticsInfos {
		logisticsMap[logisticsInfo.TaskID] = logisticsInfo
	}
	// 查询总数
	var totalLogistics int64
	if err := db1.Count(&totalLogistics).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetSpecialTaskLogisticsList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	// 查询该页数据
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("task_id").Limit(int(limit)).Offset(int(offset)).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSpecialTaskLogisticsList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskLogisticss []*http_model.SpecialTaskLogistics
	var taskLogisticss []*http_model.SpecialTaskLogisticsInfo
	var newTaskLogisticss []*http_model.SpecialTaskLogisticsInfo
	for _, taskId := range taskIds {
		TaskLogistics := new(http_model.SpecialTaskLogistics)
		TaskLogistics.Talent = taskMap[taskId]
		TaskLogistics.Logistics = logisticsMap[taskId]
		TalentPostAddrSnap := TaskLogistics.Talent.TalentPostAddrSnap
		regionCode, _ := strconv.Atoi(conv.MustString(gjson.Get(TalentPostAddrSnap, "region_code"), ""))
		TaskLogistics.Region = GetRegion(ctx, regionCode)
		TaskLogisticss = append(TaskLogisticss, TaskLogistics)
	}
	taskLogisticss = pack.SpecialTaskLogisticsToTaskInfo(TaskLogisticss)

	for _, v := range taskLogisticss {
		if platformNickname == "" {
			newTaskLogisticss = append(newTaskLogisticss, v)
		} else if strings.Contains(v.PlatformNickname, platformNickname) {
			newTaskLogisticss = append(newTaskLogisticss, v)
		} else if strings.Contains(v.TaskID, platformNickname) {
			newTaskLogisticss = append(newTaskLogisticss, v)
		} else {
			totalTask--
		}
	}
	return newTaskLogisticss, totalTask, nil
}

func GetSecTaskLogisticsList(ctx context.Context, secTaskList []*http_model.SecTaskInfo, taskStage int, productType int) ([]*http_model.SecTaskInfo, error) {
	db := GetReadDB(ctx)
	if taskStage != 6 { // 已发货
		// 查询youngee_task_logistics中物流信息
		var taskIds []string
		taskMap := make(map[string]*http_model.SecTaskInfo)
		for _, secTask := range secTaskList {
			taskIds = append(taskIds, secTask.SecTaskId)
			taskMap[secTask.SecTaskId] = secTask
		}

		var logisticsInfos []gorm_model.YoungeeTaskLogistics
		err := db.Model(gorm_model.YoungeeTaskLogistics{}).Where("task_id IN ?", taskIds).Find(&logisticsInfos).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
			return nil, err
		}
		logisticsMap := make(map[string]gorm_model.YoungeeTaskLogistics)
		for _, logisticsInfo := range logisticsInfos {
			logisticsMap[logisticsInfo.TaskID] = logisticsInfo
		}
		// 融合信息
		for i, secTask := range secTaskList {
			taskID := secTask.SecTaskId
			secTaskList[i].CompanyName = logisticsMap[taskID].CompanyName
			secTaskList[i].LogisticsNumber = logisticsMap[taskID].LogisticsNumber
			secTaskList[i].ExplorestorePeriod = logisticsMap[taskID].ExplorestorePeriod
			secTaskList[i].ExplorestoreStarttime = logisticsMap[taskID].ExplorestoreStarttime
			secTaskList[i].ExplorestoreEndtime = logisticsMap[taskID].ExplorestoreEndtime
		}
	}

	return secTaskList, nil
}
