package service

import (
	"encoding/json"
	"fmt"
	"time"
	"youngee_b_api/app/consts"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/entity"
	"youngee_b_api/app/util"
	"youngee_b_api/app/vo"
)

type InvoiceService struct{}

// 设置默认开票抬头
func (s InvoiceService) UpdateInvoiceDefault(param *vo.InvoiceDefaultParam) (*int64, error) {
	var err error
	invoiceInfo, err := dao.InvoiceInfoDao{}.SelectDefault(param.EnterpriseId, param.InvoiceType, 1)
	if err != nil {
		return nil, err
	}
	if invoiceInfo != nil && invoiceInfo.InvoiceID != 0 {
		err := dao.InvoiceInfoDao{}.Delete(invoiceInfo.InvoiceID)
		if err != nil {
			return nil, err
		}
	}
	if param.HeadType == 0 {
		param.HeadType = 1
	}
	enterprise, err1 := dao.EnterpriseDao{}.GetEnterpriseInfo(param.EnterpriseId)
	if err1 != nil {
		return nil, err1
	}
	invoiceInfoAdd := entity.InvoiceInfo{
		EnterpriseID:      param.EnterpriseId,
		InvoiceType:       param.InvoiceType,
		HeadType:          consts.GetHeadType(param.HeadType),
		InvoiceHeader:     enterprise.BusinessName,
		TaxCode:           enterprise.TaxNumber,
		RegisteredAddress: enterprise.Address,
		RegisteredPhone:   param.RegisteredPhone,
		Bank:              param.Bank,
		BankCardNumber:    param.BankCardNumber,
		IsDefault:         1,
		UpdateAt:          time.Now(),
	}
	err = dao.InvoiceInfoDao{}.Insert(&invoiceInfoAdd)
	if err != nil {
		return nil, err
	}

	return &invoiceInfoAdd.InvoiceID, nil
}

// 获取默认开票抬头
func (s InvoiceService) GetInvoiceDefault(param *vo.InvoiceDefaultParam) (*vo.ReInvoiceInfo, error) {
	invoiceInfo, err := dao.InvoiceInfoDao{}.SelectDefault(param.EnterpriseId, param.InvoiceType, 1)
	if err != nil {
		return nil, err
	}
	reInvoiceInfo := &vo.ReInvoiceInfo{
		InvoiceHeader:     invoiceInfo.InvoiceHeader,
		TaxCode:           invoiceInfo.TaxCode,
		RegisteredAddress: invoiceInfo.RegisteredAddress,
		RegisteredPhone:   invoiceInfo.RegisteredPhone,
		Bank:              invoiceInfo.Bank,
		BankCardNumber:    invoiceInfo.BankCardNumber,
		IsDefault:         invoiceInfo.IsDefault,
	}
	return reInvoiceInfo, nil
}

// 确认开票
func (s InvoiceService) BillInvoice(param *vo.InvoiceBillParam) (*string, error) {
	var err error
	billingId := util.GenerateDateRelatedUUID(16)
	taskIds := param.TaskIds
	// 将二维数组转换为 JSON 字符串
	jsonData, _ := json.Marshal(taskIds)
	// 将 []byte 转换为 string
	taskIdsString := string(jsonData)
	invoiceRecordAdd := entity.InvoiceRecord{
		BillingId:         billingId,
		EnterpriseID:      param.EnterpriseId,
		SubAccountId:      param.SubAccountId,
		InvoiceAmount:     param.InvoiceAmount,
		InvoiceBody:       param.InvoiceBody,
		InvoiceContent:    param.InvoiceContent,
		InvoiceType:       param.InvoiceType,
		InvoiceHeader:     param.InvoiceHead,
		TaxCode:           param.TaxCode,
		RegisteredAddress: param.RegisteredAddress,
		RegisteredPhone:   param.RegisteredPhone,
		Bank:              param.Bank,
		BankCardNumber:    param.BankCardNumber,
		TaskIds:           taskIdsString,
		Status:            1,
		SubmitAt:          time.Now(),
	}
	err = dao.InvoiceRecordDao{}.Insert(&invoiceRecordAdd)
	if err != nil {
		return nil, err
	}
	// 更新选品表的开票状态字段
	// 电商带货
	err = dao.SelectionInfoDAO{}.UpdateInvoiceStatus(taskIds[0])
	if err != nil {
		return nil, err
	}
	// 品牌种草
	err = dao.ProjectDAO{}.UpdateInvoiceStatus(taskIds[1])
	if err != nil {
		return nil, err
	}
	// 本地生活

	return &billingId, nil
}

// 开票记录
func (s InvoiceService) GetBillList(param *vo.InvoiceBillListParam) (vo.ResultVO, error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	var reInvoiceRecords []*vo.ReInvoiceRecord
	invoiceRecords, total, _ := dao.InvoiceRecordDao{}.GetBillList(param.EnterpriseId, param.SubAccountId, param.BillStatus, param.Page, param.PageSize)
	//if err != nil {
	//	result = vo.ResultVO{
	//		Page:     param.Page,
	//		PageSize: param.PageSize,
	//		Total:    total,
	//		Data:     reInvoiceRecords,
	//	}
	//	return result, err
	//}
	for _, invoiceRecord := range invoiceRecords {
		var creatorName string
		if invoiceRecord.SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(invoiceRecord.EnterpriseID)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(invoiceRecord.SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		var taskNumber int
		// 将 JSON 字符串解码为二维数组
		var arrayData [3][]string
		err := json.Unmarshal([]byte(invoiceRecord.TaskIds), &arrayData)
		if err != nil {
			fmt.Println("Error unmarshaling JSON:", err)
			return result, err
		}
		for _, array := range arrayData {
			taskNumber += len(array)
		}
		reInvoiceRecord := &vo.ReInvoiceRecord{
			BillingId:     invoiceRecord.BillingId,
			InvoiceAmount: invoiceRecord.InvoiceAmount,
			CreatorName:   creatorName,
			SubmitAt:      invoiceRecord.SubmitAt.Format("2006-01-02 15:04:05"),
			InvoiceBody:   invoiceRecord.InvoiceBody,
			InvoiceType:   invoiceRecord.InvoiceType,
			Status:        invoiceRecord.Status,
			TaskNumber:    int64(taskNumber),
			InvoiceUrl:    invoiceRecord.InvoiceUrl,
		}
		if param.BillStatus == 2 {
			reInvoiceRecord.BillingAt = invoiceRecord.BillingAt.Format("2006-01-02 15:04:05")
		}
		reInvoiceRecords = append(reInvoiceRecords, reInvoiceRecord)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reInvoiceRecords,
	}
	return result, nil
}

// 可开票账单
func (s InvoiceService) GetBillableList(param *vo.InvoiceBillListParam) (vo.ResultVO, error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	var reBillableInfos []*vo.ReBillableInfo
	var billableSelections []*entity.SelectionInfo
	var billableProjects []*entity.Project
	// 电商带货
	billableSelections, _, _ = dao.InvoiceRecordDao{}.GetBillableSelectionList(param.EnterpriseId, param.SubAccountId, param.Page, param.PageSize)
	// 品牌种草
	billableProjects, _, _ = dao.InvoiceRecordDao{}.GetBillableProjectList(param.EnterpriseId, param.SubAccountId, param.Page, param.PageSize)
	// 本地生活

	// 汇总结果
	for _, billableSelection := range billableSelections {
		// 获取商品详情字段
		var creatorName string
		var productName string
		var productPrice float64
		var mainImage string
		if billableSelection.SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(billableSelection.EnterpriseID)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(billableSelection.SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		product, err := dao.ProductDAO{}.GetProductByID(billableSelection.ProductID)
		if err == nil && product != nil {
			productName = product.ProductName
			productPrice = product.ProductPrice
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(billableSelection.ProductID)
		// 电商带货汇总
		reBillableInfo := &vo.ReBillableInfo{
			ProductId:      billableSelection.ProductID,
			MainImage:      mainImage,
			ProductName:    productName,
			ProductPrice:   productPrice,
			Platform:       billableSelection.Platform,
			CreatorName:    creatorName,
			TaskType:       "电商带货",
			BillableAmount: billableSelection.SettlementAmount,
			TaskId:         billableSelection.SelectionID,
		}
		reBillableInfos = append(reBillableInfos, reBillableInfo)
	}
	for _, billableProject := range billableProjects {
		// 获取商品详情字段
		var creatorName string
		var productName string
		var productPrice float64
		var mainImage string
		if billableProject.SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(billableProject.EnterpriseID)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(billableProject.SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		product, err := dao.ProductDAO{}.GetProductByID(billableProject.ProductID)
		if err == nil && product != nil {
			productName = product.ProductName
			productPrice = product.ProductPrice
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(billableProject.ProductID)
		// 品牌种草汇总
		reBillableInfo := &vo.ReBillableInfo{
			ProductId:      billableProject.ProductID,
			MainImage:      mainImage,
			ProductName:    productName,
			ProductPrice:   productPrice,
			Platform:       billableProject.ProjectPlatform,
			CreatorName:    creatorName,
			TaskType:       "品牌种草",
			BillableAmount: billableProject.SettlementAmount,
			TaskId:         billableProject.ProjectId,
		}
		reBillableInfos = append(reBillableInfos, reBillableInfo)
	}
	// 本地生活

	startIndex := (param.Page - 1) * param.PageSize
	endIndex := startIndex + param.PageSize

	// 分页
	if startIndex >= len(reBillableInfos) {
		result = vo.ResultVO{
			Page:     param.Page,
			PageSize: param.PageSize,
			Total:    int64(len(reBillableInfos)),
			Data:     nil,
		}
		return result, nil
	}
	if endIndex > len(reBillableInfos) {
		endIndex = len(reBillableInfos)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    int64(len(reBillableInfos)),
		Data:     reBillableInfos[startIndex:endIndex],
	}
	return result, nil
}

// 开票金额数据-已开票、可开票、开票中
func (s InvoiceService) ShowInvoiceBill(param *vo.InvoiceBillListParam) (map[string]float64, error) {
	resMap := make(map[string]float64)
	// 可开票
	selectionAmount1, err1 := dao.SelectionInfoDAO{}.GetSelectionFinished(param.EnterpriseId, 0)
	if err1 != nil {
		return resMap, err1
	}
	projectAmount1, err1 := dao.ProjectDAO{}.GetProjectFinished(param.EnterpriseId, 0)
	if err1 != nil {
		return resMap, err1
	}
	localLifeAmount1, err1 := dao.LocalLifeDao{}.GetLocalLifeFinished(param.EnterpriseId, 0)
	if err1 != nil {
		return resMap, err1
	}
	// 开票中
	selectionAmount2, err2 := dao.SelectionInfoDAO{}.GetSelectionFinished(param.EnterpriseId, 1)
	if err2 != nil {
		return resMap, err2
	}
	projectAmount2, err2 := dao.ProjectDAO{}.GetProjectFinished(param.EnterpriseId, 1)
	if err2 != nil {
		return resMap, err2
	}
	localLifeAmount2, err2 := dao.LocalLifeDao{}.GetLocalLifeFinished(param.EnterpriseId, 1)
	if err2 != nil {
		return resMap, err2
	}
	// 已开票
	selectionAmount3, err3 := dao.SelectionInfoDAO{}.GetSelectionFinished(param.EnterpriseId, 2)
	if err3 != nil {
		return resMap, err3
	}
	projectAmount3, err3 := dao.ProjectDAO{}.GetProjectFinished(param.EnterpriseId, 2)
	if err3 != nil {
		return resMap, err3
	}
	localLifeAmount3, err3 := dao.LocalLifeDao{}.GetLocalLifeFinished(param.EnterpriseId, 2)
	if err3 != nil {
		return resMap, err3
	}

	resMap["invoicableAmount"] = selectionAmount1 + projectAmount1 + localLifeAmount1
	resMap["invoicingAmount"] = selectionAmount2 + projectAmount2 + localLifeAmount2
	resMap["invoicedAmount"] = selectionAmount3 + projectAmount3 + localLifeAmount3

	return resMap, nil
}

// 财务待办——开票中中金额
func (s InvoiceService) GetFinance(param *vo.CommonParam) (float64, error) {
	invoicingAmount, err := dao.InvoiceRecordDao{}.GetInvoiceAmount(param.EnterpriseId, 1)
	if err != nil {
		return 0, err
	}

	return invoicingAmount, nil
}
