package com.happy.action;

import com.alibaba.fastjson.JSONObject;
import com.happy.Model.HousePrice;
import com.happy.Until.*;
import com.happy.common.controller.BaseController;
import com.happy.dto.HousePriceDto;
import com.happy.service.HousePriceService;
import com.happy.service.HouseService;
import com.happy.vo.DailyPriceVo;
import com.happy.vo.HousePriceDataVo;
import com.happy.vo.HousePriceOneDataVo;
import com.happy.vo.HousePriceResultVo;
import com.opensymphony.xwork2.ModelDriven;
import lombok.SneakyThrows;
import org.apache.struts2.ServletActionContext;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

public class HousePriceAction extends BaseController implements ModelDriven<HousePriceDto> {

    /**
     * 房型ID
     */
    public String roomId;
    /**
     * 民宿商家ID
     */
    public Integer merchantId;
    /**
     * 入住时间
     */
    public String startTime;
    /**
     * 离店时间
     */
    public String endTime;

    public String getRoomId() {
        return roomId;
    }

    public void setRoomId(String roomId) {
        this.roomId = roomId;
    }

    public Integer getMerchantId() {
        return merchantId;
    }

    public void setMerchantId(Integer merchantId) {
        this.merchantId = merchantId;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    private final HousePriceDto housePriceDto = new HousePriceDto();

    @Override
    public HousePriceDto getModel() {
        return housePriceDto;
    }

    @Resource(name = "housePriceService")
    private HousePriceService housePriceService;

    @Resource
    private HouseService houseService;

    /**
     * 批量改价 房态管理-房价管理
     * 约定body数据格式：{"dateList":["2023-08-11,2023-08-20"],"priceList":[{"managerId":"1586005529","houseId":"1379573861","price":"180"}]}
     */
    @SneakyThrows
    public void modifyPriceBatch() {
        String postDataStr = GetHttpParam.getRequestPostData(request);
        JSONObject postDataJSONObject = JSONObject.parseObject(postDataStr);
        List<String> dateList = postDataJSONObject.getJSONArray("dateList").toJavaList(String.class);
        List<HousePrice> priceList = postDataJSONObject.getJSONArray("priceList").toJavaList(HousePrice.class);
        housePriceService.modifyPriceBatch(dateList, priceList);
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "请求成功");
            put("code", 200);
        }}.toString());
    }

    /**
     * 改价 房态管理-房价管理
     */
    public void modifyPrice() {
        housePriceService.modifyPrice(housePriceDto);
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "请求成功");
            put("code", 200);
        }}.toString());
    }

    /**
     * 表格数据 房态管理-房价管理
     */
    public void queryPage() {
        if(housePriceDto.getSetDate() == null){
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "参数不能为空！");
                put("code", 500);
            }}.toString());
        }
        if(housePriceDto.getManagerId() == null){
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "参数不能为空！");
                put("code", 500);
            }}.toString());
        }
        if(page == null){
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "参数不能为空！");
                put("code", 500);
            }}.toString());
        }
        if(rows == null){
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "参数不能为空！");
                put("code", 500);
            }}.toString());
        }
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "请求成功");
            put("code", 200);
            put("data", housePriceService.queryPage(housePriceDto, page, rows));
        }}.toString());
    }

    public void queryDate() {
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "请求成功");
            put("code", 200);
            put("data", housePriceService.queryDate());
        }}.toString());
    }

    public void queryHouseListByManagerId() {
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "请求成功");
            put("code", 200);
            put("data", housePriceService.queryHouseListByManagerId(housePriceDto.getManagerId()));
        }}.toString());
    }

    /**
     * 表格数据 房态管理-房价管理-改价记录
     */
    public void queryPageHistory() {
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "请求成功");
            put("code", 200);
            put("data", housePriceService.queryPageHistory(housePriceDto, page, rows));
        }}.toString());
    }

    /**
     * 导出表格数据 房态管理-房价管理-改价记录
     */
    public void exportHistory() {
        housePriceService.exportHistory(housePriceDto);
    }

    /**
     * 获取价格日历
     * managerId：民宿商家ID
     * startTime：入住时间
     * endTime：离店时间
     *
     * @return
     */
    public String priceCalendar() throws ParseException {
        JSONObject resultJson = new JSONObject();
        if (merchantId == null) {
            resultJson.put("message", "商家不能为空");
            resultJson.put("code", 500);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        if (startTime == null) {
            resultJson.put("message", "月份时间不能为空");
            resultJson.put("code", 500);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }

        int days = TimeExchange.getMonthDays(startTime, Integer.valueOf(startTime.substring(5, 7)));
        String[] months = TimeExchange.getCurrentMonthTimeFrame(startTime);
        String startDate = months[0];
        String endDate = months[1];
        List<HousePriceResultVo> result = new ArrayList<>();
        List<String> dateStrs = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            String date = TimeExchange.TimeDesD(startTime, i);
            dateStrs.add(date);
        }
        Collections.sort(dateStrs);

        List<HousePriceDataVo> hprd = housePriceService.queryHousePriceDatas(merchantId, startDate, endDate);
        List<HousePriceOneDataVo> oneDatas = new ArrayList<>();
        //将数据处理成单天的
        for (HousePriceDataVo hp : hprd) {
            if (hp.getStartTime().equals(hp.getEndTime())) {
                HousePriceOneDataVo oneData = new HousePriceOneDataVo();
                oneData.setSetDate(hp.getStartTime());
                oneData.setCreateDate(hp.getCreateDate());
                oneData.setPrice(hp.getPrice());
                oneData.setHouseId(hp.getHouseId());
                oneDatas.add(oneData);
            } else {
                int beDateNum = TimeExchange.daysBetween(hp.getStartTime(), hp.getEndTime());
                for (int i = 0; i <= beDateNum; i++) {
                    HousePriceOneDataVo oneData = new HousePriceOneDataVo();
                    oneData.setSetDate(TimeExchange.TimeDesD(hp.getStartTime(), i));
                    oneData.setCreateDate(hp.getCreateDate());
                    oneData.setPrice(hp.getPrice());
                    oneData.setHouseId(hp.getHouseId());
                    oneDatas.add(oneData);
                }
            }
        }

        /**
         * 根据房型ID处理重复的数据
         */
        List<HousePriceOneDataVo> newOneDatas = new ArrayList<>();
        List<String> houseIds = oneDatas.stream().map(HousePriceOneDataVo::getHouseId).distinct().collect(Collectors.toList());
        for (String houseId : houseIds) {
            for (String str : dateStrs) {
                Optional<HousePriceOneDataVo> one = oneDatas.stream().filter(e -> e.getSetDate().equals(str) && e.getHouseId().equals(houseId)).sorted(Comparator.comparing(HousePriceOneDataVo::getCreateDate, Comparator.reverseOrder())).findFirst();
                if (one != null && one.isPresent()) {
                    HousePriceOneDataVo oneData = new HousePriceOneDataVo();
                    oneData.setSetDate(one.get().getSetDate());
                    oneData.setCreateDate(one.get().getCreateDate());
                    oneData.setPrice(one.get().getPrice());
                    oneData.setHouseId(one.get().getHouseId());
                    newOneDatas.add(oneData);
                }
            }
        }

        /**
         * 获取该民宿下最低房型价格
         */
        Double minPrice = houseService.getHouseMinPrice(merchantId);

        DecimalFormat decimalFormat = new DecimalFormat("#####.##");
        for (String str : dateStrs) {
            HousePriceResultVo data = new HousePriceResultVo();
            data.setDate(str);
            List<HousePriceOneDataVo> priceDatas = newOneDatas.stream().filter(e -> e.getSetDate().equals(str)).sorted(Comparator.comparing(HousePriceOneDataVo::getPrice)).collect(Collectors.toList());

            if (priceDatas.size() > 0 && priceDatas.get(0).getPrice() < minPrice) {
                data.setTopinfo("￥" + decimalFormat.format(priceDatas.get(0).getPrice()) + "起");
            } else {
                data.setTopinfo("￥" + decimalFormat.format(minPrice) + "起");
            }
            result.add(data);
        }

        resultJson.put("message", "查询成功");
        resultJson.put("code", 200);
        resultJson.put("data", result);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    /**
     * 根据房型ID获取每日价格
     * houseId：房型ID
     * startTime：入住时间
     * endTime：离店时间
     *
     * @return
     */
    public String dailyPrice() throws ParseException {
        JSONObject resultJson = new JSONObject();

        if (roomId == null) {
            resultJson.put("message", "房型不能为空");
            resultJson.put("code", 500);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        if (startTime == null) {
            resultJson.put("message", "入住时间不能为空");
            resultJson.put("code", 500);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        if (endTime == null) {
            resultJson.put("message", "离店时间不能为空");
            resultJson.put("code", 500);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        List<HousePriceDataVo> priceDatas = housePriceService.queryPriceByHouseId(roomId, startTime, TimeExchange.TimeDesD(endTime, -1));

        List<HousePriceOneDataVo> oneDatas = new ArrayList<>();
        //将数据处理成单天的
        for (HousePriceDataVo hp : priceDatas) {
            if (hp.getStartTime().equals(hp.getEndTime())) {
                HousePriceOneDataVo oneData = new HousePriceOneDataVo();
                oneData.setSetDate(hp.getStartTime());
                oneData.setCreateDate(hp.getCreateDate());
                oneData.setPrice(hp.getPrice());
                oneData.setHouseId(hp.getHouseId());
                oneDatas.add(oneData);
            } else {
                int beDateNum = TimeExchange.daysBetween(hp.getStartTime(), hp.getEndTime());
                for (int i = 0; i <= beDateNum; i++) {
                    HousePriceOneDataVo oneData = new HousePriceOneDataVo();
                    oneData.setSetDate(TimeExchange.TimeDesD(hp.getStartTime(), i));
                    oneData.setCreateDate(hp.getCreateDate());
                    oneData.setPrice(hp.getPrice());
                    oneData.setHouseId(hp.getHouseId());
                    oneDatas.add(oneData);
                }
            }
        }

        List<String> dateStrs = new ArrayList<>();
        int dateNum = TimeExchange.daysBetween(startTime, endTime);
        for (int i = 0; i <= dateNum; i++) {
            String date = TimeExchange.TimeDesD(startTime, i);
            dateStrs.add(date);
        }

        /**
         * 获取该房型默认价格
         */
        Double housePrice = houseService.queryPriceByHouseId(roomId);

        DailyPriceVo dpv = new DailyPriceVo();
        dpv.setList(new ArrayList<>());
        for (String dateStr : dateStrs) {
            HousePriceResultVo data = new HousePriceResultVo();
            data.setDate(dateStr);
            List<HousePriceOneDataVo> datas = oneDatas.stream().filter(e -> e.getSetDate().equals(dateStr)).sorted(Comparator.comparing(HousePriceOneDataVo::getCreateDate,Comparator.reverseOrder())).collect(Collectors.toList());

            if(dateStr.equals(endTime)){
                data.setTopinfo("离店时间");
            }else{
                if (datas.size() > 0) {
                    data.setTopinfo("1晚 共" + datas.get(0).getPrice());
                    dpv.setTotalPrice((dpv.getTotalPrice() == null ? 0 : dpv.getTotalPrice()) + datas.get(0).getPrice());
                } else {
                    data.setTopinfo("1晚 共" + housePrice);
                    dpv.setTotalPrice((dpv.getTotalPrice() == null ? 0 : dpv.getTotalPrice()) + housePrice);
                }
            }

            dpv.getList().add(data);
        }

        resultJson.put("message", "查询成功");
        resultJson.put("code", 200);
        resultJson.put("data", dpv);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

}
