package org.ta.pddserver.mapper;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import org.ta.pddserver.entity.AreaEntity;
import org.ta.pddserver.entity.StorageEntity;
import org.ta.pddserver.model.api.request.AreaListRequest;
import org.ta.pddserver.model.api.response.StorageListResponse;
import org.ta.pddserver.model.api.response.StorageResponse;

import java.util.List;

@Mapper
public interface StorageMapper extends BaseMapper<StorageEntity> {

    @Select("SELECT * FROM `storage` WHERE `logisticsOrderCode` = #{logisticsOrderCode} ORDER BY `uid` DESC LIMIT 1; ")
    StorageEntity getInfoByLogisticsOrderCode(@Param("logisticsOrderCode") String logisticsOrderCode);

    @Select("SELECT * FROM `storage` WHERE  `mailNo` = #{mailNo};")
    StorageEntity getInfoByMailNo(@Param("mailNo") String mailNo);

    @Select("SELECT COUNT(*) FROM `storage` WHERE  `logisticsOrderCode` = #{logisticsOrderCode} ")
    int findCountByLogisticsOrderCode(@Param("logisticsOrderCode") String logisticsOrderCode);

    @Update("UPDATE `storage` SET `num` = `num` + 1 WHERE  `logisticsOrderCode` = #{logisticsOrderCode}")
    void updateNumByLogisticsOrderCode(String logisticsOrderCode);

    @Select("SELECT COUNT(`uid`) FROM `storage` WHERE `code` = #{code}")
    int findAllCount(@Param("code") String code);

    @Select("SELECT SUM(IFNULL(`total`, 0) - IFNULL(`num`, 0)) FROM( SELECT `total`, `num` FROM `storage` WHERE `num` <> `total` AND `code` = #{code} GROUP BY `logisticsOrderCode`) t")
    Integer findReNumCount(@Param("code") String code);

    @Select("SELECT `code`, `place` FROM  `storage` WHERE `mailNo` = #{mailNo}")
    StorageResponse storageSelect(@Param("mailNo") String mailNo);

    @Select("SELECT a.`mailNo`, a.`code` , a.`place` FROM `storage` a, `unpack_mail_detail` b WHERE b.`orderCode` = #{logisticsOrderCode} AND b.`mailNo` = a.`mailNo` ORDER BY a.`place`")
    List<StorageListResponse> storageUnpackList(@Param("logisticsOrderCode") String logisticsOrderCode);

    @Select("SELECT a.`mailNo`, a.`code` , a.`place` FROM `storage` a, `collect_mail_detail` b WHERE b.`orderCode` = #{logisticsOrderCode} AND b.`mailNo` = a.`mailNo` ORDER BY a.`place`")
    List<StorageListResponse> storageCollectList(@Param("logisticsOrderCode") String logisticsOrderCode);

    @Delete("DELETE FROM `storage` WHERE `mailNo` IN ${ids}")
    void storageDel(@Param("ids") String ids);
}
