package dao

import (
	"demo/configs"
	"demo/data/domain"
	"demo/data/domain/vo"
	"fmt"
)

// 排序
func GetGoodsTagList(goodsTag domain.GoodsTag, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.GoodsTag
	Count, err := configs.Engine.Table("goods_tag").OrderBy("sort").
		Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &goodsTag)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, len(arr))
	for i, v := range arr {
		vo.List[i] = v
	}
	vo.Total = int(Count)
	return vo, nil
}

// SelectGoodsDetailById 获取相同的商品详情
func SelectGoodsDetailById(skuId int64) (vo.DetailVo, error) {
	detailVo := vo.DetailVo{}
	var caId int64 = -1
	//================查询sku========================
	var sku domain.GoodsSku
	//查询 sku
	rows, err := configs.Engine.Table("goods_sku").
		Where("goods_id = (select a.goods_id as goods_id from goods_sku as a where a.id = ? )", skuId).
		Desc("create_time").Rows(&sku)
	if err != nil {
		println("查询sku失败", err)
		return vo.DetailVo{}, err
	}
	var skus []domain.GoodsSku
	var commodityAreaIds = make([]int64, 0)
	commodityAreaIdsString := ""
A:
	for rows.Next() {
		rows.Scan(&sku)
		skus = append(skus, sku)
		if sku.Id == skuId {
			caId = sku.CommodityAreaId
		}
		//去重
		for i := range commodityAreaIds {
			if sku.CommodityAreaId == commodityAreaIds[i] {
				continue A
			}
		}

		commodityAreaIds = append(commodityAreaIds, sku.CommodityAreaId)
		commodityAreaIdsString = fmt.Sprint(commodityAreaIdsString, ",", sku.CommodityAreaId)
	}
	if len(skus) == 0 {
		return detailVo, nil
	}

	if len(commodityAreaIdsString) > 1 {
		commodityAreaIdsString = commodityAreaIdsString[1:]
	}

	fmt.Println("=============================>", commodityAreaIdsString)
	//================查询goods========================
	var goods domain.Goods
	_, err = configs.Engine.Table("goods").Where("id = ?", sku.GoodsId).Get(&goods)
	if err != nil {
		println("查询goods失败", err)
		return vo.DetailVo{}, err
	}
	//=================查询goods_tag========================
	var goodsTag domain.GoodsTag
	rows, err = configs.Engine.Table("goods_tag").
		Where(" FIND_IN_SET(goods_tag.id,?)", goods.TagIds).
		Rows(&goodsTag)
	if err != nil {
		println("查询goods_tag失败", err)
		return vo.DetailVo{}, err
	}
	var goodsTags []domain.GoodsTag
	for rows.Next() {
		rows.Scan(&goodsTag)
		goodsTags = append(goodsTags, goodsTag)
	}
	//=================查询goods_type========================
	var goodsType domain.GoodsType
	_, err = configs.Engine.Table("goods_type").Where("id = ?", goods.TypeId).Get(&goodsType)
	if err != nil {
		println("查询goods_type失败", err)
		return vo.DetailVo{}, err
	}
	//=================查询goods_CommodityArea========================
	var goodsCommodityArea domain.GoodsCommodityArea
	rows, err = configs.Engine.Table("goods_commodity_area").
		Where(" FIND_IN_SET(goods_commodity_area.id,?)", commodityAreaIdsString).
		Rows(&goodsCommodityArea)
	if err != nil {
		println("查询goods_CommodityArea失败", err)
		return vo.DetailVo{}, err
	}
	var goodsCommodityAreas []domain.GoodsCommodityArea

	var introductionIds = make([]int64, 0)
	var introductionIdString = ""
B:
	for rows.Next() {
		rows.Scan(&goodsCommodityArea)
		goodsCommodityAreas = append(goodsCommodityAreas, goodsCommodityArea)
		for i := range introductionIds {
			if goodsCommodityArea.DetailIntroductionId == introductionIds[i] {
				continue B
			}
		}
		introductionIds = append(introductionIds, goodsCommodityArea.DetailIntroductionId)
		introductionIdString = fmt.Sprint(introductionIdString, ",", goodsCommodityArea.DetailIntroductionId)
	}
	if len(introductionIdString) > 1 {
		introductionIdString = introductionIdString[1:]
	}
	fmt.Println("=============================>", introductionIdString)
	//=================查询goods_introduction========================
	var goodsIntroduction domain.GoodsIntroduction
	rows, err = configs.Engine.Table("goods_introduction").
		Where("FIND_IN_SET(id,?)", introductionIdString).
		Rows(&goodsIntroduction)
	if err != nil {
		println("查询goods_introduction失败", err)
		return vo.DetailVo{}, err
	}

	var goodsIntroductions []domain.GoodsIntroduction
	for rows.Next() {
		rows.Scan(&goodsIntroduction)
		goodsIntroductions = append(goodsIntroductions, goodsIntroduction)
	}

	detailVo.DetailGoodsVo = vo.DetailGoodsVo{
		Tags:        goodsTags,
		GoodsId:     goods.Id,
		Name:        goods.GoodsName,
		SalesVolume: goods.SalesVolume,
		Type:        goodsType,
	}

	detailVo.DetailSkuVo = vo.DetailSkuVo{
		SkuList:  skus,
		NowSkuId: skuId,
	}

	detailVo.DetailCommodityAreaVo = vo.DetailCommodityAreaVo{
		CommodityAreaList:  goodsCommodityAreas,
		NowCommodityAreaId: caId,
	}

	//=================相关推荐========================
	//复制sku 8个数据
	if len(skus) >= 8 {
		detailVo.RecommendedGoods = skus[0:8]
	} else {
		detailVo.RecommendedGoods = skus
	}
	detailVo.Introduction = goodsIntroductions

	return detailVo, nil
}
func SelectSkuInfoBySkuId(skuId int64) (vo.DetailInfoVo, error) {
	//根据skuid 获取GoodsId
	var sku domain.GoodsSku
	var infoVo vo.DetailInfoVo
	_, err := configs.Engine.Table("goods_sku").Where("id = ?", skuId).Get(&sku)
	if err != nil || sku.GoodsId == 0 {
		return infoVo, err
	}
	var goods domain.Goods
	_, err = configs.Engine.Table("goods").Where("id = ?", sku.GoodsId).Get(&goods)
	//查询属性
	var areas = make([]domain.GoodsCommodityArea, 0)
	err = configs.Engine.Table("goods_commodity_area").
		Where("goods_id = ?", goods.Id).Find(&areas)
	if err != nil {
		return infoVo, err
	}
	//查询文章下的所有

	var intrs = make([]domain.GoodsIntroduction, 0)

	//{
	//	intrIds := make([]int64, 0)
	//	intrIds = append(intrIds, goods.IntroductionId)
	//
	//	for i := range areas {
	//		if areas[i].DetailIntroductionId != 0 {
	//			intrIds = append(intrIds, areas[i].DetailIntroductionId)
	//		}
	//	}
	//
	//	var iis = ""
	//	for i := range intrIds {
	//		iis += fmt.Sprint(",", intrIds[i])
	//	}
	//	iis = iis[1:]
	//
	//	err = configs.Engine.Table("goods_introduction").
	//		Where("FIND_IN_SET(id,?)", iis).Find(&intrs)
	//	if err != nil {
	//		return infoVo, err
	//	}
	//}
	{
		sign := false
		if goods.IntroductionId != 0 {
			err = configs.Engine.Table("goods_introduction").
				Where("id = ?", goods.IntroductionId).Find(&intrs)
			if err != nil {
				sign = true
			}
		}
		if sign || len(intrs) == 0 {
			err = configs.Engine.Table("goods_introduction").
				Where("goods_id = ?", goods.Id).Find(&intrs)
		}
	}

	var skus = make([]domain.GoodsSku, 0)
	err = configs.Engine.Table("goods_sku").Where("goods_id = ?", goods.Id).Find(&skus)

	infoVo.Sku = sku
	infoVo.Goods = goods
	infoVo.Introductions = intrs
	infoVo.Skus = skus
	infoVo.Areas = areas

	if len(skus) > 8 {
		infoVo.RecommendedGoods = skus[0:8]
	} else {
		infoVo.RecommendedGoods = skus
	}

	return infoVo, nil
}

// 搜索==================

func GetSkuByKey2(key string, pageNum, pageSize int) ([]domain.GoodsSku, int64, error) {
	if pageNum == 0 {
		pageNum = 1
	}
	if pageSize == 0 {
		pageSize = 12
	}

	var sqlKey = "%" + key + "%"
	arr := make([]domain.GoodsSku, 0)
	if key == "" {
		count, err := configs.Engine.Table("goods_sku").Desc("id").
			Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr)
		if err != nil {
			return nil, 0, err
		}
		return arr, count, nil
	}
	//sql := `SELECT DISTINCT
	//        s.id,
	//        s.sku_image,
	//        s.sku_name,
	//        s.price,
	//        s.historical_prices,
	//        s.inventory_number,
	//        s.commodity_area_id,
	//        s.goods_id,
	//        s.create_by,
	//        s.create_time
	//    FROM goods_sku s
	//    LEFT JOIN goods g ON s.goods_id = g.id
	//    LEFT JOIN goods_tag t ON FIND_IN_SET(t.id, g.tag_ids)
	//    WHERE t.tag LIKE ?
	//       OR g.goods_name LIKE ?
	//       OR s.sku_name LIKE ?
	//       OR t.id IS NULL
	//	ORDER BY s.id DESC
	//	LIMIT ? OFFSET ?
	//`
	//count, err := configs.Engine.SQL(sql, sqlKey, sqlKey, sqlKey, pageSize, (pageNum-1)*pageSize).FindAndCount(&arr)
	count, err := configs.Engine.Table("goods_sku s").
		Join("left", "goods g", "s.goods_id = g.id").
		//Join("left", "goods_tag t", "FIND_IN_SET(t.id, g.tag_ids)").Desc("s.id").
		Join("left", "(SELECT gt.tag as tag,g.id AS goods_id FROM goods g JOIN goods_tag gt ON FIND_IN_SET(gt.id, g.tag_ids)) AS t ", " g.id = t.goods_id").Desc("s.id").
		Where("t.tag LIKE ? OR g.goods_name LIKE ? OR s.sku_name LIKE ?", sqlKey, sqlKey, sqlKey).
		Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr)
	if err != nil {
		fmt.Println("sql语句错误", err)
		return nil, 0, err
	}
	return arr, count, nil
}

func GetSkuByKey(key string, pageNum, pageSize int) ([]domain.GoodsSku, int64, error) {
	var sqlKey = "%" + key + "%"
	var sku domain.GoodsSku
	var arr []domain.GoodsSku
	//查询tag
	var tag domain.GoodsTag
	var goods domain.Goods

	var inTags = make([]int64, 0)

	//获取标签
	targetRow, err := configs.Engine.Cols("id").Where("name like ?", sqlKey).Or("tag like ?", sqlKey).
		//去重
		Distinct("id").Rows(&tag)
	for targetRow.Next() {
		targetRow.Scan(&tag)
		inTags = append(inTags, tag.Id)
	}

	//商品内名称查询
	sess := configs.Engine.Cols("id").Distinct("id").Where("goods_name like ?", sqlKey)
	for i := range inTags {
		sess.Or("FIND_IN_SET(?,tag_ids)", inTags[i])
	}
	goodsRow, err := sess.Rows(&goods)
	if err != nil {
		return arr, 0, err
	}
	var goodsInTags = make([]int64, 0)
	for goodsRow.Next() {
		goodsRow.Scan(&goods)
		goodsInTags = append(goodsInTags, goods.Id)
	}

	//最终sku查询
	sess = configs.Engine.Where("sku_name like ?", sqlKey)
	for i := range goodsInTags {
		sess.Or("goods_id = ?", goodsInTags[i])
	}
	skuRow, err := sess.Desc("id").Limit(pageSize, (pageNum-1)*pageSize).Rows(&sku)
	if err != nil {
		return arr, 0, err
	}

	var skus = make([]any, 0)
	for skuRow.Next() {
		skuRow.Scan(&sku)
		skus = append(skus, sku)
	}

	cs := configs.Engine.Where("sku_name like ?", sqlKey)
	for i := range goodsInTags {
		cs.Or("goods_id = ?", goodsInTags[i])
	}
	count, err := cs.Distinct("id").Count("id")

	return arr, count, nil
}

func GetGoodsSkuList(goodsSku domain.GoodsSku, pageNum, pageSize int) ([]domain.GoodsSku, int64, error) {
	var arr []domain.GoodsSku
	Count, err := configs.Engine.Table("goods_sku").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &goodsSku)
	if err != nil {
		return arr, 0, err
	}
	if err != nil {
		return arr, 0, err
	}
	return arr, Count, nil
}
