package shop.alien.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import shop.alien.entity.store.LifeUserOrder;
import shop.alien.entity.store.vo.LifeUserOrderVo;

import java.util.List;
import java.util.Map;

/**
 * 用户订单
 */
@Mapper
public interface LifeUserOrderMapper extends BaseMapper<LifeUserOrder> {
    @Select("select store_id, ifnull(round(sum(uorder.price) / count(1), 0), 0) avg_price\n" +
            "from life_user_order uorder \n" +
            "where uorder.status = '1' and uorder.delete_flag = 0\n" +
            "group by store_id")
    List<Map<String, Object>> allStoreAvgPrice();

    @Select("select coupon_id,count(ocm.coupon_id) count\n" +
            "from life_user_order luo \n" +
            "left join order_coupon_middle ocm on ocm.order_id = luo.id and ocm.delete_flag =0\n" +
            "${ew.customSqlSegment}")
    List<LifeUserOrderVo> getQuanCount(@Param(Constants.WRAPPER) QueryWrapper<LifeUserOrderVo> queryWrapper);

    LifeUserOrderVo queryUserOrderDetail(@Param("orderId") String orderId,@Param("position") String position);

/*    @Select("with total_coupon as(\n" +
            "-- 团购\n" +
            "\tselect id coupon_id,2 coupon_type,lgbm.group_name coupon_name, SUBSTRING_INDEX(image_id, ',', 1) AS image_id,effective_date_type,effective_date_value \n" +
            "from life_group_buy_main lgbm \n" +
            "\tunion all\n" +
            "-- 代金券\n" +
            "\tselect id coupon_id,1 coupon_type,lc.name coupon_name, SUBSTRING_INDEX(image_path, ',', 1) AS image_id,\n" +
            "case when expiration_type = 1 then 0 else 1 end effective_date_type,case when expiration_type = 1 then expiration_date else validity_period end  effective_date_value \n" +
            "from life_coupon lc \n" +
            ")\n" +
            "select luo.id,luo.buy_time,luo.status,luo.price,luo.final_price,luo.user_id,luo.store_id,luo.order_no,luo.pay_time,luo.cancel_time,luo.finish_time,luo.order_str,luo.expert_order_id,luo.order_appraise,\n" +
            "si.store_name,si.commission_rate,si.business_section store_type,si.store_status,si.business_status,\n" +
            "count(ocm.coupon_code) coupon_count,\n" +
            "simg.img_url,\n" +
            "lu.user_phone,\n" +
            "IF(sc.id is null,false,true) as hasComment,\n" +
            "tc.*,\n" +
            "CASE\n" +
            "        WHEN si.delete_flag = 1 OR si.logout_flag = 1 THEN 1\n" +
            "        ELSE 0\n" +
            "    END AS abnormalStateFlag,\n" +
            "ldc.nominal_value,ldc.type\n" +
            "from life_user_order luo\n" +
            "left join store_info si on si.id = luo.store_id  -- 查询店铺相关 \n" +
            "left join life_user lu on lu.id = luo.user_id and lu.delete_flag = 0 -- 查询用户相关 \n" +
            "left join order_coupon_middle ocm on ocm.order_id = luo.id and ocm.delete_flag = 0\n" +
            "left join total_coupon tc on tc.coupon_id = ocm.coupon_id and tc.coupon_type = luo.coupon_type\n" +
            "left join  store_img simg on simg.id = tc.image_id and simg.delete_flag = 0 \n" +
            "left join  store_comment sc on sc.business_id = luo.id and sc.delete_flag = 0 and sc.business_type = 5\n" +
            "left join life_discount_coupon_user ldcu on ldcu .id = luo.quan_id \n" +
            "left join life_discount_coupon ldc on ldc.id = ldcu.coupon_id \n" +
            "${ew.customSqlSegment}")*/
    @Select("with total_coupon as(\n" +
            "-- 团购\n" +
            "\tselect id coupon_id,2 coupon_type,lgbm.group_name coupon_name, SUBSTRING_INDEX(image_id, ',', 1) AS image_id,effective_date_type,effective_date_value \n" +
            "\tfrom life_group_buy_main lgbm \n" +
            "\tunion all\n" +
            "-- 代金券\n" +
            "\tselect id coupon_id,1 coupon_type,lc.name coupon_name, SUBSTRING_INDEX(image_path, ',', 1) AS image_id,0 effective_date_type,expiration_date effective_date_value \n" +
            "\tfrom life_coupon lc \n" +
            ")\n" +
            "select \n" +
            "    luo.id,\n" +
            "    luo.buy_time,\n" +
            "    luo.status,\n" +
            "    luo.price,\n" +
            "    luo.final_price,\n" +
            "    luo.user_id,\n" +
            "    luo.store_id,\n" +
            "    luo.order_no,\n" +
            "    luo.pay_time,\n" +
            "    luo.cancel_time,\n" +
            "    luo.finish_time,\n" +
            "    luo.order_str,\n" +
            "    luo.expert_order_id,\n" +
            "    luo.order_appraise,\n" +
            "    -- 店铺表列：用ANY_VALUE包裹（一个订单对应一个店铺，值唯一）\n" +
            "    ANY_VALUE(si.store_name) as store_name,\n" +
            "    ANY_VALUE(si.commission_rate) as commission_rate,\n" +
            "    ANY_VALUE(si.business_section) as store_type,\n" +
            "    ANY_VALUE(si.store_status) as store_status,\n" +
            "    ANY_VALUE(si.business_status) as business_status,\n" +
            "    -- 聚合列：优惠券数量（唯一聚合列，无需处理）\n" +
            "    count(ocm.coupon_code) as coupon_count,\n" +
            "    -- 图片表列：用ANY_VALUE包裹（一个优惠券对应一张图片，值唯一）\n" +
            "    ANY_VALUE(simg.img_url) as img_url,\n" +
            "    -- 用户表列：用ANY_VALUE包裹（一个订单对应一个用户，值唯一）\n" +
            "    ANY_VALUE(lu.user_phone) as user_phone,\n" +
            "    -- 评论状态：用ANY_VALUE包裹（一个订单最多一条评论，值唯一）\n" +
            "    ANY_VALUE(IF(sc.id is null,false,true)) as hasComment,\n" +
            "    -- 优惠券CTE列：拆解tc.*为具体列，用ANY_VALUE包裹\n" +
            "    ANY_VALUE(tc.coupon_id) as coupon_id,\n" +
            "    ANY_VALUE(tc.coupon_type) as coupon_type,\n" +
            "    ANY_VALUE(tc.coupon_name) as coupon_name,\n" +
            "    ANY_VALUE(tc.image_id) as tc_image_id,\n" +
            "    ANY_VALUE(tc.effective_date_type) as effective_date_type,\n" +
            "    ANY_VALUE(tc.effective_date_value) as effective_date_value,\n" +
            "    -- 异常状态标识：用ANY_VALUE包裹\n" +
            "    ANY_VALUE(CASE\n" +
            "        WHEN si.delete_flag = 1 OR si.logout_flag = 1 THEN 1\n" +
            "        ELSE 0\n" +
            "    END) AS abnormalStateFlag,\n" +
            "    -- 折扣券列：用ANY_VALUE包裹（一个订单对应一个折扣券，值唯一）\n" +
            "    ANY_VALUE(ldc.nominal_value) as nominal_value,\n" +
            "    ANY_VALUE(ldc.type) as type\n" +
            "from life_user_order luo\n" +
            "left join store_info si on si.id = luo.store_id  -- 查询店铺相关 \n" +
            "left join life_user lu on lu.id = luo.user_id and lu.delete_flag = 0 -- 查询用户相关 \n" +
            "left join order_coupon_middle ocm on ocm.order_id = luo.id \n" +
            "left join total_coupon tc on tc.coupon_id = ocm.coupon_id and tc.coupon_type = luo.coupon_type\n" +
            "left join store_img simg on simg.id = tc.image_id and simg.delete_flag = 0 \n" +
            "left join store_comment sc on sc.business_id = luo.id and sc.delete_flag = 0 and sc.business_type = 5\n" +
            "left join life_discount_coupon_user ldcu on ldcu.id = luo.quan_id \n" +
            "left join life_discount_coupon ldc on ldc.id = ldcu.coupon_id \n" +
            "${ew.customSqlSegment}")
    IPage<LifeUserOrderVo> queryUserOrderList(IPage<LifeUserOrderVo> brandedPage,@Param(Constants.WRAPPER) QueryWrapper<LifeUserOrderVo> lifeUserOrderQueryWrapper);

    /**
     * 统计各状态订单数量
     * <p>
     * 注意：此查询需要与queryUserOrderList使用相同的查询条件，但不需要分页和分组
     * </p>
     *
     * @param queryWrapper 查询条件包装器（需要移除分页和分组条件）
     * @return 各状态订单数量统计，key为orderStatus（订单状态），value为orderCount（订单数量）
     */
    @Select("WITH total_coupon AS (\n" +
            "    -- 团购\n" +
            "    SELECT id coupon_id, 2 coupon_type, lgbm.group_name coupon_name, " +
            "           SUBSTRING_INDEX(image_id, ',', 1) AS image_id, " +
            "           effective_date_type, effective_date_value \n" +
            "    FROM life_group_buy_main lgbm \n" +
            "    UNION ALL\n" +
            "    -- 代金券\n" +
            "    SELECT id coupon_id, 1 coupon_type, lc.name coupon_name, " +
            "           SUBSTRING_INDEX(image_path, ',', 1) AS image_id, " +
            "           0 effective_date_type, expiration_date effective_date_value \n" +
            "    FROM life_coupon lc \n" +
            ")\n" +
            "SELECT " +
            "    luo.status AS orderStatus, " +
            "    COUNT(DISTINCT luo.id) AS orderCount " +
            "FROM life_user_order luo " +
            "LEFT JOIN store_info si ON si.id = luo.store_id " +
            "LEFT JOIN life_user lu ON lu.id = luo.user_id AND lu.delete_flag = 0 " +
            "LEFT JOIN order_coupon_middle ocm ON ocm.order_id = luo.id " +
            "LEFT JOIN total_coupon tc ON tc.coupon_id = ocm.coupon_id AND tc.coupon_type = luo.coupon_type " +
            "LEFT JOIN store_img simg ON simg.id = tc.image_id AND simg.delete_flag = 0 " +
            "LEFT JOIN store_comment sc ON sc.business_id = luo.id AND sc.delete_flag = 0 AND sc.business_type = 5 " +
            "LEFT JOIN life_discount_coupon_user ldcu ON ldcu.id = luo.quan_id " +
            "LEFT JOIN life_discount_coupon ldc ON ldc.id = ldcu.coupon_id " +
            "${ew.customSqlSegment} " +
            "GROUP BY luo.status")
    List<Map<String, Object>> countOrdersByStatus(@Param(Constants.WRAPPER) QueryWrapper<LifeUserOrderVo> queryWrapper);

    /**
     * 统计全部订单数量
     * <p>
     * 统计符合条件的全部订单数量，不区分状态
     * </p>
     *
     * @param queryWrapper 查询条件包装器
     * @return 全部订单数量
     */
    @Select("WITH total_coupon AS (\n" +
            "    -- 团购\n" +
            "    SELECT id coupon_id, 2 coupon_type, lgbm.group_name coupon_name, " +
            "           SUBSTRING_INDEX(image_id, ',', 1) AS image_id, " +
            "           effective_date_type, effective_date_value \n" +
            "    FROM life_group_buy_main lgbm \n" +
            "    UNION ALL\n" +
            "    -- 代金券\n" +
            "    SELECT id coupon_id, 1 coupon_type, lc.name coupon_name, " +
            "           SUBSTRING_INDEX(image_path, ',', 1) AS image_id, " +
            "           0 effective_date_type, expiration_date effective_date_value \n" +
            "    FROM life_coupon lc \n" +
            ")\n" +
            "SELECT COUNT(DISTINCT luo.id) AS totalOrderCount " +
            "FROM life_user_order luo " +
            "LEFT JOIN store_info si ON si.id = luo.store_id " +
            "LEFT JOIN life_user lu ON lu.id = luo.user_id AND lu.delete_flag = 0 " +
            "LEFT JOIN order_coupon_middle ocm ON ocm.order_id = luo.id " +
            "LEFT JOIN total_coupon tc ON tc.coupon_id = ocm.coupon_id AND tc.coupon_type = luo.coupon_type " +
            "LEFT JOIN store_img simg ON simg.id = tc.image_id AND simg.delete_flag = 0 " +
            "LEFT JOIN store_comment sc ON sc.business_id = luo.id AND sc.delete_flag = 0 AND sc.business_type = 5 " +
            "LEFT JOIN life_discount_coupon_user ldcu ON ldcu.id = luo.quan_id " +
            "LEFT JOIN life_discount_coupon ldc ON ldc.id = ldcu.coupon_id " +
            "${ew.customSqlSegment}")
    Long countTotalOrders(@Param(Constants.WRAPPER) QueryWrapper<LifeUserOrderVo> queryWrapper);

    /**
     * 查询过期退款订单
     * @param selectWrapper
     * @return
     */
    List<LifeUserOrderVo> selectRefundList(@Param(Constants.WRAPPER) QueryWrapper<LifeUserOrder> selectWrapper);

    @Select("SELECT count( luo.id ) FROM life_user_order luo LEFT JOIN order_coupon_middle ocm ON luo.id = ocm.order_id WHERE luo.`status` IN ( 0, 1, 2, 7 ) AND luo.delete_flag = 0 AND luo.coupon_type = 2 AND ocm.coupon_id = #{groupId}")
    Integer countBuyGroup(@Param("groupId") String groupId);

    @Select("with total_coupon as(\n" +
            "-- 团购\n" +
            "\tselect id coupon_id,2 coupon_type,lgbm.group_name coupon_name, SUBSTRING_INDEX(image_id, ',', 1) AS image_id,effective_date_type,effective_date_value \n" +
            "from life_group_buy_main lgbm \n" +
            "\tunion all\n" +
            "-- 代金券\n" +
            "\tselect id coupon_id,1 coupon_type,lc.name coupon_name, SUBSTRING_INDEX(image_path, ',', 1) AS image_id,\n" +
            "case when expiration_type = 1 then 0 else 1 end effective_date_type,case when expiration_type = 1 then expiration_date else validity_period end  effective_date_value \n" +
            "from life_coupon lc \n" +
            ")\n" +
            "select luo.id,luo.buy_time,luo.status,luo.price,luo.final_price,luo.user_id,luo.store_id,luo.order_no,luo.pay_time,luo.cancel_time,luo.finish_time,luo.order_str,luo.expert_order_id,luo.order_appraise,\n" +
            "si.store_name,si.commission_rate,si.business_section store_type,si.store_status,si.business_status,\n" +
            "count(ocm.coupon_code) coupon_count,\n" +
            "simg.img_url,\n" +
            "lu.user_phone,\n" +
            "IF(sc.id is null,false,true) as hasComment,\n" +
            "tc.*,\n" +
            "CASE\n" +
            "        WHEN si.delete_flag = 1 OR si.logout_flag = 1 THEN 1\n" +
            "        ELSE 0\n" +
            "    END AS abnormalStateFlag,\n" +
            "ldc.nominal_value,ldc.type\n" +
            "from life_user_order luo\n" +
            "left join store_info si on si.id = luo.store_id  -- 查询店铺相关 \n" +
            "left join life_user lu on lu.id = luo.user_id and lu.delete_flag = 0 -- 查询用户相关 \n" +
            "left join order_coupon_middle ocm on ocm.order_id = luo.id \n" +
            "left join total_coupon tc on tc.coupon_id = ocm.coupon_id and tc.coupon_type = luo.coupon_type\n" +
            "left join  store_img simg on simg.id = tc.image_id and simg.delete_flag = 0 \n" +
            "left join  store_comment sc on sc.business_id = luo.id and sc.delete_flag = 0 and sc.business_type = 5\n" +
            "left join life_discount_coupon_user ldcu on ldcu .id = luo.quan_id \n" +
            "left join life_discount_coupon ldc on ldc.id = ldcu.coupon_id \n" +
            "${ew.customSqlSegment}")
    IPage<LifeUserOrderVo> queryPlatformOrderList(IPage<LifeUserOrderVo> brandedPage,@Param(Constants.WRAPPER) QueryWrapper<LifeUserOrderVo> lifeUserOrderQueryWrapper);

    @Select("SELECT count( luo.id ) FROM life_user_order luo LEFT JOIN order_coupon_middle ocm ON luo.id = ocm.order_id WHERE luo.`status` IN ( 0, 1, 2, 7 ) AND luo.delete_flag = 0 AND luo.coupon_type = 1 AND ocm.coupon_id = #{groupId}")
    Integer countCouponByCouponId(@Param("groupId") String groupId);
}
