package service

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"strconv"
	"strings"
	"time"
	"youngee_b_api/db"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
)

var Supplier *supplier

type supplier struct {
}

// CreateSupplier 创建younggee平台用户账号与服务商信息
func (*supplier) CreateSupplier(ctx context.Context, phone string) (*http_model.RegisterData, error) {
	// 1. 创建YG平台用户
	user := gorm_model.YounggeeUser{
		Phone:         phone,
		User:          "1003",
		Username:      phone,
		Password:      "1003",
		RealName:      "",
		Role:          "6",
		Email:         "",
		LastLoginTime: time.Now().UTC().Local(),
	}
	userId, err := db.CreateUser(ctx, user)
	if err != nil {
		log.Infof("[CreateEnterpriseUser] fail,err:%+v", err)
		return nil, err
	} else {
		// 2. 创建服务商信息
		supplier := &gorm_model.YoungeeSupplier{
			SupplierName: phone,
			PhoneNumber:  phone,
			UserId:       *userId,
		}
		supplierId, err := db.CreateSupplier(ctx, *supplier)
		fmt.Println(supplierId)
		if err != nil {
			log.Infof("[CreateEnterpriseUser] fail,err:%+v", err)
			return nil, err
		}
		res := &http_model.RegisterData{
			UserID: *userId,
		}
		return res, nil
	}
}

// GetSupplierIncomeList 查询服务商收入列表
func (*supplier) GetSupplierIncomeList(ctx context.Context, req *http_model.FullSProjectIncomeListRequest) (*http_model.FullSProjectIncomeData, error) {
	// 1. 查询
	supplierIncome, total, err := db.GetSupplierIncomeList(ctx, req)
	if err != nil {
		return nil, nil
	}

	// 2. 整理数据格式
	var sProjectIncomeData *http_model.FullSProjectIncomeData
	sProjectIncomeData = &http_model.FullSProjectIncomeData{}
	sProjectIncomeData.SProjectIncomeList = supplierIncome
	sProjectIncomeData.Total = total
	return sProjectIncomeData, nil
}

// CreateSupplierInvoice 创建服务商发票
func (*supplier) CreateSupplierInvoice(ctx context.Context, req *http_model.CreateSupplierInvoiceRequest) error {
	// 1. 数据转换
	var invoiceData *gorm_model.YounggeeSupplierInvoice
	invoiceData = &gorm_model.YounggeeSupplierInvoice{
		SupplierId:    req.SupplierId,
		InvoiceStatus: 1,
		IncomeIds:     req.IncomeIds,
	}
	if req.SOperatorType == 1 {
		invoiceData.SOperatorType = 1
		invoiceData.SOperator = req.SupplierId
	} else if req.SOperatorType == 2 {
		invoiceData.SOperatorType = 2
		invoiceData.SOperator = req.SubAccountId
	}

	// 2. 插入数据库
	err := db.CreateSupplierInvoice(ctx, invoiceData)
	if err != nil {
		return err
	}
	return nil
}

// UpdateSupplierInvoice 更新服务商发票
func (*supplier) UpdateSupplierInvoice(ctx context.Context, req *http_model.UpdateSupplierInvoiceRequest) error {
	// 1. 数据转换
	var invoiceData *gorm_model.YounggeeSupplierInvoice
	var currentTime time.Time
	currentTime = time.Now()
	invoiceData = &gorm_model.YounggeeSupplierInvoice{
		InvoiceId:         req.InvoiceId,
		InvoiceUrl:        req.InvoiceUrl,
		Company:           req.Company,
		UploadInvoiceTime: &currentTime,
	}

	// 2. 更新
	err := db.UpdateSupplierInvoice(ctx, invoiceData)
	if err != nil {
		return err
	}

	// 3. 更新服务商收入状态
	incomeIds, dbErr := db.GetIncomeIdsByInvoiceId(ctx, req.InvoiceId)
	if dbErr != nil {
		return dbErr
	}
	if incomeIds == "" {
		return nil
	}
	strSlice := strings.Split(incomeIds, ",")
	intSlice := make([]int, len(strSlice))
	for i, s := range strSlice {
		num, err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("转换错误:", err)
			return err
		}
		intSlice[i] = num
	}
	updateSupplierIncomeErr := db.UpdateSupplierIncomeStatus(ctx, intSlice, 3)
	if updateSupplierIncomeErr != nil {
		return updateSupplierIncomeErr
	}

	return nil
}

// UpdateSupplierIncomeStatus 修改服务商收入状态
func (*supplier) UpdateSupplierIncomeStatus(ctx context.Context, incomeIds string, incomeStatus int) error {
	// 1. 转换incomeIds为数组
	strSlice := strings.Split(incomeIds, ",")
	intSlice := make([]int, len(strSlice))
	for i, s := range strSlice {
		num, err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("转换错误:", err)
			return err
		}
		intSlice[i] = num
	}

	// 2. 修改数据库中数据
	updateSupplierIncomeErr := db.UpdateSupplierIncomeStatus(ctx, intSlice, incomeStatus)
	if updateSupplierIncomeErr != nil {
		return updateSupplierIncomeErr
	}
	return nil
}

// GetSupplierInvoiceList 查找服务商发票列表
func (*supplier) GetSupplierInvoiceList(ctx context.Context, req *http_model.SupplierInvoiceListRequest) (*http_model.SupplierInvoiceListData, error) {
	// 1. 查询服务商发票信息
	supplierInvoiceList, total, err := db.GetInvoiceListBySupplierId(ctx, req.SupplierId, req.InvoiceStatus, 4, req.PageSize, req.PageNum)
	if err != nil {
		return nil, err
	}

	// 2. 根据发票中的incomeIds去查找任务及其服务费收入
	var supplierInvoiceData *http_model.SupplierInvoiceListData
	supplierInvoiceData = &http_model.SupplierInvoiceListData{}

	for _, supplierInvoice := range supplierInvoiceList {
		var supplierInvoiceInfo *http_model.SupplierInvoiceInfo
		supplierInvoiceInfo = &http_model.SupplierInvoiceInfo{}

		// 2.1. 基础信息填入
		supplierInvoiceInfo.UploadInvoiceTime = supplierInvoice.UploadInvoiceTime
		supplierInvoiceInfo.InvoiceUrl = supplierInvoice.InvoiceUrl
		supplierInvoiceInfo.AgreeTime = supplierInvoice.AgreeTime
		supplierInvoiceInfo.RejectTime = supplierInvoice.RejectTime
		supplierInvoiceInfo.Company = supplierInvoice.Company
		supplierInvoiceInfo.SOperator = supplierInvoice.SOperator
		supplierInvoiceInfo.FailReason = supplierInvoice.FailReason

		// 2.2. 任务及其收入信息填入
		incomeIds := supplierInvoice.IncomeIds
		strSlice := strings.Split(incomeIds, ",")
		intSlice := make([]int, len(strSlice))
		for i, s := range strSlice {
			num, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println("转换错误:", err)
				return nil, err
			}
			intSlice[i] = num
		}
		for _, incomeId := range intSlice {
			var sTaskInfo *http_model.STaskInfo
			sTaskInfo = &http_model.STaskInfo{}
			currIncome, incomeErr := db.GetIncomeInfoByIncomeId(ctx, incomeId)
			if incomeErr != nil {
				return nil, incomeErr
			}
			sTaskInfo.ServiceCharge = currIncome.SupplierChargeActual
			if currIncome.IncomeType == 1 {
				sTaskInfo.Id = currIncome.SProjectID
			} else if currIncome.IncomeType == 3 {
				sTaskInfo.Id = currIncome.SLocalLifeID
			}
			supplierInvoiceInfo.STaskInfo = append(supplierInvoiceInfo.STaskInfo, sTaskInfo)
		}
		supplierInvoiceData.SupplierInvoiceList = append(supplierInvoiceData.SupplierInvoiceList, supplierInvoiceInfo)
	}
	supplierInvoiceData.Total = total
	return supplierInvoiceData, nil
}

// GetSupplierToWithdrawList 服务商待提现列表
func (*supplier) GetSupplierToWithdrawList(ctx context.Context, req *http_model.SupplierToWithdrawListRequest) (*http_model.SupplierToWithdrawListData, error) {
	// 1. 查询服务商发票信息
	supplierInvoiceList, total, err := db.GetInvoiceListBySupplierId(ctx, req.SupplierId, 3, 1, req.PageSize, req.PageNum)
	if err != nil {
		return nil, err
	}

	// 2. 根据发票中的incomeIds去查找任务及其服务费收入
	var supplierInvoiceData *http_model.SupplierToWithdrawListData
	supplierInvoiceData = &http_model.SupplierToWithdrawListData{}

	for _, supplierInvoice := range supplierInvoiceList {
		var supplierInvoiceInfo *http_model.SupplierToWithdrawInfo
		supplierInvoiceInfo = &http_model.SupplierToWithdrawInfo{}

		// 2.1. 基础信息填入
		supplierInvoiceInfo.AgreeTime = supplierInvoice.AgreeTime
		supplierInvoiceInfo.Company = supplierInvoice.Company

		// 2.2. 任务及其收入信息填入
		incomeIds := supplierInvoice.IncomeIds
		strSlice := strings.Split(incomeIds, ",")
		intSlice := make([]int, len(strSlice))
		for i, s := range strSlice {
			num, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println("转换错误:", err)
				return nil, err
			}
			intSlice[i] = num
		}
		for _, incomeId := range intSlice {
			var sTaskInfo *http_model.STaskInfo
			sTaskInfo = &http_model.STaskInfo{}
			currIncome, incomeErr := db.GetIncomeInfoByIncomeId(ctx, incomeId)
			if incomeErr != nil {
				return nil, incomeErr
			}
			sTaskInfo.ServiceCharge = currIncome.SupplierChargeActual
			supplierInvoiceInfo.Amount += currIncome.SupplierChargeActual
			if currIncome.IncomeType == 1 {
				sTaskInfo.Id = currIncome.SProjectID
			} else if currIncome.IncomeType == 3 {
				sTaskInfo.Id = currIncome.SLocalLifeID
			}
			supplierInvoiceInfo.STaskInfo = append(supplierInvoiceInfo.STaskInfo, sTaskInfo)
		}
		supplierInvoiceData.ToWithdrawList = append(supplierInvoiceData.ToWithdrawList, supplierInvoiceInfo)
	}
	supplierInvoiceData.Total = total
	return supplierInvoiceData, nil
}

// CreateSupplierWithdraw TODO
// CreateSupplierWithdraw 创建服务商提现信息
func (*supplier) CreateSupplierWithdraw(ctx context.Context, req *http_model.CreateSupplierWithdrawRequest) error {

	// 1. 数据整理
	var supplierWithdrawInfoList []*gorm_model.YounggeeSupplierWithdraw
	for _, withdrawInfo := range req.CreateSupplierWithdrawList {
		var supplierWithdrawInfo *gorm_model.YounggeeSupplierWithdraw
		supplierWithdrawInfo = &gorm_model.YounggeeSupplierWithdraw{}

		// 1.1. 接口传入信息填入
		supplierWithdrawInfo.SupplierId = req.SupplierId
		supplierWithdrawInfo.WithdrawStatus = 1
		supplierWithdrawInfo.BankName = withdrawInfo.BankName
		supplierWithdrawInfo.BankNumber = withdrawInfo.BankNumber

		// 1.2. 查找服务商信息填入

		// 1.3. 回票信息填入
		supplierWithdrawInfoList = append(supplierWithdrawInfoList, supplierWithdrawInfo)

	}

	// 2. 数据库插入
	err := db.CreateSupplierWithdraw(ctx, supplierWithdrawInfoList)
	if err != nil {
		return err
	}

	return nil
}
