package cn.ysk.cashier.mybatis.mapper;

import cn.ysk.cashier.pojo.order.TbCashierCart;
import cn.ysk.cashier.vo.CarVO;
import cn.ysk.cashier.vo.PendingCountVO;
import cn.ysk.cashier.vo.TbCashierCartVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;

public interface TbCashierCartMapper extends BaseMapper<TbCashierCart> {


    @Select("select table_id tableId,user_id userId, shop_Id as shopId,master_id as masterId,uuid,\n" +
            "        TRIM(TRAILING ', ' FROM GROUP_CONCAT(name ORDER BY id SEPARATOR ', ')) AS productName,\n" +
            "        pending_at as pendingAt,\n" +
            "        ifnull(sum(total_amount),0) as totalAmount\n" +
            "        from tb_cashier_cart where table_id is not null and shop_id = #{shopId} and status = 'refund' group by shop_Id, master_id order by trade_day desc")
    List<CarVO> selectCar(@Param("shopId") Integer shopId);


    @Select("<script> select\n" +
            "            a.id orderId,b.pending_at pendingAt, sum(b.total_amount) totalAmount,\n" +
            "               count(b.id) totalCount, sum(b.total_number) totalNumber, a.remark\n" +
            "        from tb_order_info a\n" +
            "        JOIN tb_cashier_cart b on a.id=b.order_id\n" +
            "        where a.shop_id=#{shopId} and a.`status`='pending'\n" +
            "          and a.trade_day=#{day} and a.use_type=#{useType}\n" +
            "        <if test=\"tableId != null and tableId != ''\">\n" +
            "            and a.table_id=#{tableId}\n" +
            "        </if>\n" +
            "        GROUP BY a.id ORDER BY a.id desc</script>")
    List<PendingCountVO> countPending(@Param("shopId") Integer shopId, @Param("tableId") String tableId, @Param("day") String day, @Param("useType") String useType);

    @Select("select a.*, b.spec_snap from tb_cashier_cart as a left join tb_product_sku as b on a.sku_id=b.id where a.shop_id=#{shopId} and a.status='refund';")
    List<TbCashierCartVO> selectPending(Integer shopId);

    /**
     * 更新购物车数量以及金额
     * @param id id
     * @param status 状态
     * @param changeNum 修改数量 正数增加 负数减少
     * @return 影响行数
     */
    @Update("update tb_cashier_cart set status=#{status}, total_amount=(number+#{changeNum})*sale_price,number=number+#{changeNum},total_number=total_number+#{changeNum} " +
            "where id=#{id}")
    int updateNumAmountStatus(Integer id, String status, BigDecimal changeNum);

    @Select("select a.* from tb_cashier_cart as a left join tb_order_detail as b on a.id=b.cart_id where a.shop_id=#{shopId} and a.status=#{state} and a.created_at>#{time} and b.id is not null;")
    List<TbCashierCart> selectPlaceCart(Integer shopId, long time, String state);
}
