package backstage_service

import (
	"context"
	"errors"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"youngmini_server/app/model/backstage_model"
	"youngmini_server/app/utils"
)

var Order = serviceOrder{}

type serviceOrder struct {
}

// FindAll 查询所有订单
func (s *serviceOrder) FindAll(findAll *backstage_model.OrderFindAll) ([]*backstage_model.ResponseOrderInfo, int, error) {
	g.DB().SetDebug(true)
	contact := s.contact(findAll.OrderFind)
	var orders []*backstage_model.ResponseOrderInfo
	err := g.DB().Model("order_info").
		LeftJoin("task_base_info", "order_info.task_id = task_base_info.task_id").
		Fields("order_id", "order_info.task_id", "talent_id",
			"talent_platform_info_snap", "talent_personal_info_snap", "talent_post_addr_snap", "task_level_id", "complete_status", "complete_date",
			"signup_status", "order_status", "create_date", "task_base_info.deadline_time", "order_info.task_name", "prod_note", "order_status").
		Page(findAll.IndexPage, findAll.PageSize).
		Where(contact).
		OrderDesc("order_info.create_date").Scan(&orders)
	if err != nil {
		return nil, 0, err
	}
	count, err := g.DB().Model("order_info").Where(findAll.OrderFind).OmitEmpty().Count()
	if err != nil {
		return nil, 0, err
	}
	return orders, count, nil
}

// 拼接数据库数据库where语句字符串
func (s *serviceOrder) contact(order *backstage_model.OrderFindByCondition) string {
	var res []string
	if order.OrderId != "" {
		res = append(res, "order_id="+order.OrderId)
	}
	if order.TalentId != "" {
		res = append(res, "talent_id="+order.TalentId)
	}
	if order.TaskId != "" {
		res = append(res, "order_info.task_id="+order.TaskId)
	}
	if order.TaskName != "" {
		res = append(res, "order_info.task_name= '"+order.TaskName+"'")
	}
	var result string
	for k, value := range res {
		if k == 0 {
			result += value
		} else {
			result += " and " + value
		}
	}
	return result
}

// FindAddress 查询该订单下面所对应招募所需要的信息（刚开是需要查询地址，所以名称以地址开头）
func (s *serviceOrder) FindAddress(orderId *backstage_model.OrderFindAddress) (
	*backstage_model.OrderTaskRecruitRequirements, error) {
	g.DB().SetDebug(true)
	var requirement *backstage_model.OrderTaskRecruitRequirements
	err := g.DB().Model("task_recruit_requirements").Where("task_base_id", orderId.TaskId).Scan(&requirement)
	if err != nil {
		return nil, err
	}
	return requirement, nil
}

// ExecutiveInfo 查询执行信息下面所需要的所有信息（发货信息，初稿审核，作品审核，质检链接，数据链接，）
func (s *serviceOrder) ExecutiveInfo(orderId *backstage_model.OrderFindAddress) (*backstage_model.ResponseDeliveryInfo,
	*backstage_model.ResponseDraftReview, *backstage_model.ResponseOrderArticleReview, *backstage_model.ResponseLinkQuality,
	*backstage_model.ResponseDataQuality, error) {
	g.DB().SetDebug(true)
	var deliveryInfo *backstage_model.ResponseDeliveryInfo
	err := g.DB().Model("order_delivery_info").Where("order_id", orderId.OrderId).Scan(&deliveryInfo)
	if err != nil {
		return nil, nil, nil, nil, nil, err
	}
	var draftReview *backstage_model.ResponseDraftReview
	err = g.DB().Model("order_draft_review").Where("order_id", orderId.OrderId).Scan(&draftReview)
	if err != nil {
		return nil, nil, nil, nil, nil, err
	}
	var auditReview *backstage_model.ResponseOrderArticleReview
	err = g.DB().Model("order_article_review").Where("order_id", orderId.OrderId).Scan(&auditReview)
	if err != nil {
		return nil, nil, nil, nil, nil, err
	}
	var quality *backstage_model.ResponseLinkQuality
	err = g.DB().Model("order_link_quality").Where("order_id", orderId.OrderId).Scan(&quality)
	if err != nil {
		return nil, nil, nil, nil, nil, err
	}
	var dtaQuality *backstage_model.ResponseDataQuality
	err = g.DB().Model("order_data_review").Where("order_id", orderId.OrderId).Scan(&dtaQuality)
	if err != nil {
		return nil, nil, nil, nil, nil, err
	}
	return deliveryInfo, draftReview, auditReview, quality, dtaQuality, nil
}

// RegistrationInfo 报名信息所需信息
func (s *serviceOrder) RegistrationInfo(orderId *backstage_model.OrderFindAddress) (*backstage_model.OrderTaskBaseInfo,
	*backstage_model.OrderProduct, *backstage_model.OrderTaskRecruitTalentLevel, *backstage_model.OrderProductPhoto, error) {
	g.DB().SetDebug(true)
	var taskBaseInfo *backstage_model.OrderTaskBaseInfo
	err := g.DB().Model("task_base_info").Fields("task_name", "task_mode", "business_type",
		"content_form", "other_form", "product_id").
		Where("task_id", orderId.TaskId).Scan(&taskBaseInfo)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	var product *backstage_model.OrderProduct
	var productPhoto *backstage_model.OrderProductPhoto
	if taskBaseInfo != nil {
		err = g.DB().Model("product").Fields("product_specification").
			Where("product_id", taskBaseInfo.ProductId).Scan(&product)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		err = g.DB().Model("product_photo").Fields("photo_url").
			Where("product_id", taskBaseInfo.ProductId).Where("symbol", 1).Scan(&productPhoto)
		if err != nil {
			return nil, nil, nil, nil, err
		}
	}

	var taskRecruitTalentLevel *backstage_model.OrderTaskRecruitTalentLevel
	err = g.DB().Model("task_recruit_talent_level").Where("trt_id", orderId.TaskLevelId).Scan(&taskRecruitTalentLevel)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	return taskBaseInfo, product, taskRecruitTalentLevel, productPhoto, nil
}

// DraftFee 稿费明细界面信息
func (s *serviceOrder) DraftFee(orderId *backstage_model.OrderFindAddress) (*backstage_model.ResponseOrderDraftFee, error) {
	g.DB().SetDebug(true)
	var orderDraftFee *backstage_model.ResponseOrderDraftFee
	err := g.DB().Model("order_draft_fee").Where("order_id", orderId.OrderId).Scan(&orderDraftFee)
	if err != nil {
		return nil, err
	}
	return orderDraftFee, nil
}

// AddDelivery 添加订单发货的信息
func (s *serviceOrder) AddDelivery(addDelivery *backstage_model.AddDelivery) error {
	g.DB().SetDebug(true)
	// "delivery_status": 2 这个2代表发货成功
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		_, err := g.DB().Model("order_delivery_info").Data(g.Map{"logistics_company": addDelivery.LogisticsCompany,
			"tracking_num": addDelivery.TrackingNum, "delivery_time": addDelivery.DeliveryTime, "delivery_status": 2}).OmitEmpty().
			Where("order_id", addDelivery.OrderId).Update()
		if err != nil {
			return errors.New("添加地址信息失败，请检查")
		}
		err = utils.OrderProcedureManager.OnOperateOrder(addDelivery.OrderId, true,
			addDelivery.AlterListStatus.UserId, addDelivery.AlterListStatus.UserName)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return errors.New("创建失败，请检查必填字段是否未填")
	}

	return nil
}

// AddDraftReview 添加初稿审核信息
func (s *serviceOrder) AddDraftReview(addDraftReview *backstage_model.AddDraftReview) error {
	g.DB().SetDebug(true)
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		_, err := g.DB().Model("order_draft_review").Data(g.Map{"audit_opinion": addDraftReview.AuditOpinion,
			"confirm_time": addDraftReview.ConfirmTime}).OmitEmpty().
			Where("order_id", addDraftReview.OrderId).Update()
		if err != nil {
			return errors.New("添加初稿审核信息，请检查")
		}
		err = utils.OrderProcedureManager.OnOperateOrder(addDraftReview.OrderId, addDraftReview.AlterListStatus.AlterStatus,
			addDraftReview.AlterListStatus.UserId, addDraftReview.AlterListStatus.UserName, addDraftReview.AuditOpinion)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return errors.New("创建失败，请检查必填字段是否未填")
	}
	return nil
}

// AddAuditReview 添加作品审核信息
func (s *serviceOrder) AddAuditReview(addAuditReview *backstage_model.AddAuditReview) error {
	g.DB().SetDebug(true)
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		_, err := g.DB().Model("order_article_review").Data(g.Map{"audit_opinion": addAuditReview.AuditOpinion,
			"confirm_time": addAuditReview.ConfirmTime}).OmitEmpty().
			Where("order_id", addAuditReview.OrderId).Update()
		if err != nil {
			return errors.New("添加作品审核信息失败，请检查")
		}
		err = utils.OrderProcedureManager.OnOperateOrder(addAuditReview.AlterListStatus.OrderId, addAuditReview.AlterListStatus.AlterStatus,
			addAuditReview.AlterListStatus.UserId, addAuditReview.AlterListStatus.UserName, addAuditReview.AuditOpinion)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return err
	}

	return nil
}

// AddDataQuality 添加数据质检审核信息
func (s *serviceOrder) AddDataQuality(addDataQuality *backstage_model.AddDataQuality) error {
	g.DB().SetDebug(true)
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		_, err := g.DB().Model("order_data_review").Data(g.Map{"audit_opinion": addDataQuality.AuditOpinion,
			"confirm_time": addDataQuality.ConfirmTime}).
			Where("order_id", addDataQuality.OrderId).Update()
		if err != nil {
			return errors.New("添加数据质检审核信息失败，请检查")
		}
		err = utils.OrderProcedureManager.OnOperateOrder(addDataQuality.AlterListStatus.OrderId, addDataQuality.AlterListStatus.AlterStatus,
			addDataQuality.AlterListStatus.UserId, addDataQuality.AlterListStatus.UserName, addDataQuality.AuditOpinion)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return err
	}

	return nil
}

// AddLinkQuality 添加链接质检信息
func (s *serviceOrder) AddLinkQuality(addLinkQuality *backstage_model.AddLinkQuality) error {
	g.DB().SetDebug(true)
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		_, err := g.DB().Model("order_link_quality").Data(g.Map{"audit_opinion": addLinkQuality.AuditOpinion,
			"confirm_time": addLinkQuality.ConfirmTime}).OmitEmpty().
			Where("order_id", addLinkQuality.OrderId).Update()
		if err != nil {
			return errors.New("添加链接质检信息失败，请检查")
		}
		err = utils.OrderProcedureManager.OnOperateOrder(addLinkQuality.AlterListStatus.OrderId, addLinkQuality.AlterListStatus.AlterStatus,
			addLinkQuality.AlterListStatus.UserId, addLinkQuality.AlterListStatus.UserName, addLinkQuality.AuditOpinion)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return err
	}

	return nil
}

// AlterListStatus 修改订单状态
func (s *serviceOrder) AlterListStatus(alterStatus *backstage_model.AlterListStatus) error {
	//查询订单当前状态
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		err := utils.OrderProcedureManager.OnOperateOrder(alterStatus.OrderId, alterStatus.AlterStatus,
			alterStatus.UserId, alterStatus.UserName)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return errors.New("创建失败，请检查必填字段是否未填")
	}
	return nil
}

// ChargesDetail 查询一个订单下面所对应的扣款明细
func (s *serviceOrder) ChargesDetail(orderId *backstage_model.AcquiredOrderId) ([]*backstage_model.ResponseBobocoinDeductRecord, error) {
	g.DB().SetDebug(true)
	var result []*backstage_model.ResponseBobocoinDeductRecord
	err := g.DB().Model("bobocoin_deduct_record").Where("order_id", orderId.OrderId).Scan(&result)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// QueryTaskRecruitTalentLevel 查询招募等级表
func (s *serviceOrder) QueryTaskRecruitTalentLevel(taskLevelId *backstage_model.AcquiredOrderId) (*backstage_model.ResponseTaskRecruitTalentLevel, error) {
	g.DB().SetDebug(true)
	var result *backstage_model.ResponseTaskRecruitTalentLevel
	err := g.DB().Model("task_recruit_talent_level").Where("trt_id", taskLevelId.TaskLevelId).Scan(&result)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// AddBobocoinIncomeRecord 订单完成后需要在收入里面加一条信息
func (s *serviceOrder) AddBobocoinIncomeRecord(incomeRecord *backstage_model.RequestBobocoinIncomeRecord) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("bobocoin_income_record").Data(g.Map{"bobocoin_value": incomeRecord.BobocoinValue,
		"order_id": incomeRecord.OrderId, "recruit_level_id": incomeRecord.RecruitLevelId, "talent_id": incomeRecord.TalentId}).Insert()
	if err != nil {
		return errors.New("参数错误，请检查")
	}
	return nil
}
