package rentComputer

import (
	"context"
	"errors"
	"fmt"
	"github.com/xuri/excelize/v2"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/rentComputer"
	"log-server/model/rentComputer/request"
	"log-server/model/rentComputer/response"
	"time"
)

type ServiceRentComputerLedger struct {
}

func (service *ServiceRentComputerLedger) RentComputerLedgerList(ctx context.Context, api rentComputer.RentComputerLedger, info request.PageInfo, order string, desc bool) ([]*response.RentComputerLedgerResponse, int64, error) {

	db := global.GVA_DB.Model(&rentComputer.RentComputerLedger{})
	db = db.Select("rent_computer_ledger.id,rent_computer_ledger.update_time,rent_computer_ledger.create_time,rent_computer_ledger.pc_num,rent_computer_ledger.new_date,rent_computer_ledger.set_meal_id," +
		"rent_computer_ledger.pc_name,rent_computer_ledger.shop_id,rent_computer_ledger.rent_start_then,rent_computer_ledger.rent_duration_then,rent_computer_ledger.rent_price_then,rent_computer_ledger.rent_end_then," +
		"rent_computer_ledger.remark,rent_computer_ledger.rent_price_used_then,rent_computer_ledger.is_expire,rent_computer_ledger.rent_price_day_then,rent_computer_ledger.set_meal_id," +
		"s.name as shop_name, r.name as set_meal_name")
	db = db.Joins("left join rent_computer_shop s on s.id = rent_computer_ledger.shop_id")
	db = db.Joins("left join rent_set_meal r on r.id = rent_computer_ledger.set_meal_id")
	if api.PcNum != "" {
		db = db.Where("rent_computer_ledger.pc_num = ?", api.PcNum)
	}
	if api.ShopId != 0 {
		db = db.Where("rent_computer_ledger.shop_id = ?", api.ShopId)
	}
	if api.SetMealId != 0 {
		db = db.Where("rent_computer_ledger.set_meal_id = ?", api.SetMealId)
	}
	//if api.IsExpire != -1 {
	//	db = db.Where("rent_computer_ledger.is_expire = ?", api.IsExpire)
	//}
	if api.NewDate != "" {
		db = db.Where("rent_computer_ledger.new_date = ?", api.NewDate)
	} else {
		yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
		db = db.Where("rent_computer_ledger.new_date = ?", yesterday)
	}

	var total int64
	err := db.Count(&total).Error
	//if err != nil {
	//	return nil, 0, err
	//}
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	//var statisticsLogs []*log.LogComputer
	var ledgerComputers []*response.RentComputerLedgerResponse
	db = db.Limit(limit).Offset(offset)
	if order != "" {
		var OrderStr string
		// 设置有效排序key 防止sql注入
		// 感谢 Tom4t0 提交漏洞信息
		orderMap := make(map[string]bool, 3)
		orderMap["pc_num"] = true
		//orderMap["game_id"] = true
		//orderMap["operator"] = true
		if orderMap[order] {
			if desc {
				OrderStr = order + " desc"
			} else {
				OrderStr = order
			}
		} else { // didn't matched any order key in `orderMap`
			global.GVA_LOG.Error("获取失败!", zap.Error(err))
			return ledgerComputers, total, err
		}
		err = db.Order(OrderStr).Find(&ledgerComputers).Error
	} else {
		err = db.Order("pc_num").Find(&ledgerComputers).Error
	}
	if err != nil {
		return nil, 0, err
	}
	var infos []*response.RentComputerLedgerResponse

	for _, one := range ledgerComputers {
		info := new(response.RentComputerLedgerResponse)
		info.Id = one.Id
		info.UpdateTime = one.UpdateTime
		info.CreateTime = one.CreateTime
		info.PcNum = one.PcNum
		info.PcName = one.PcName
		info.ShopId = one.ShopId
		info.Remark = one.Remark
		info.IsExpire = one.IsExpire
		info.SetMealId = one.SetMealId
		info.ShopName = one.ShopName
		info.SetMealName = one.SetMealName
		info.RentPriceUsedThen = one.RentPriceUsedThen
		info.RentStartThen = one.RentStartThen
		info.RentEndThen = one.RentEndThen
		info.RentPriceDayThen = one.RentPriceDayThen
		info.NewDate = one.NewDate
		info.RentPriceThen = one.RentPriceThen
		info.RentDurationThen = one.RentDurationThen
		infos = append(infos, info)
	}
	return infos, total, err
}

func (service *ServiceRentComputerLedger) GetRentComputerLedgerNum(ctx context.Context, api rentComputer.RentComputerLedger) int64 {
	var total int64

	db := global.GVA_DB.Model(&rentComputer.RentComputerLedger{})
	db = db.Distinct("id")
	if api.PcNum != "" {
		db = db.Where("rent_computer_ledger.pc_num = ?", api.PcNum)
	}
	if api.ShopId != 0 {
		db = db.Where("rent_computer_ledger.shop_id = ?", api.ShopId)
	}
	if api.SetMealId != 0 {
		db = db.Where("rent_computer_ledger.set_meal_id = ?", api.SetMealId)
	}
	if api.NewDate != "" {
		db = db.Where("rent_computer_ledger.new_date = ?", api.NewDate)
	} else {
		yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
		db = db.Where("rent_computer_ledger.new_date = ?", yesterday)
	}
	//db = db.Where("is_expire != 1")
	_ = db.Count(&total).Error
	return total
}

func (service *ServiceRentComputerLedger) ParseInfoList2Excel(infoList []*response.RentComputerLedgerResponse, filePath string) (err error) {
	excel := excelize.NewFile()
	err = excel.SetSheetRow("Sheet1", "A1", &[]string{"日期", "供应商", "编号", "起租日期", "到期日期", "租期", "套餐", "价格", "天租金", "已产生租金", "备注"})
	if err != nil {
		return err
	}
	for i, one := range infoList {
		axis := fmt.Sprintf("A%d", i+2)
		err = excel.SetSheetRow("Sheet1", axis, &[]interface{}{
			one.NewDate,
			one.ShopName,
			one.PcNum,
			one.RentStartThen,
			one.RentEndThen,
			one.RentDurationThen,
			one.SetMealName,
			one.RentPriceThen,
			one.RentPriceDayThen,
			one.RentPriceUsedThen,
			one.Remark,
		})
		if err != nil {
			return err
		}
	}
	err = excel.SaveAs(filePath)
	return err
}

func (s *ServiceRentComputerLedger) DeleteRentComputerLedgerByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]rentComputer.RentComputerLedger{}, "id in ?", ids.Ids).Error
	return err
}

func (s *ServiceRentComputerLedger) DeleteRentComputerLedgerById(api rentComputer.RentComputerLedger) (err error) {
	var entity rentComputer.RentComputerLedger
	err = global.GVA_DB.Where("id = ?", api.Id).First(&entity).Error // 根据id查询api记录
	if errors.Is(err, gorm.ErrRecordNotFound) {                      // api记录不存在
		return err
	}
	return global.GVA_DB.Delete(&entity).Error
}
