package com.fjs.scenic.controller.ord;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpSession;

import com.fjs.scenic.annotation.LoggerManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fjs.scenic.dto.OrdersDto;
import com.fjs.scenic.entity.order.OrderNum;
import com.fjs.scenic.entity.order.Orders;
import com.fjs.scenic.service.ord.OrdersService;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.ReturnResult;
import com.fjs.scenic.utils.Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    /**
     * 进入orders页面
     *
     * @param session
     * @return
     */
    @GetMapping("index")
    public ModelAndView index(HttpSession session) {
        return new ModelAndView("/ord/Orders");
    }

    /**
     * 查询所有订单
     *
     * @param manage      条件
     * @param currentPage 页码
     * @param pageSize    每页显示数量
     * @return
     * @throws Exception
     */
    @PostMapping("selectPage")
    @ResponseBody
    @LoggerManage(logDescription = "查询订单")
    public ReturnResult selectPage(@RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime, Orders orders, int currentPage, int pageSize)
            throws Exception {
        currentPage = (currentPage == 0) ? 1 : currentPage;
        pageSize = (pageSize == 0) ? 1 : pageSize;
        PageHelper.startPage(currentPage, pageSize);

        List<Orders> ordersList = null;
        // 如果查询条件时间不为空时 -- 暂时未用
        if ((startTime != null && !"".equals(startTime)) || (endTime != null && !"".equals(endTime))) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c = Calendar.getInstance();
            if (startTime == null || "".equals(startTime)) {
                c.setTime(dateFormat.parse(endTime));
                c.add(Calendar.MONTH, -1);
                Date mouthLater = c.getTime();
                startTime = dateFormat.format(mouthLater);
            }
            if (endTime == null || "".equals(endTime)) {
                endTime = dateFormat.format(new Date());
            }
            ordersList = ordersService.selectByJoin(
                    " o.*, d.num num, d.price price, p.name pName, p.phone pPhone, p.id_card card ",
                    " orders o LEFT JOIN order_details d ON o.id = d.order_id LEFT JOIN play_man p ON o.id = p.order_id "
                            + "where order_time between '" + startTime + "' and '" + endTime + "'  GROUP BY order_no");
        } else {

            orders.setField(" o.*, d.num num, d.price price, p.name pName, p.phone pPhone, p.id_card card ");
            orders.setParam(
                    " orders o LEFT JOIN order_details d ON o.id = d.order_id LEFT JOIN play_man p ON o.id = p.order_id");
            ordersList = ordersService.select(orders);
        }

        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
        return ReturnResult.ok(pageInfo);
    }


    /**
     * 查询所有订单
     *
     * @param orders      条件
     * @param currentPage 页码
     * @param pageSize    每页显示数量
     * @return
     * @throws Exception
     */
    @PostMapping("selectPage1")
    @ResponseBody
    @LoggerManage(logDescription = "查询订单")
    public ReturnResult selectPage1(OrdersDto orders, int currentPage, int pageSize) {
        return ReturnResult.ok(ordersService.selectPage1(orders,  currentPage, pageSize));
    }


    /**
     * 修改订单信息
     *
     * @param orders
     * @return
     */
    @PostMapping("update")
    @ResponseBody
    public ReturnResult update(Orders orders) {
        ordersService.update(orders);
        return ReturnResult.ok();
    }

    /**
     * 根据ID查询订单
     *
     * @param id
     * @return
     */
    @PostMapping("get/{id}")
    @ResponseBody
    public ReturnResult get(@PathVariable("id") Integer id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setField(" o.*, d.num num, d.price price, p.name pName, p.phone pPhone, p.id_card card ");
        orders.setParam(
                " orders o LEFT JOIN order_details d ON o.id = d.order_id LEFT JOIN play_man p ON o.id = p.order_id ");
        return ReturnResult.ok(ordersService.select(orders));
    }

    /**
     * 时段统计
     *
     * @param dataTime 某个时间 天为单位
     * @return
     * @throws Exception
     */
    @PostMapping("getHour")
    @ResponseBody
    public ReturnResult getHour(@RequestParam(required = false) String times) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateHour = new SimpleDateFormat("HH");
        String day = "";
        if (times == null || "".equals(times)) {
            day = dateFormat.format(new Date());
        } else {
            day = dateFormat.format(dateFormat.parse(times));
        }

        List<Orders> ordersList = ordersService.selectByParam("id,pay_time",
                " DATE_FORMAT(pay_time,'%Y-%m-%d')='" + day + "'");
        // 存储十二小时分别的 票数
        List<Integer> hourList = new LinkedList<Integer>();
        // 设置12小时的初始值 为0
        for (int i = 6; i <= 24; i++) {
            hourList.add(0);
        }
        // 统计
        for (Orders order : ordersList) {
            int hour = Integer.parseInt(dateHour.format(order.getPayTime()));
            if (hour >= 6) {
                hourList.set(hour - 6, hourList.get(hour - 6) + 1);
            }
        }
        return ReturnResult.build(Cons.RESULT_OK, "SUCCESS", hourList);
    }

    /**
     * 订单统计
     *
     * @param startTime 开始时间 按天为单位
     * @param endTime   结束时间 按天为单位
     * @return
     * @throws Exception
     */
    @PostMapping("getOrdersNum")
    @ResponseBody
    public ReturnResult getOrdersNum(@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateMonth = new SimpleDateFormat("yyyy-MM");

        //开始时间为空 默认为一个月以前 -- 结束时间为空默认当前时间
        Calendar c1 = Calendar.getInstance();
        if (startTime == null || "".equals(startTime)) {
            c1.setTime(new Date());
            c1.add(Calendar.MONTH, -1);
            Date mouthLater = c1.getTime();
            startTime = dateFormat.format(mouthLater);
        }
        if (endTime == null || "".equals(endTime)) {
            endTime = dateFormat.format(new Date());
        }

        String startDay = dateFormat.format(dateFormat.parse(startTime));
        String endDay = dateFormat.format(dateFormat.parse(endTime));

        Map<String, Object> map = new HashMap<String, Object>();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        // 上月时间
        Date upMouth = c.getTime();

        // 统计上月与下月的完成订单数量
        List<OrderNum> mouthSumList = ordersService.selectByCount("count(*) num, DATE_FORMAT(pay_time,'%Y-%m') time",
                " DATE_FORMAT(pay_time,'%Y-%m') between '" + dateMonth.format(upMouth) + "' and '"
                        + dateMonth.format(new Date()) + "' GROUP BY DATE_FORMAT(pay_time,'%Y-%m')");

        Map<String, Object> mouthNumList = new HashMap<>();
        int nowMouth, upnowMouth, nowWeek, upWeek = 0;
        // 防止某月数据为0，没有返回
        for (int i = 0; i < 2; i++) {
            try {
                if (dateMonth.format(upMouth).equals(mouthSumList.get(i).getTime())) {
                    mouthNumList.put("upnowMouth", mouthSumList.get(i).getNum());
                }
                if (dateMonth.format(new Date()).equals(mouthSumList.get(i).getTime())) {
                    mouthNumList.put("nowMouth", mouthSumList.get(i).getNum());
                }
            } catch (Exception e) {
//				mouthNumList.add(0);
            }
        }

        nowMouth = (int) mouthNumList.get("nowMouth"); // 本月数量
        upnowMouth = (int) mouthNumList.get("upnowMouth"); // 上月数量

        map.put("rateMouthSum", nowMouth); // 本月订单总数
        DecimalFormat df = new DecimalFormat("0.0000"); // 保留4位小数
        if (nowMouth >= upnowMouth) {
            double nums = (double) nowMouth / (double) upnowMouth;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateMouth", 0);
            } else {
                map.put("rateMouth", df.format(nums));
            }
        } else {
            double nums = (double) upnowMouth / (double) nowMouth;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateMouth", 0);
            } else {
                map.put("rateMouth", df.format(nums));
            }
        }

        // 统计这周与上周的订单数量
        List<OrderNum> weekSumList = ordersService.selectByCount("count(*) num, YEARWEEK(date_format(pay_time,'%Y-%m-%d')) timeWeek",
                "YEARWEEK(date_format(pay_time,'%Y-%m-%d')) = YEARWEEK(now()) or YEARWEEK(date_format(pay_time,'%Y-%m-%d')) = YEARWEEK(now()) - 1 GROUP BY YEARWEEK(date_format(pay_time,'%Y-%m-%d'))");

        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(new Date());

        int week = Integer.parseInt(calendar.get(Calendar.YEAR) + "" + calendar.get(Calendar.WEEK_OF_YEAR)) - 1;

        Map<String, Integer> weekNumList = new HashMap<>();
        // 防止某周数据为0，没有返回
        for (int i = 0; i < 2; i++) {
            try {
                if (weekSumList.get(i).getTimeWeek() == week - 1) {
                    weekNumList.put("upWeek", weekSumList.get(i).getNum());
                }
                if (weekSumList.get(i).getTimeWeek() == week) {
                    weekNumList.put("nowWeek", weekSumList.get(i).getNum());
                }
            } catch (Exception e) {
//				weekNumList.add(0);
            }
        }

        nowWeek = weekNumList.get("nowWeek"); // 本周数量
        upWeek = weekNumList.get("upWeek"); // 上周数量

        map.put("rateWeekSum", nowWeek); // 本周订单总数
        if (nowWeek >= upWeek) {
            double nums = (double) nowWeek / (double) upWeek;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateWeek", 0);
            } else {
                map.put("rateWeek", df.format(nums));
            }
        } else {
            double nums = (double) upWeek / (double) nowWeek;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateWeek", 0);
            } else {
                map.put("rateWeek", df.format(nums));
            }
        }

        // 获取统计数据
        List<Orders> ordersList = ordersService.selectByParam("id,pay_time",
                " DATE_FORMAT(pay_time,'%Y-%m-%d') between '" + startDay + "' and '" + endDay + "' ");
        // 存储时间段
        List<String> listTime = Utils.getBetweenDate(startDay, endDay);

        map.put("dayList", listTime); // 时间段

        // 存储时间分别的 票数
        List<Integer> dayNum = new LinkedList<Integer>();
        // 设置初始值 为0
        for (int i = 0; i < listTime.size(); i++) {
            dayNum.add(0);
        }
        // 统计
        for (Orders order : ordersList) {
            int i = 0;
            for (String time : listTime) {
                if (time.equals(dateFormat.format(order.getPayTime()))) {
                    dayNum.set(i, dayNum.get(i) + 1);
                    break;
                }
                i++;
            }
        }

        map.put("dayNum", dayNum);
        return ReturnResult.build(Cons.RESULT_OK, "SUCCESS", map);
    }

    /**
     * 销售统计
     *
     * @param startTime 开始时间 按天为单位
     * @param endTime   结束时间 按天为单位
     * @return
     * @throws Exception
     */
    @PostMapping("getOrdersMoney")
    @ResponseBody
    public ReturnResult getOrdersMoney(@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateMonth = new SimpleDateFormat("yyyy-MM");

        //开始时间为空 默认为一个月以前 -- 结束时间为空默认当前时间
        Calendar c1 = Calendar.getInstance();
        if (startTime == null || "".equals(startTime)) {
            c1.setTime(new Date());
            c1.add(Calendar.MONTH, -1);
            Date mouthLater = c1.getTime();
            startTime = dateFormat.format(mouthLater);
        }
        if (endTime == null || "".equals(endTime)) {
            endTime = dateFormat.format(new Date());
        }

        String startDay = dateFormat.format(dateFormat.parse(startTime));
        String endDay = dateFormat.format(dateFormat.parse(endTime));

        Map<String, Object> map = new HashMap<String, Object>();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        // 上月时间
        Date upMouth = c.getTime();

        // 统计上月与下月的完成订单数量
        List<OrderNum> mouthSumList = ordersService.selectByCount("sum(totel_price)/100 price, DATE_FORMAT(pay_time,'%Y-%m') time",
                " DATE_FORMAT(pay_time,'%Y-%m') between '" + dateMonth.format(upMouth) + "' and '"
                        + dateMonth.format(new Date()) + "' GROUP BY DATE_FORMAT(pay_time,'%Y-%m')");

        Map<String, Double> mouthNumList = new HashMap<>();
        double nowMouth, upnowMouth, nowWeek, upWeek = 0;
        // 防止某月数据为0，没有返回
        for (int i = 0; i < 2; i++) {
            try {
                if (dateMonth.format(upMouth).equals(mouthSumList.get(i).getTime())) {
                    mouthNumList.put("upnowMouth", mouthSumList.get(i).getPrice());
                }
                if (dateMonth.format(new Date()).equals(mouthSumList.get(i).getTime())) {
                    mouthNumList.put("nowMouth", mouthSumList.get(i).getPrice());
                }
            } catch (Exception e) {
//				mouthNumList.add(0.0);
            }
        }

        nowMouth = mouthNumList.get("nowMouth"); // 本月数量
        upnowMouth = mouthNumList.get("upnowMouth"); // 上月数量

        map.put("rateMouthSum", nowMouth); // 本月订单总数

        DecimalFormat df = new DecimalFormat("0.0000"); // 保留4位小数
        if (nowMouth >= upnowMouth) {
            double nums = (double) nowMouth / (double) upnowMouth;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateMouth", 0);
            } else {
                map.put("rateMouth", df.format(nums));
            }
        } else {
            double nums = (double) upnowMouth / (double) nowMouth;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateMouth", 0);
            } else {
                map.put("rateMouth", df.format(nums));
            }
        }

        // 统计这周与上周的订单数量
        List<OrderNum> weekSumList = ordersService.selectByCount("sum(totel_price)/100 price, YEARWEEK(date_format(pay_time,'%Y-%m-%d')) timeWeek",
                "YEARWEEK(date_format(pay_time,'%Y-%m-%d')) = YEARWEEK(now()) or YEARWEEK(date_format(pay_time,'%Y-%m-%d')) = YEARWEEK(now()) - 1 GROUP BY YEARWEEK(date_format(pay_time,'%Y-%m-%d'))"); //

        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(new Date());

        int week = Integer.parseInt(calendar.get(Calendar.YEAR) + "" + calendar.get(Calendar.WEEK_OF_YEAR)) - 1;

        Map<String, Double> weekNumList = new HashMap<>();
        // 防止某周数据为0，没有返回
        for (int i = 0; i < 2; i++) {
            try {
                if (weekSumList.get(i).getTimeWeek() == week - 1) {
                    weekNumList.put("upWeek", weekSumList.get(i).getPrice());
                }
                if (weekSumList.get(i).getTimeWeek() == week) {
                    weekNumList.put("nowWeek", weekSumList.get(i).getPrice());
                }
            } catch (Exception e) {
//				weekNumList.add(0.0);
            }
        }

        nowWeek = weekNumList.get("nowWeek"); // 本周数量
        upWeek = weekNumList.get("upWeek"); // 上周数量

        map.put("rateWeekSum", nowWeek); // 本周订单总数
        if (nowWeek >= upWeek) {
            double nums = (double) nowWeek / (double) upWeek;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateWeek", 0);
            } else {
                map.put("rateWeek", df.format(nums));
            }
        } else {
            double nums = (double) upWeek / (double) nowWeek;
            if ((nums + "").equals("NaN") || (nums + "").equals("Infinity")) {
                map.put("rateWeek", 0);
            } else {
                map.put("rateWeek", df.format(nums));
            }
        }

        // 获取统计数据
        List<Orders> ordersList = ordersService.selectByParam("id,pay_time,totel_price",
                " DATE_FORMAT(pay_time,'%Y-%m-%d') between '" + startDay + "' and '" + endDay + "'"); //
        // 存储时间段
        List<String> listTime = Utils.getBetweenDate(startDay, endDay);

        map.put("dayList", listTime); // 时间段

        // 存储时间分别的 票数
        List<Double> dayNum = new LinkedList<Double>();
        // 设置初始值 为0
        for (int i = 0; i < listTime.size(); i++) {
            dayNum.add(0.0);
        }
        // 统计
        for (Orders order : ordersList) {
            int i = 0;
            for (String time : listTime) {
                if (time.equals(dateFormat.format(order.getPayTime()))) {
                    dayNum.set(i, Double.parseDouble(df.format(dayNum.get(i) + order.getTotelPrice() / 100.0)));
                    break;
                }
                i++;
            }
        }

        map.put("dayNum", dayNum);
        return ReturnResult.build(Cons.RESULT_OK, "SUCCESS", map);
    }

    /**
     * title
     *
     * @throws Exception
     */
    @PostMapping("getTile")
    @ResponseBody
    public ReturnResult getTile() throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Object> map = new HashMap<String, Object>();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -1);
        // 昨天
        Date upDay = c.getTime();
        // 今天与昨天的金额
        List<OrderNum> sumPrice = ordersService.selectByCount("sum(totel_price)/100 price, date_format(pay_time,'%Y-%m-%d') time",
                "date_format(pay_time,'%Y-%m-%d') between '" + dateFormat.format(upDay) + "' and '" + dateFormat.format(new Date()) + "' group by date_format(pay_time,'%Y-%m-%d')");
        // 今天与昨天的订单数
        List<OrderNum> sum = ordersService.selectByCount("count(*) num, date_format(pay_time,'%Y-%m-%d') time",
                "date_format(pay_time,'%Y-%m-%d') between '" + dateFormat.format(upDay) + "' and '" + dateFormat.format(new Date()) + "' group by date_format(pay_time,'%Y-%m-%d')");

        //与时间判断
        for (int i = 0; i < 2; i++) {
            try {
                if (dateFormat.format(upDay).equals(sum.get(i).getTime())) {
                    map.put("sum1", sum.get(i).getNum() + "");
                }
                if (dateFormat.format(new Date()).equals(sum.get(i).getTime())) {
                    map.put("sum2", sum.get(i).getNum() + "");
                }
            } catch (Exception e) {
                try {
                    //判断昨天数据是否为空，如果为空 就异常添加，如果不为空就添加今天的数据
                    if (map.get("sum1") != null) {
                        map.put("sum2", 0 + "");
                    } else {
                        map.put("sum1", 0 + "");
                    }
                } catch (Exception e1) {
                    map.put("sum2", 0 + "");
                }


            }
        }
        //与时间判断
        for (int i = 0; i < 2; i++) {
            try {
                if (dateFormat.format(upDay).equals(sumPrice.get(i).getTime())) {
                    map.put("sumPrice1", sumPrice.get(i).getPrice() + "");
                }
                if (dateFormat.format(new Date()).equals(sumPrice.get(i).getTime())) {
                    map.put("sumPrice2", sumPrice.get(i).getPrice() + "");
                }

            } catch (Exception e) {
                try {
                    //判断昨天数据是否为空，如果为空 就异常添加，如果不为空就添加今天的数据
                    if (map.get("sumPrice1") != null) {
                        map.put("sumPrice2", 0 + "");
                    } else {
                        map.put("sumPrice1", 0 + "");
                    }
                } catch (Exception e1) {
                    map.put("sumPrice2", 0 + "");
                }
            }
        }

        return ReturnResult.build(Cons.RESULT_OK, "SUCCESS", map);
    }


    /**
     * 导出订单
     * @param params
     * @return
     */
    @PostMapping("export")
    @ResponseBody
    @LoggerManage(logDescription = "导出订单")
    public ReturnResult export(OrdersDto params) throws NoSuchFieldException {
        return ReturnResult.ok(ordersService.selectPage1(params,1,1000*1000*1000));
    }
    
}
