package com.cweb.controller.qianZhu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.PageUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsProductConfig;
import com.hfkj.model.ResponseData;
import com.hfkj.qianzhu.CinemaService;
import com.hfkj.service.BsProductConfigService;
import com.hfkj.sysenum.order.OrderChildProductTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value="/cinema")
@Api(value="电影票数据")
public class CinemaController {

    Logger log = LoggerFactory.getLogger(CinemaController.class);

    @Resource
    private BsProductConfigService productConfigService;

    @RequestMapping(value="/filmsPagedQuery",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据城市分页查询影片")
    public ResponseData filmsPagedQuery(@RequestParam(value = "cityId", required = false) Integer cityId,
                                        @RequestParam(value = "name", required = false) String name,
                                        @RequestParam(value = "cityCode", required = false) String cityCode,
                                        @RequestParam(value = "cinemaId", required = false) String cinemaId,
                                        @RequestParam(value = "like", required = false) Integer like,
                                        @RequestParam(value = "grade", required = false) Integer grade,
                                        @RequestParam(value = "publishDate", required = false) Integer publishDate,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {

            Map<String, Object> params = new HashMap<>();
            if (cityId != null) {
                params.put("cityId", cityId);
            }
            if (cityCode != null) {
                params.put("cityCode", cityCode);
            }
            if (cinemaId != null) {
                params.put("cinemaId", cinemaId);
            }
            params.put("pageIndex", 1);
            params.put("pageSize", 499);

            JSONObject object = CinemaService.filmsPagedQuery(params);

            JSONArray array = object.getJSONArray("data");



            List<JSONObject> list = new ArrayList<>();

            for (Object o : array) {
                JSONObject item = (JSONObject) o;
                if (item.getString("grade") == null) {
                    item.put("grade" , "0");
                }
                list.add(item);
            }

            if (list.isEmpty()) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "暂无数据！");
            }

            if (name != null) {
                list = list.stream()
                        .filter(s -> s.getString("name").contains(name)) // 使用contains方法进行模糊查询
                        .collect(Collectors.toList()); // 将结果收集到列表中
            }



            if (publishDate != null) {
                if (publishDate == 1) {
                    list = list.stream().sorted(
                            // 根据对象中的ID进行升序排序 小到大
                            Comparator.comparingLong(
                                    e -> DateUtil.timesTamp(JSONObject.parseObject(e.toString()).getString("publishDate"))
                            )
                            // 放开下面的注释,使用reversed()方法,就是降序 大到小
//                                    .reversed()
                    ).collect(Collectors.toList());
                }
                if (publishDate == 2) {
                    list = list.stream().sorted(
                            // 根据对象中的ID进行升序排序 小到大
                            Comparator.comparingLong(
                                            e -> DateUtil.timesTamp(JSONObject.parseObject(e.toString()).getString("publishDate"))
                                    )
                                    // 放开下面的注释,使用reversed()方法,就是降序 大到小
                                    .reversed()
                    ).collect(Collectors.toList());
                }

            }

//            if (like != null) {
//                if (like == 1) {
//                    list = list.stream().sorted(
//                            // 根据对象中的ID进行升序排序 小到大
//                            Comparator.comparingLong(
//                                            e -> JSONObject.parseObject(e.toString()).getLong("like")
//                                    )
//                                    // 放开下面的注释,使用reversed()方法,就是降序 大到小
////                                    .reversed()
//                    ).collect(Collectors.toList());
//                }
//                if (like == 2) {
//                    list = list.stream().sorted(
//                            // 根据对象中的ID进行升序排序 小到大
//                            Comparator.comparingLong(
//                                            e -> JSONObject.parseObject(e.toString()).getLong("like")
//                                    )
//                                    // 放开下面的注释,使用reversed()方法,就是降序 大到小
//                                    .reversed()
//                    ).collect(Collectors.toList());
//                }
//
//            }

            if (grade != null) {
                if (grade == 1) {
                    list = list.stream().sorted(
                            // 根据对象中的ID进行升序排序 小到大
                            Comparator.comparingDouble(
                                            e -> JSONObject.parseObject(e.toString()).getDouble("grade")
                                    )
                                    // 放开下面的注释,使用reversed()方法,就是降序 大到小
//                                    .reversed()
                    ).collect(Collectors.toList());
                }
                if (grade == 2) {
                    list = list.stream().sorted(
                            // 根据对象中的ID进行升序排序 小到大
                            Comparator.comparingDouble(
                                    e -> JSONObject.parseObject(e.toString()).getDouble("grade")
                            )
                            // 放开下面的注释,使用reversed()方法,就是降序 大到小
                                    .reversed()
                    ).collect(Collectors.toList());
                }

            }

//            list = list.stream().sorted(
//                    // 根据对象中的ID进行升序排序 小到大
//                    Comparator.comparingDouble(
//                                    e -> JSONObject.parseObject(e.toString()).getDouble("grade")
//                            )
//                            // 放开下面的注释,使用reversed()方法,就是降序 大到小
//                            .reversed()
//            ).collect(Collectors.toList());
            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, list.size(), pageSize, new PageInfo<>(list)));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/pagedQueryNotShownFilms",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分页查询待上映影片")
    public ResponseData pagedQueryNotShownFilms(
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {

            Map<String, Object> params = new HashMap<>();
            params.put("pageIndex", pageNum);
            params.put("pageSize", pageSize);

            return ResponseMsgUtil.success(CinemaService.pagedQueryNotShownFilms(params));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/cinemaBrands",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询所有影院品牌")
    public ResponseData cinemaBrands(
    ) {
        try {

            return ResponseMsgUtil.success(CinemaService.cinemaBrands());

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/cinemasPagedQuery",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分页查询城市影院")
    public ResponseData cinemasPagedQuery(@RequestParam(value = "cityId", required = false) Integer cityId,
                                        @RequestParam(value = "cityCode", required = false) String cityCode,
                                        @RequestParam(value = "regionId", required = false) Integer regionId,
                                        @RequestParam(value = "filmId", required = false) Integer filmId,
                                        @RequestParam(value = "cinemaId", required = false) String cinemaId,
                                        @RequestParam(value = "showDate", required = false) String showDate,
                                        @RequestParam(value = "brandKeyword", required = false) String brandKeyword,
                                        @RequestParam(name = "lon", required = true) BigDecimal lon,
                                        @RequestParam(name = "lat", required = true) BigDecimal lat,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {

            Map<String, Object> params = new HashMap<>();

            if (cityId != null) {
                params.put("cityId", cityId);
            }
            if (cityCode != null) {
                params.put("cityCode", cityCode);
            }
            if (cinemaId != null) {
                params.put("cinemaId", cinemaId);
            }
            if (filmId != null) {
                params.put("filmId", filmId);
            }
            if (regionId != null) {
                params.put("regionId", regionId);
            }
            if (brandKeyword != null) {
                params.put("brandKeyword", brandKeyword);
            }

            params.put("lon", lon);
            params.put("lat", lat);
            params.put("showDate", showDate);
            params.put("pageIndex", pageNum);
            params.put("pageSize", pageSize);

            return ResponseMsgUtil.success(CinemaService.cinemasPagedQuery(params));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/listByCinemaId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据影院id查询影片")
    public ResponseData listByCinemaId(
            @RequestParam(name = "cinemaId", required = true) Integer cinemaId
    ) {
        try {

            Map<String, Object> params = new HashMap<>();
            params.put("cinemaId", cinemaId);

            return ResponseMsgUtil.success(CinemaService.listByCinemaId(params));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getByCinemasId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据影院id查询影院")
    public ResponseData getByCinemasId(
            @RequestParam(name = "cinemaId", required = true) Integer cinemaId
    ) {
        try {

            Map<String, Object> params = new HashMap<>();
            params.put("cinemaId", cinemaId);

            return ResponseMsgUtil.success(CinemaService.getByCinemasId(params));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/listByCinemaAndFilm",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据影院和影片查询场次")
    public ResponseData listByCinemaAndFilm(
            @RequestParam(name = "cinemaId", required = true) Integer cinemaId,
            @RequestParam(name = "filmId", required = true) Integer filmId
    ) {
        try {

            Map<String, Object> params = new HashMap<>();
            params.put("cinemaId", cinemaId);
            params.put("filmId", filmId);

            return ResponseMsgUtil.success(CinemaService.listByCinemaAndFilm(params));

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/pagedQuery",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分页查询场次")
    public ResponseData pagedQuery(
            @RequestParam(name = "cityId", required = false) Integer cityId,
            @RequestParam(name = "cityCode", required = false) String cityCode,
            @RequestParam(name = "cinemaId", required = false) Integer cinemaId,
            @RequestParam(name = "filmId", required = false) Integer filmId,
            @RequestParam(value = "showTimeBeginTime" , required = false) String showTimeBeginTime,
            @RequestParam(value = "showTimeEndTime" , required = false) String showTimeEndTime,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {

            Map<String, Object> params = new HashMap<>();

            if (cityId != null) {
                params.put("cityId", cityId);
            }
            if (cityCode != null) {
                params.put("cityCode", cityCode);
            }
            if (cinemaId != null) {
                params.put("cinemaId", cinemaId);
            }
            if (filmId != null) {
                params.put("filmId", filmId);
            }
            if (showTimeBeginTime != null) {
                params.put("showTimeBeginTime", showTimeBeginTime);
            }
            if (showTimeEndTime != null) {
                params.put("showTimeEndTime", showTimeEndTime);
            }

            params.put("pageIndex", pageNum);
            params.put("pageSize", pageSize);

            JSONObject object = CinemaService.pagedQuery(params);
            JSONArray jsonArray = object.getJSONArray("data");
            BsProductConfig productConfig = productConfigService.queryDetail(OrderChildProductTypeEnum.type3.getCode());

            for (Object array: jsonArray) {
                JSONObject jsonObject = (JSONObject) array;
                BigDecimal salePrice = jsonObject.getBigDecimal("price").add(jsonObject.getBigDecimal("fastModePrice").multiply(productConfig.getDiscount()).divide(new BigDecimal(100) , 2, RoundingMode.HALF_UP));
                if (salePrice.compareTo(jsonObject.getBigDecimal("price")) > 0) {
                    jsonObject.put("salePrice" , salePrice);
                } else {
                    jsonObject.put("salePrice" , jsonObject.getBigDecimal("price"));
                }
            }

            JSONArray newJSONArray = jsonArray.stream().sorted(
                    // 根据对象中的ID进行升序排序 小到大
                    Comparator.comparingLong(
                            e -> DateUtil.timesTamp(JSONObject.parseObject(e.toString()).getString("showTime"))
                    )
                    // 放开下面的注释,使用reversed()方法,就是降序 大到小
                    // .reversed()
            ).collect(Collectors.toCollection(JSONArray::new));

            object.put("data" , newJSONArray);

            return ResponseMsgUtil.success(object);

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/getRealTimeSeatByShowId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询场次实时座位")
    public ResponseData getRealTimeSeatByShowId(
            @RequestParam(name = "showId", required = true) Long showId
    ) {
        try {

            Map<String, Object> params = new HashMap<>();
            params.put("showId", showId);

            JSONObject object = CinemaService.getRealTimeSeatByShowId(params).getJSONObject("data");
            JSONArray jsonArray = object.getJSONArray("seats");
            JSONArray areaPrices = object.getJSONArray("areaPrices");

            BsProductConfig productConfig = productConfigService.queryDetail(OrderChildProductTypeEnum.type3.getCode());

            for(Object array : jsonArray) {
                JSONArray seats = (JSONArray) array;
                if (!seats.isEmpty()) {
                    for(Object s : seats) {
                        JSONObject jsonObject = (JSONObject) s;
                        if (jsonObject != null) {
                            BigDecimal salePrice = jsonObject.getBigDecimal("price").add(jsonObject.getBigDecimal("fastDrawModePrice").multiply(productConfig.getDiscount()).divide(new BigDecimal(100) , 2, RoundingMode.HALF_UP));

                            if (salePrice.compareTo(jsonObject.getBigDecimal("price")) > 0) {
                                jsonObject.put("salePrice" , salePrice);
                            } else {
                                jsonObject.put("salePrice" , jsonObject.getBigDecimal("price"));
                            }
                        }
                    }
                }
            }

            if (areaPrices != null) {

                String[] areaName = new String[]{"特价" , "优选" , "最佳" , "中心" , "" , ""};

                for (int i = 0; i < areaPrices.size(); i++) {
                    JSONObject priceObject = (JSONObject) areaPrices.get(i);
                    BigDecimal salePrice = priceObject.getBigDecimal("price").add(priceObject.getBigDecimal("qmmPrice").multiply(productConfig.getDiscount()).divide(new BigDecimal(100) , 2, RoundingMode.HALF_UP));
                    if (salePrice.compareTo(priceObject.getBigDecimal("price")) > 0) {
                        priceObject.put("salePrice" , salePrice);
                    } else {
                        priceObject.put("salePrice" , priceObject.getBigDecimal("price"));
                    }

                    priceObject.put("areaName" , areaName[i]);

                }

            }

            object.put("seats" , jsonArray);
            object.put("areaPrices" , areaPrices);

            return ResponseMsgUtil.success(object);

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
