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.Param;
import org.apache.ibatis.annotations.Select;
import shop.alien.entity.store.StoreClockIn;
import shop.alien.entity.store.vo.StoreClockInDeleteFlagVo;
import shop.alien.entity.store.vo.StoreClockInVo;

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

/**
 * <p>
 * 店铺打卡 Mapper 接口
 * </p>
 *
 * @author ssk
 * @since 2025-05-15
 */
public interface StoreClockInMapper extends BaseMapper<StoreClockIn> {

    @Select("select storeUser.logout_flag,clock.id, clock.user_id, clock.store_id, clock.permission, user.user_name, store.store_name, store.store_blurb storeBlurb, store.score_avg score, clock.like_count, store.store_position, clock.content, clock.created_time, clock.img_url clockImg, img.img_url storeImg, user.user_image userImg,clock.maybe_ai_content," +
            "store.administrative_region_district_name region, dict.dict_detail storeType, clock.phone_user_type phoneUserType, clock.phone_ref_id phoneRefId, " +
            "CASE WHEN clock.phone_user_type = 1 THEN CONCAT('user_', (SELECT user_phone FROM life_user WHERE id = clock.phone_ref_id AND delete_flag = 0 LIMIT 1)) " +
            "WHEN clock.phone_user_type = 2 THEN CONCAT('store_', (SELECT phone FROM store_user WHERE id = clock.phone_ref_id AND delete_flag = 0 LIMIT 1)) " +
            "WHEN clock.phone_user_type = 3 THEN CONCAT('lawyer_', (SELECT phone FROM lawyer_user WHERE id = clock.phone_ref_id AND delete_flag = 0 LIMIT 1)) " +
            "END phoneId, store.business_section,store.business_section_name,business_types_name,img1.img_url entranceImage," +
            "( " +
            " select ifnull(round(sum(uorder.price) / count(1), 0), 0) " +
            " from life_user_order uorder " +
            " where uorder.store_id = store.id and uorder.status = '1' and uorder.delete_flag = 0 " +
            ") perCapitaPrice, " +
            "( " +
            " select ifnull(round(avg(cr_avg.score), 1), 0) " +
            " from common_rating cr_avg " +
            " where cr_avg.business_type = 1 and cr_avg.business_id = store.id and cr_avg.delete_flag = 0 " +
            " and (cr_avg.audit_status is null or cr_avg.audit_status <> 2) " +
            ") score, " +
            "( " +
            " select ifnull(count(1), 0) " +
            " from common_rating cr_cnt " +
            " where cr_cnt.business_type = 1 and cr_cnt.business_id = store.id and cr_cnt.delete_flag = 0 " +
            " and (cr_cnt.audit_status is null or cr_cnt.audit_status <> 2) " +
            ") rating_count " +
            "from store_clock_in clock " +
            "join life_user user on user.id = clock.user_id " +
            "join store_info store on store.id = clock.store_id " +
            "join store_user storeUser on storeUser.store_id = store.id " +
            "left join store_img img on img.store_id = clock.store_id and img.img_type = '10' and img.delete_flag = 0 " +
            "left join store_img img1 on img1.store_id = clock.store_id and img1.img_type = '1' and img1.delete_flag = 0 " +
            "left join store_dictionary dict on dict.type_name = 'storeType' and store.store_type = dict.dict_id and dict.delete_flag = 0 " +
            "${ew.customSqlSegment} ")
    IPage<StoreClockInVo> getStoreClockInList(IPage<StoreClockIn> page, @Param(Constants.WRAPPER) QueryWrapper<StoreClockIn> queryWrapper);

    /**
     * 获取门店打卡次数
     *
     * @return list
     */
    @Select("SELECT store_id as storeId, count(store_id) as count FROM `store_clock_in` where delete_flag = 0 and check_flag != 3 GROUP BY store_id ")
    List<Map<Integer, Integer>> getStoreClockInCount();
     /**
      * 获取所有店铺打卡次数（有图片并且设置为可见的）
      *
      * @return map
      */
    @Select("SELECT store_id as storeId, count(store_id) as count FROM `store_clock_in` where delete_flag = 0 and permission = 1 and img_url is not null GROUP BY store_id ")
    List<Map<Integer, Integer>> getStoreClockInWithCanLookCount();

    /**
     * 用户打卡记录中出现的年份（降序）。
     * 时间维度均使用 {@code store_clock_in.created_time}。
     */
    @Select("SELECT DISTINCT YEAR(clock.created_time) FROM store_clock_in clock " +
            "WHERE clock.user_id = #{userId} AND clock.delete_flag = 0 " +
            "AND (clock.check_flag IS NULL OR clock.check_flag NOT IN (3)) " +
            "ORDER BY YEAR(clock.created_time) DESC")
    List<Integer> listDistinctClockInYears(@Param("userId") Integer userId);

    /**
     * 用户打过卡的城市（门店行政区域市名称，去重）
     */
    @Select("SELECT DISTINCT store.administrative_region_city_name FROM store_clock_in clock " +
            "INNER JOIN store_info store ON store.id = clock.store_id AND store.delete_flag = 0 " +
            "WHERE clock.user_id = #{userId} AND clock.delete_flag = 0 " +
            "AND (clock.check_flag IS NULL OR clock.check_flag NOT IN (3)) " +
            "AND store.administrative_region_city_name IS NOT NULL AND store.administrative_region_city_name <> '' " +
            "ORDER BY store.administrative_region_city_name")
    List<String> listDistinctClockInCityNames(@Param("userId") Integer userId);

    /**
     * 指定年份内有打卡的月份（1-12）；传入 city 时仅统计该城市的打卡。
     * 年份、月份均按 {@code store_clock_in.created_time} 计算。
     */
    @Select("<script>" +
            "SELECT DISTINCT MONTH(clock.created_time) FROM store_clock_in clock " +
            "INNER JOIN store_info store ON store.id = clock.store_id AND store.delete_flag = 0 " +
            "WHERE clock.user_id = #{userId} AND clock.delete_flag = 0 " +
            "AND (clock.check_flag IS NULL OR clock.check_flag NOT IN (3)) " +
            "AND YEAR(clock.created_time) = #{year} " +
            "<if test=\"city != null and city != ''\">AND store.administrative_region_city_name = #{city}</if>" +
            "</script>")
    List<Integer> listClockInMonthsByYear(@Param("userId") Integer userId,
                                          @Param("year") Integer year,
                                          @Param("city") String city);

    /**
     * 按用户+年份查询去重城市（城市用于页面回显统计）
     */
    @Select("<script>" +
            "SELECT DISTINCT store.administrative_region_city_name FROM store_clock_in clock " +
            "INNER JOIN store_info store ON store.id = clock.store_id AND store.delete_flag = 0 " +
            "WHERE clock.user_id = #{userId} AND clock.delete_flag = 0 " +
            "AND (clock.check_flag IS NULL OR clock.check_flag NOT IN (3)) " +
            "<if test=\"year != null\">AND YEAR(clock.created_time) = #{year}</if> " +
            "<if test=\"month != null\">AND MONTH(clock.created_time) = #{month}</if> " +
            "AND store.administrative_region_city_name IS NOT NULL AND store.administrative_region_city_name != '' " +
            "ORDER BY store.administrative_region_city_name" +
            "</script>")
    List<String> listDistinctClockInCityNamesByYear(@Param("userId") Integer userId,
                                                    @Param("year") Integer year,
                                                    @Param("month") Integer month);

    /**
     * 按用户+年份(+城市)统计去重打卡地点数（门店数）
     */
    @Select("<script>" +
            "SELECT COUNT(DISTINCT clock.store_id) FROM store_clock_in clock " +
            "INNER JOIN store_info store ON store.id = clock.store_id AND store.delete_flag = 0 " +
            "WHERE clock.user_id = #{userId} AND clock.delete_flag = 0 " +
            "AND (clock.check_flag IS NULL OR clock.check_flag NOT IN (3)) " +
            "<if test=\"year != null\">AND YEAR(clock.created_time) = #{year}</if> " +
            "<if test=\"month != null\">AND MONTH(clock.created_time) = #{month}</if> " +
            "<if test=\"city != null and city != ''\">AND store.administrative_region_city_name = #{city}</if> " +
            "</script>")
    Integer countDistinctClockInStoreByCondition(@Param("userId") Integer userId,
                                                 @Param("year") Integer year,
                                                 @Param("month") Integer month,
                                                 @Param("city") String city);

    /**
     * 按主键查询删除标记、门店 id 及门店营业状态（打卡含已逻辑删除；门店左连接不过滤 delete_flag）
     */
    @Select("SELECT clock.delete_flag AS deleteFlag, clock.store_id AS storeId, store.business_status AS businessStatus " +
            "FROM store_clock_in clock " +
            "LEFT JOIN store_info store ON store.id = clock.store_id " +
            "WHERE clock.id = #{id} LIMIT 1")
    StoreClockInDeleteFlagVo selectDeleteFlagAndBusinessStatusById(@Param("id") Integer id);
}
