package service

import (
	"fmt"
	"strconv"
	"time"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/entity"
	"youngee_b_api/app/vo"
)

type CooperationService struct{}

// 服务商搜索
func (s CooperationService) SearchSupplier(param *vo.SupplierSearchParam) ([]*vo.ReSupplierPreview, error) {
	var reSupplierPreviews []*vo.ReSupplierPreview
	suppliers, err := dao.SupplierDao{}.GetSuppliersByMsg(param.FieldName)
	if err != nil {
		return reSupplierPreviews, err
	}
	for _, supplier := range suppliers {
		// 判断该服务商是否已在商家库
		exist, _ := dao.EnterpriseSupplierCooperateDao{}.EnterpriseDatabaseCheck(param.EnterpriseId, supplier.SupplierID)
		reSupplierPreview := &vo.ReSupplierPreview{
			SupplierId:   supplier.SupplierID,
			HeadUrl:      "",
			SupplierName: supplier.SupplierName,
			SupplierType: supplier.SupplierType,
			CompanyName:  supplier.CompanyName,
			Name:         supplier.Name,
			Existence:    exist,
		}
		reSupplierPreviews = append(reSupplierPreviews, reSupplierPreview)
	}
	return reSupplierPreviews, nil
}

// 服务商入库批量邀请
func (s CooperationService) InviteSupplier(param *vo.SupplierInviteParam) error {
	// 要求传入的服务商都是未在该商家库的
	var records []*entity.EnterpriseSupplierCooperate
	for _, supplierId := range param.SupplierIds {
		record := &entity.EnterpriseSupplierCooperate{
			EnterpriseId:    param.EnterpriseId,
			SupplierId:      supplierId,
			CooperateNum:    1,
			CooperateStatus: 1,
			CreateTime:      time.Now(),
		}
		if param.SubAccountId == 0 {
			record.BOperator = param.EnterpriseId
			record.BOperatorType = 1
		} else {
			record.BOperator = strconv.Itoa(int(param.SubAccountId))
			record.BOperatorType = 2
		}
		records = append(records, record)
	}
	err := dao.EnterpriseSupplierCooperateDao{}.InsertBatch(records)

	return err
}

// 在库服务商列表
func (s CooperationService) GetEnterprisePoolList(param *vo.SupplierSearchInPoolParam) (vo.ResultVO, error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	var reSupplierPoolInfos []*vo.ReSupplierPoolInfo
	var enterpriseOperator string
	enterpriseSupplierCooperates, total, _ := dao.EnterpriseSupplierCooperateDao{}.GetSupplierByEnterprise(param.EnterpriseId, param.Page, param.PageSize)
	for _, enterpriseSupplierCooperate := range enterpriseSupplierCooperates {
		// 获取商家操作人姓名
		bOperator := enterpriseSupplierCooperate.BOperator
		if enterpriseSupplierCooperate.BOperatorType == 1 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(bOperator)
			if err == nil && enterprise != nil {
				enterpriseOperator = enterprise.BusinessName
			}
		} else if enterpriseSupplierCooperate.BOperatorType == 2 {
			subAccountId, err := strconv.ParseInt(bOperator, 10, 64)
			if err != nil {
				fmt.Println("GetEnterprisePoolList==subAccountId 转换出错:", err)
			} else {
				subAccount, err := dao.SubAccountDao{}.GetSubAccount(subAccountId)
				if err == nil && subAccount != nil {
					enterpriseOperator = subAccount.SubAccountName
				}
			}
		}
		supplier, err := dao.SupplierDao{}.GetSupplierInfoById(enterpriseSupplierCooperate.SupplierId)
		if err != nil {
			continue
		}
		supplierPreview := &vo.ReSupplierPreview{
			SupplierId:   supplier.SupplierID,
			HeadUrl:      "",
			SupplierName: supplier.SupplierName,
			SupplierType: supplier.SupplierType,
			CompanyName:  supplier.CompanyName,
			Name:         supplier.Name,
			Existence:    true,
		}
		reSupplierPoolInfo := &vo.ReSupplierPoolInfo{
			SupplierPreview:    supplierPreview,
			PhoneNumber:        supplier.PhoneNumber,
			WechatId:           "",
			WechatUrl:          "",
			CooperateNum:       enterpriseSupplierCooperate.CooperateNum,
			UploadTalentNum:    enterpriseSupplierCooperate.UploadTalentNum,
			CooperateTalentNum: enterpriseSupplierCooperate.CooperateTalentNum,
			AgreeTime:          enterpriseSupplierCooperate.AgreeTime.Format("2006-01-02 15:04:05"),
			EnterpriseOperator: enterpriseOperator,
		}
		reSupplierPoolInfos = append(reSupplierPoolInfos, reSupplierPoolInfo)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reSupplierPoolInfos,
	}
	return result, nil
}

// 服务商邀请待确认列表
func (s CooperationService) GetSupplierConfirmingList(param *vo.SupplierConfirmingParam) (vo.ResultVO, error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	var reSupplierConfirmingInfos []*vo.ReSupplierConfirmingInfo
	var enterpriseOperator string
	enterpriseSupplierCooperates, total, _ := dao.EnterpriseSupplierCooperateDao{}.GetSupplierConfirmingList(param.EnterpriseId, param.Page, param.PageSize)
	for _, enterpriseSupplierCooperate := range enterpriseSupplierCooperates {
		// 获取商家操作人姓名
		bOperator := enterpriseSupplierCooperate.BOperator
		if enterpriseSupplierCooperate.BOperatorType == 1 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(bOperator)
			if err == nil && enterprise != nil {
				enterpriseOperator = enterprise.BusinessName
			}
		} else if enterpriseSupplierCooperate.BOperatorType == 2 {
			subAccountId, err := strconv.ParseInt(bOperator, 10, 64)
			if err != nil {
				fmt.Println("GetSupplierConfirmingList==subAccountId 转换出错:", err)
			} else {
				subAccount, err := dao.SubAccountDao{}.GetSubAccount(subAccountId)
				if err == nil && subAccount != nil {
					enterpriseOperator = subAccount.SubAccountName
				}
			}
		}
		supplier, err := dao.SupplierDao{}.GetSupplierInfoById(enterpriseSupplierCooperate.SupplierId)
		var supplierPreview *vo.ReSupplierPreview
		var phoneNumber string
		if err == nil {
			supplierPreview = &vo.ReSupplierPreview{
				SupplierId:   supplier.SupplierID,
				HeadUrl:      "",
				SupplierName: supplier.SupplierName,
				SupplierType: supplier.SupplierType,
				CompanyName:  supplier.CompanyName,
				Name:         supplier.Name,
			}
			phoneNumber = supplier.PhoneNumber
		}
		reSupplierConfirmingInfo := &vo.ReSupplierConfirmingInfo{
			SupplierPreview:    supplierPreview,
			PhoneNumber:        phoneNumber,
			WechatId:           "",
			WechatUrl:          "",
			CreateTime:         enterpriseSupplierCooperate.CreateTime.Format("2006-01-02 15:04:05"),
			Status:             enterpriseSupplierCooperate.CooperateStatus,
			EnterpriseOperator: enterpriseOperator,
		}
		reSupplierConfirmingInfos = append(reSupplierConfirmingInfos, reSupplierConfirmingInfo)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reSupplierConfirmingInfos,
	}
	return result, nil
}

// 服务商管理-角标
func (t CooperationService) GetSupplierCount(param *vo.SupplierConfirmingParam) map[string]int64 {
	res := make(map[string]int64)
	var inPoolNum int64     // 在库服务商
	var confirmingNum int64 // 邀请待确认
	dao.Db.Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND cooperate_status = 2", param.EnterpriseId).Count(&inPoolNum)
	dao.Db.Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND cooperate_status = 1", param.EnterpriseId).Count(&confirmingNum)
	res["inPoolNum"] = inPoolNum
	res["confirmingNum"] = confirmingNum

	return res
}

// 服务商合作-服务商列表
func (s CooperationService) GetSupplierInTargetTaskList(param *vo.SupplierSearchInTargetTaskParam) (vo.ResultVO, error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = 10
	}
	var reSupplierTargetTasks []*vo.ReSupplierTargetTask
	var total int64
	result := vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reSupplierTargetTasks,
	}
	var enterpriseSupplierCooperates []*entity.EnterpriseSupplierCooperate
	var sProjectInfos []*entity.SProjectInfo
	var sLocalLifeInfos []*entity.SLocalLifeInfo
	var enterpriseOperator string
	if param.Status == 1 { // 可邀约
		enterpriseSupplierCooperates, total, _ = dao.EnterpriseSupplierCooperateDao{}.GetSupplierByEnterprise(param.EnterpriseId, param.Page, param.PageSize)
	} else if param.Status == 2 { // 邀约中
		if param.TaskType == 2 {
			// 品牌种草
			sProjectInfos, total, _ = dao.SProjectDao{}.GetSProjectByStatus(param.TaskId, 1, param.Page, param.PageSize)
		} else if param.TaskType == 3 {
			// 本地生活
			sLocalLifeInfos, total, _ = dao.SLocalLifeDao{}.GetSLocalLifeByStatus(param.TaskId, 1, param.Page, param.PageSize)
		}
	} else if param.Status == 3 { // 合作中
		if param.TaskType == 2 {
			// 品牌种草
			sProjectInfos, total, _ = dao.SProjectDao{}.GetSProjectByStatus(param.TaskId, 2, param.Page, param.PageSize)
		} else if param.TaskType == 3 {
			// 本地生活
			sLocalLifeInfos, total, _ = dao.SLocalLifeDao{}.GetSLocalLifeByStatus(param.TaskId, 2, param.Page, param.PageSize)
		}
	}
	if enterpriseSupplierCooperates == nil {
		if param.TaskType == 2 { // 种草
			for _, sProjectInfo := range sProjectInfos {
				supplierId := sProjectInfo.SupplierID
				enterpriseSupplierCooperate, err1 := dao.EnterpriseSupplierCooperateDao{}.GetDataByEnterpriseAndSupplier(param.EnterpriseId, supplierId)
				if err1 != nil {
					return result, err1
				}
				enterpriseSupplierCooperates = append(enterpriseSupplierCooperates, enterpriseSupplierCooperate)
			}
		} else if param.TaskType == 3 {
			// 本地生活
			for _, sLocalLifeInfo := range sLocalLifeInfos {
				supplierId := sLocalLifeInfo.SupplierID
				enterpriseSupplierCooperate, err1 := dao.EnterpriseSupplierCooperateDao{}.GetDataByEnterpriseAndSupplier(param.EnterpriseId, supplierId)
				if err1 != nil {
					return result, err1
				}
				enterpriseSupplierCooperates = append(enterpriseSupplierCooperates, enterpriseSupplierCooperate)
			}
		}
	}
	for _, enterpriseSupplierCooperate := range enterpriseSupplierCooperates {
		// 获取商家操作人姓名
		bOperator := enterpriseSupplierCooperate.BOperator
		if enterpriseSupplierCooperate.BOperatorType == 1 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(bOperator)
			if err == nil && enterprise != nil {
				enterpriseOperator = enterprise.BusinessName
			}
		} else if enterpriseSupplierCooperate.BOperatorType == 2 {
			subAccountId, err := strconv.ParseInt(bOperator, 10, 64)
			if err != nil {
				fmt.Println("GetEnterprisePoolList==subAccountId 转换出错:", err)
			} else {
				subAccount, err := dao.SubAccountDao{}.GetSubAccount(subAccountId)
				if err == nil && subAccount != nil {
					enterpriseOperator = subAccount.SubAccountName
				}
			}
		}
		supplier, err := dao.SupplierDao{}.GetSupplierInfoById(enterpriseSupplierCooperate.SupplierId)
		var supplierPreview *vo.ReSupplierPreview
		var phoneNumber string
		if err == nil {
			supplierPreview = &vo.ReSupplierPreview{
				SupplierId:   supplier.SupplierID,
				HeadUrl:      "",
				SupplierName: supplier.SupplierName,
				SupplierType: supplier.SupplierType,
				CompanyName:  supplier.CompanyName,
				Name:         supplier.Name,
				Existence:    true,
			}
			phoneNumber = supplier.PhoneNumber
		}
		reSupplierTargetTask := &vo.ReSupplierTargetTask{
			SupplierPreview:    supplierPreview,
			PhoneNumber:        phoneNumber,
			WechatId:           "",
			WechatUrl:          "",
			CooperateNum:       enterpriseSupplierCooperate.CooperateNum,
			UploadTalentNum:    enterpriseSupplierCooperate.UploadTalentNum,
			CooperateTalentNum: enterpriseSupplierCooperate.CooperateTalentNum,
			EnterpriseOperator: enterpriseOperator,
			Status:             param.Status,
		}
		reSupplierTargetTasks = append(reSupplierTargetTasks, reSupplierTargetTask)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reSupplierTargetTasks,
	}
	return result, nil
}

// 服务商合作-服务商列表角标
func (t CooperationService) GetSupplierInTargetCount(param *vo.SupplierSearchInTargetTaskParam) map[string]int64 {
	res := make(map[string]int64)
	var invitableNum int64   // 可邀约
	var invitingNum int64    // 邀约中
	var cooperatingNum int64 // 合作中
	dao.Db.Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND cooperate_status = ?", param.EnterpriseId, 2).Count(&invitableNum)
	if param.TaskType == 2 {
		// 品牌种草
		dao.Db.Model(&entity.SProjectInfo{}).Where("project_id = ? AND s_project_status = ?", param.TaskId, 1).Count(&invitingNum)
		dao.Db.Model(&entity.SProjectInfo{}).Where("project_id = ? AND s_project_status = ?", param.TaskId, 2).Count(&cooperatingNum)
	} else if param.TaskType == 3 {
		// 本地生活
		dao.Db.Model(&entity.SLocalLifeInfo{}).Where("local_id = ? AND s_local_status = ?", param.TaskId, 1).Count(&invitingNum)
		dao.Db.Model(&entity.SProjectInfo{}).Where("local_id = ? AND s_local_status = ?", param.TaskId, 2).Count(&cooperatingNum)

	}
	res["invitableNum"] = invitableNum
	res["invitingNum"] = invitingNum
	res["cooperatingNum"] = cooperatingNum

	return res
}

// 服务商合作-邀约合作
func (s CooperationService) InviteSupplierInTargetTask(param *vo.SupplierInviteInTargetTaskParam) error {
	var sProjectInfo entity.SProjectInfo
	if param.TaskType == 2 {
		sProjectInfo.ProjectID = param.TaskId
		sProjectInfo.SupplierID = param.SupplierId
		sProjectInfo.SProjectStatus = 1
		sProjectInfo.CreateTime = time.Now()
		if param.SubAccountId == 0 {
			sProjectInfo.BOperator = param.EnterpriseId
			sProjectInfo.BOperatorType = 1
		} else {
			sProjectInfo.BOperator = strconv.Itoa(int(param.SubAccountId))
			sProjectInfo.BOperatorType = 2
		}
		// 查找该 projectId 对应的信息
		project, err1 := dao.ProjectDAO{}.GetProjectById(param.TaskId)
		if err1 != nil {
			return err1
		}
		if project != nil {
			sProjectInfo.ProductID = project.ProductID
			sProjectInfo.ProjectName = project.ProjectName
			sProjectInfo.ProjectStatus = project.ProjectStatus
			sProjectInfo.ProjectType = project.ProjectType
			sProjectInfo.ProjectPlatform = project.ProjectPlatform
			sProjectInfo.ProjectForm = project.ProjectForm
			sProjectInfo.ContentType = project.ContentType
			sProjectInfo.EnterpriseID = param.EnterpriseId
			//sProjectInfo.ApplyNum = project.ApplyNum
			//sProjectInfo.RecruitNum = project.RecruitNum
		}
	} else if param.TaskType == 3 {
		// 本地生活
	}
	err := dao.SProjectDao{}.Insert(&sProjectInfo)
	return err
}
