package service

import (
	"context"
	"fmt"
	"time"
	"youngee_b_api/db"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"

	"github.com/gin-gonic/gin"
	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
)

var Logistics *logistics

type logistics struct {
}

// Create 在物流信息表插入记录
func (*logistics) Create(ctx context.Context, newLogistics http_model.CreateLogisticsRequest) (*http_model.CreateLogisticsData, error) {
	ThingsType := newLogistics.ThingsType
	StrategyID := newLogistics.StrategyID
	Logistics := gorm_model.YoungeeTaskLogistics{
		LogisticsID:           newLogistics.LogisticsID,
		TaskID:                newLogistics.TaskID,
		ThingsType:            int64(ThingsType),
		ExplorestoreStarttime: time.Now(),
		ExplorestoreEndtime:   time.Now(),
		DeliveryTime:          time.Now(),
	}
	fmt.Println("ThingsType:", ThingsType)
	//实物
	if ThingsType == 1 {
		Logistics.CompanyName = newLogistics.CompanyName
		Logistics.LogisticsNumber = newLogistics.LogisticsNumber
		Logistics.DeliveryTime = time.Now()
	} else if ThingsType == 3 {
		fmt.Println("开始时间：", newLogistics.ExplorestoreStarttime)
		fmt.Println("结束时间：", newLogistics.ExplorestoreEndtime)
		ExplorestoreStarttime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreStarttime, time.Local)
		ExplorestoreEndtime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreEndtime, time.Local)
		Logistics.ExplorestoreStarttime = ExplorestoreStarttime
		Logistics.ExplorestoreEndtime = ExplorestoreEndtime
	} else {
		Logistics.CouponCodeInformation = newLogistics.CouponCodeInformation
	}

	logisticsID, err := db.CreateLogistics(ctx, Logistics, StrategyID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateLogistics error,err:%+v", err)
		return nil, err
	}

	projectId, err1 := db.GetProjectIdByTaskId(ctx, newLogistics.TaskID)
	if err1 != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetProjectIdByTaskId error,err:%+v", err1)
		return nil, err1
	}

	// 查询StrategyID 通过 StrategyID 和 projectId
	RecruitStrategyId, err2 := db.GetRecruitStrategyIdByTS(ctx, *projectId, StrategyID)
	if err2 != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetStrategyIDByTS error,err:%+v", err1)
		return nil, err2
	}

	fmt.Println("RecruitStrategyId: ", *RecruitStrategyId)
	// 修改招募策略中已签收数量
	err = db.UpdateLogisticsNumber(ctx, *RecruitStrategyId, 1, -1, 0)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call UpdateLogisticsNumber error,err:%+v", err)
		return nil, err
	}
	// 修改task_info中发货状态
	err = db.UpdateLogisticsStatus(ctx, Logistics.TaskID, 2)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogisticsStatus error,err:%+v", err)
		return nil, err
	}

	// 修改task_info中发货时间
	err = db.UpdateLogisticsDate(ctx, Logistics.TaskID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogisticsDate error,err:%+v", err)
		return nil, err
	}
	// 修改task_info中任务阶段
	err = db.UpdateTaskStageByTaskId(ctx, Logistics.TaskID, 2, 5) //修改为待传初稿
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogisticsDate error,err:%+v", err)
		return nil, err
	}

	// 对应招募策略待发货--，已发货++

	// 记录任务日志-发货
	err = db.CreateTaskLog(ctx, Logistics.TaskID, "发货时间")
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateTaskLog error,err:%+v", err)
		return nil, err
	}

	err = db.CreateMessageByTaskId(ctx, 8, 2, Logistics.TaskID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateMessageByTaskId error,err:%+v", err)
		return nil, err
	}

	res := &http_model.CreateLogisticsData{
		LogisticsID: *logisticsID,
	}
	return res, nil
}

// 修改物流信息表
func (*logistics) Update(ctx context.Context, newLogistics http_model.CreateLogisticsRequest) (*http_model.CreateLogisticsData, error) {
	ThingsType := newLogistics.ThingsType
	Logistics := gorm_model.YoungeeTaskLogistics{
		LogisticsID:  newLogistics.LogisticsID,
		TaskID:       newLogistics.TaskID,
		ThingsType:   int64(ThingsType),
		DeliveryTime: time.Now(),
	}
	//实物
	if ThingsType == 1 {
		Logistics.CompanyName = newLogistics.CompanyName
		Logistics.LogisticsNumber = newLogistics.LogisticsNumber
	} else if ThingsType == 3 {
		fmt.Println("开始时间：", newLogistics.ExplorestoreStarttime)
		fmt.Println("结束时间：", newLogistics.ExplorestoreEndtime)
		ExplorestoreStarttime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreStarttime, time.Local)
		ExplorestoreEndtime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreEndtime, time.Local)
		Logistics.ExplorestoreStarttime = ExplorestoreStarttime
		Logistics.ExplorestoreEndtime = ExplorestoreEndtime
		// Logistics.ExplorestorePeriod = newLogistics.ExplorestorePeriod
	} else {
		Logistics.CouponCodeInformation = newLogistics.CouponCodeInformation
	}
	logisticsID, err := db.UpdateLogistics(ctx, Logistics)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogistics error,err:%+v", err)
		return nil, err
	}
	res := &http_model.CreateLogisticsData{
		LogisticsID: *logisticsID,
	}
	return res, nil
}

// 签收
func (*logistics) SignForReceipt(ctx *gin.Context, data http_model.SignForReceiptRequest) interface{} {
	projectId, err1 := db.GetProjectIdByTaskId(ctx, data.TaskStrategyIds[0].TaskId)
	if err1 != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetProjectIdByTaskId error,err:%+v", err1)
		return err1
	}
	// 签收时更新任务阶段
	project, err3 := db.GetProjectDetail(ctx, *projectId)
	if err3 != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetPorjectDetail error,err:%+v", err3)
		return err3
	}
	if project.ContentType == 1 {
		err := db.UpdateTaskStageByProjectId(ctx, *projectId, 2, 9)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
			return err
		}
	} else {
		err := db.UpdateTaskStageByProjectId(ctx, *projectId, 2, 7)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
			return err
		}
	}
	for _, value := range data.TaskStrategyIds {
		taskId := value.TaskId
		strategyId := conv.MustInt64(value.StrategyId)
		err := db.UpdateLogisticsStatus(ctx, taskId, 3)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[project service] call UpdateLogisticsStatus error,err:%+v", err)
			return err
		}

		// 签收时间
		err = db.SignForReceipt(ctx, taskId)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[project service] call SignForReceipt error,err:%+v", err)
			return err
		}

		// 查询StrategyID 通过 StrategyID 和 projectId
		StrategyID, err2 := db.GetRecruitStrategyIdByTS(ctx, *projectId, strategyId)
		if err2 != nil {
			logrus.WithContext(ctx).Errorf("[project service] call GetStrategyIDByTS error,err:%+v", err1)
			return err2
		}

		// 修改招募策略中已签收数量
		err = db.UpdateLogisticsNumber(ctx, *StrategyID, 0, 0, 1)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[project service] call UpdateLogisticsNumber error,err:%+v", err)
			return err
		}

		// 记录任务日志
		err = db.CreateTaskLog(ctx, taskId, "签收时间")
		if err != nil {
			logrus.WithContext(ctx).Errorf("[logistics service] call CreateTaskLog error,err:%+v", err)
			return err
		}

		err = db.CreateMessageByTaskId(ctx, 9, 2, taskId)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[logistics service] call CreateMessageByTaskId error,err:%+v", err)
			return err
		}
	}

	return nil
}

func (l *logistics) CreateSpecialLogistics(ctx context.Context, newLogistics http_model.CreateSpecialLogisticsRequest) (*http_model.SpecialLogisticsData, error) {
	ThingsType := newLogistics.ThingsType
	Logistics := gorm_model.YoungeeTaskLogistics{
		LogisticsID:           newLogistics.LogisticsID,
		TaskID:                newLogistics.TaskID,
		ThingsType:            int64(ThingsType),
		ExplorestoreStarttime: time.Now(),
		ExplorestoreEndtime:   time.Now(),
		DeliveryTime:          time.Now(),
	}
	//实物
	if ThingsType == 1 {
		Logistics.CompanyName = newLogistics.CompanyName
		Logistics.LogisticsNumber = newLogistics.LogisticsNumber
		Logistics.DeliveryTime = time.Now()
	} else if ThingsType == 3 {
		ExplorestoreStarttime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreStarttime, time.Local)
		ExplorestoreEndtime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreEndtime, time.Local)
		Logistics.ExplorestoreStarttime = ExplorestoreStarttime
		Logistics.ExplorestoreEndtime = ExplorestoreEndtime
	} else {
		Logistics.CouponCodeInformation = newLogistics.CouponCodeInformation
	}
	logisticsID, err := db.CreateLogistics(ctx, Logistics, 0)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateLogistics error,err:%+v", err)
		return nil, err
	}
	// 修改task_info中发货时间
	err = db.UpdateLogisticsDate(ctx, Logistics.TaskID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogisticsDate error,err:%+v", err)
		return nil, err
	}
	// 修改task_info中发货状态
	err = db.UpdateLogisticsStatus(ctx, Logistics.TaskID, 2)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogisticsStatus error,err:%+v", err)
		return nil, err
	}
	// 修改task_info中任务阶段
	err = db.UpdateTaskStageByTaskId(ctx, Logistics.TaskID, 2, 5) //修改为待传初稿
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogisticsDate error,err:%+v", err)
		return nil, err
	}
	// 记录任务日志-发货
	err = db.CreateTaskLog(ctx, Logistics.TaskID, "发货时间")
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateTaskLog error,err:%+v", err)
		return nil, err
	}
	err = db.CreateMessageByTaskId(ctx, 8, 2, Logistics.TaskID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateMessageByTaskId error,err:%+v", err)
		return nil, err
	}
	res := &http_model.SpecialLogisticsData{
		LogisticsID: *logisticsID,
	}
	return res, nil
}

func (*logistics) UpdateSpecialLogistics(ctx context.Context, newLogistics http_model.CreateSpecialLogisticsRequest) (*http_model.SpecialLogisticsData, error) {
	ThingsType := newLogistics.ThingsType
	Logistics := gorm_model.YoungeeTaskLogistics{
		LogisticsID:  newLogistics.LogisticsID,
		TaskID:       newLogistics.TaskID,
		ThingsType:   int64(ThingsType),
		DeliveryTime: time.Now(),
	}
	//实物
	if ThingsType == 1 {
		Logistics.CompanyName = newLogistics.CompanyName
		Logistics.LogisticsNumber = newLogistics.LogisticsNumber
	} else if ThingsType == 3 {
		ExplorestoreStarttime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreStarttime, time.Local)
		ExplorestoreEndtime, _ := time.ParseInLocation("2006-01-02 15:04:05", newLogistics.ExplorestoreEndtime, time.Local)
		Logistics.ExplorestoreStarttime = ExplorestoreStarttime
		Logistics.ExplorestoreEndtime = ExplorestoreEndtime
	} else {
		Logistics.CouponCodeInformation = newLogistics.CouponCodeInformation
	}
	logisticsID, err := db.UpdateLogistics(ctx, Logistics)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call UpdateLogistics error,err:%+v", err)
		return nil, err
	}
	res := &http_model.SpecialLogisticsData{
		LogisticsID: *logisticsID,
	}
	return res, nil
}

func (l *logistics) SignForSpecialLogistic(ctx *gin.Context, logisticRequest http_model.SignForSpecialLogisticRequest) error {
	projectId, err1 := db.GetProjectIdByTaskId(ctx, logisticRequest.TaskId)
	if err1 != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetProjectIdByTaskId error,err:%+v", err1)
		return err1
	}
	// 签收时更新任务阶段
	project, err3 := db.GetProjectDetail(ctx, *projectId)
	if err3 != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetPorjectDetail error,err:%+v", err3)
		return err3
	}
	if project.ContentType == 1 {
		err := db.UpdateTaskStageByProjectId(ctx, *projectId, 2, 9)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
			return err
		}
	} else {
		err := db.UpdateTaskStageByProjectId(ctx, *projectId, 2, 7)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
			return err
		}
	}

	taskId := logisticRequest.TaskId
	err := db.UpdateLogisticsStatus(ctx, taskId, 3)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call UpdateLogisticsStatus error,err:%+v", err)
		return err
	}

	// 签收时间
	err = db.SignForReceipt(ctx, taskId)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call SignForReceipt error,err:%+v", err)
		return err
	}

	// 记录任务日志
	err = db.CreateTaskLog(ctx, taskId, "签收时间")
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateTaskLog error,err:%+v", err)
		return err
	}
	err = db.CreateMessageByTaskId(ctx, 9, 2, taskId)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics service] call CreateMessageByTaskId error,err:%+v", err)
		return err
	}
	return nil
}
