package com.iamberry.wechat.handles.statistics;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.StatisticsSalesOrderUtil;
import com.iamberry.wechat.core.entity.statictics.StatisticsSalesOrder;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.tools.ResultInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by liuzhiwei on 2017/9/19.
 */
@Controller
@RequestMapping("/admin/orderStatistics")
public class OrderStatisticsHandler {

    //存储一年之中所有月份
    private String[] months = {"01","02","03","04","05","06","07","08","09","10","11","12"};
    @Autowired
    private AdminOrderService adminOrderService;


    /**
     * 进入销售统计页面
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/_sales_order_statistics")
    public ModelAndView salesOrderStatistics(HttpServletRequest request) throws Exception {
        ModelAndView mv = new ModelAndView("admin/statistics/salesStatistics");
        return mv;
    }

    /**
     * 查询本周，上周，今年的统计数量
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_order_statistics")
    public ResultMsg selectOrderStatistics(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        Map<String,Object> map = new HashMap<String,Object>();

        //查询本周统计数据
        List<StatisticsSalesOrder> listWeekNum = adminOrderService.listWeekNum();
        String[] weekDate = getThisWeek();
        //封装本周销售数据
        listWeekNum = getWeekList(listWeekNum,weekDate);
        try {
            Collections.sort(listWeekNum, new StatisticsSalesOrderUtil());
        } catch (Exception e) {
            System.out.println("-------------集合排序失败------------");
        }

        //查询上周统计数据
        List<StatisticsSalesOrder> listLastWeekNum = adminOrderService.listLastWeekNum();
        String[] LastWeekDate = getLastWeek();
        //封装上周销售数据
        listLastWeekNum = getWeekList(listLastWeekNum,LastWeekDate);
        try {
            Collections.sort(listLastWeekNum, new StatisticsSalesOrderUtil());
        } catch (Exception e) {
            System.out.println("-------------集合排序失败------------");
        }
        //封装一年的销售数据
        List<StatisticsSalesOrder> listYearNum = getYearList();
        try {
            Collections.sort(listYearNum, new StatisticsSalesOrderUtil());
        } catch (Exception e) {
            System.out.println("-------------集合排序失败------------");
        }

        map.put("listWeekNum",listWeekNum);
        map.put("listLastWeekNum",listLastWeekNum);
        map.put("listYearNum",listYearNum);
        msg.setData(map);
        msg.setStatus(true);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        return msg;
    }

    /**
     * 按月查询统计数量
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_order_by_month")
    public ResultMsg selectOrderByMonth(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        String month = request.getParameter("month");
        if (!StringUtils.isNotEmpty(month)) {
            msg.setStatus(false);
            msg.setResultCode(ResultInfo.ERRORCODE);
            return msg;
        }
        List<StatisticsSalesOrder> listMonthNum = getMonthList(month);
        try {
            Collections.sort(listMonthNum, new StatisticsSalesOrderUtil());
        } catch (Exception e) {
            System.out.println("-------------集合排序失败------------");
        }
        msg.setData(listMonthNum);
        msg.setStatus(true);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        return msg;
    }

    /**
     * 按月份封装销售数据
     * @param
     * @return
     */
    public List<StatisticsSalesOrder> getMonthList(String month) throws Exception {
        month = month + "-01";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        StatisticsSalesOrder salesOrder = new StatisticsSalesOrder();
        salesOrder.setSalesDate(format.parse(month));
        List<StatisticsSalesOrder> listMonthNum = adminOrderService.listMonthNum(salesOrder);
        List<StatisticsSalesOrder> listMonth = new ArrayList<StatisticsSalesOrder>();
        String[] days = getMonthDate(month);
        listMonth.addAll(listMonthNum);
        if (listMonthNum != null && listMonthNum.size() > 0) {
            for (int i = 0;i < days.length;i++) {
                boolean flag = true;
                for(StatisticsSalesOrder order : listMonthNum) {
                    if (days[i].equals(format.format(order.getSalesDate()))) {
                        flag = false;
                    }
                }
                if (flag) {
                    StatisticsSalesOrder salOrder = new StatisticsSalesOrder();
                    salOrder.setSalesBlackNum(0);
                    salOrder.setSalesBlueNum(0);
                    salOrder.setSalesRedNum(0);
                    salOrder.setSalesNum(0);
                    salOrder.setSalesDate(format.parse(days[i]));
                    listMonth.add(salOrder);
                }
            }
        } else {
            for (int i = 0;i < days.length;i++) {
                StatisticsSalesOrder salOrder = new StatisticsSalesOrder();
                salOrder.setSalesBlackNum(0);
                salOrder.setSalesBlueNum(0);
                salOrder.setSalesRedNum(0);
                salOrder.setSalesNum(0);
                salOrder.setSalesDate(format.parse(days[i]));
                listMonth.add(salOrder);
            }
        }
        return listMonth;
    }

    /**
     * 封装本周销售数据
     * @param
     * @return
     */
    public List<StatisticsSalesOrder> getWeekList(List<StatisticsSalesOrder> listWeekNum,
                                                  String[] weekDate) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<StatisticsSalesOrder> listWeek = new ArrayList<StatisticsSalesOrder>();
        listWeek.addAll(listWeekNum);
        //添加中断的日期的统计数
        if (listWeekNum != null && listWeekNum.size() > 0) {
            for (int i = 0;i < weekDate.length;i++) {
                boolean flag = true;
                for (StatisticsSalesOrder order : listWeekNum) {
                    if (weekDate[i].equals(format.format(order.getSalesDate()))) {
                        flag = false;
                    }
                }
                if (flag) {
                    StatisticsSalesOrder salOrder = new StatisticsSalesOrder();
                    salOrder.setSalesBlackNum(0);
                    salOrder.setSalesBlueNum(0);
                    salOrder.setSalesRedNum(0);
                    salOrder.setSalesNum(0);
                    salOrder.setSalesDate(format.parse(weekDate[i]));
                    listWeek.add(salOrder);
                }
            }
        } else {
            for (int i = 0;i < weekDate.length;i++) {
                StatisticsSalesOrder salOrder = new StatisticsSalesOrder();
                salOrder.setSalesBlackNum(0);
                salOrder.setSalesBlueNum(0);
                salOrder.setSalesRedNum(0);
                salOrder.setSalesNum(0);
                salOrder.setSalesDate(format.parse(weekDate[i]));
                listWeek.add(salOrder);
            }
        }
        return listWeek;
    }

    /**
     * 封装一年的销售数据
     * @param
     * @return
     */
    public List<StatisticsSalesOrder> getYearList () throws Exception {
        StatisticsSalesOrder salesOrder = new StatisticsSalesOrder();
        Date date = new Date();
        salesOrder.setSalesDate(date);
        //查询今年统计数据
        List<StatisticsSalesOrder> listYearNum = adminOrderService.listYearNum(salesOrder);
        List<StatisticsSalesOrder> listYear = new ArrayList<StatisticsSalesOrder>();
        listYear.addAll(listYearNum);
        if (listYearNum != null && listYearNum.size() > 0) {
            for (int i = 0;i < months.length;i++) {
                boolean flag = true;
                for (StatisticsSalesOrder order : listYearNum) {
                    if (months[i].equals(order.getSalesMonth())) {
                        flag = false;
                    }
                }
                if (flag) {
                    StatisticsSalesOrder salOrder = new StatisticsSalesOrder();
                    salOrder.setSalesBlackNum(0);
                    salOrder.setSalesBlueNum(0);
                    salOrder.setSalesRedNum(0);
                    salOrder.setSalesNum(0);
                    salOrder.setSalesMonth(months[i]);
                    listYear.add(salOrder);
                }
            }
        }  else {
            for (int i = 0;i < months.length;i++) {
                StatisticsSalesOrder salOrder = new StatisticsSalesOrder();
                salOrder.setSalesBlackNum(0);
                salOrder.setSalesBlueNum(0);
                salOrder.setSalesRedNum(0);
                salOrder.setSalesNum(0);
                salOrder.setSalesMonth(months[i]);
                listYear.add(salOrder);
            }
        }
        return listYear;
    }

    /**
     * 获取上周所有日期节点
     * @param
     * @return
     */
    public String[] getLastWeek() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, -1);
        String[] days = new String[7];
        for (int i = 0; i < 7; i++) {
            cal.add(Calendar.DATE, -1 * cal.get(Calendar.DAY_OF_WEEK) + 2 + i);
            days[i] = format.format(cal.getTime());
        }
        return days;
    }

    /**
     * 获取本周所有日期节点
     * @param
     * @return
     */
    public String[] getThisWeek() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String[] days = new String[7];
        Calendar c = Calendar.getInstance();
        int weekday = c.get(7)-1;
        c.add(5,-weekday);
        for (int i = 0; i < 7; i++) {
            c.add(5,1);
            days[i] = format.format(c.getTime());
        }
        return days;
    }

    /**
     * 获取指定年月的所有日期点
     * @param date
     * @return
     */
    public String[] getMonthDate(String date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
        calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(5, 7)) -1);
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        String[] days = new String[maxDay];
        for(int i = 1; i <= maxDay; i++){
            StringBuilder str = new StringBuilder();
            str.append(date.substring(0, 4));
            str.append("-");
            str.append(date.substring(5, 7));
            str.append("-");
            if (i < 10) {
                str.append("0");
                str.append(i);
            } else {
                str.append(i);
            }
            days[i-1] = str.toString();
        }
        return days;
    }

}
