package com.winsun.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.HhrSupervisorSchool;
import com.winsun.bean.HhrUser;
import com.winsun.bean.UserSchool;
import com.winsun.mapper.*;
import com.winsun.service.AccessStatisticService;
import com.winsun.service.IHhrUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 首页数据获取
 */
@RequestMapping(("/analysis"))
@RestController
@Slf4j
public class AnalysisController extends BaseController {

    private HhrUserMapper hhrUserMapper;

    private SysUserMapper sysUserMapper;

    private HhrSupervisorSchoolMapper hhrSupervisorSchoolMapper;

    private UserSchoolMapper userSchoolMapper;

    private AccessStatisticService accessStatisticService;

    private IHhrUserService hhrUserService;

    private OrderMapper orderMapper;

    @Autowired
    public AnalysisController(SysUserMapper sysUserMapper, HhrUserMapper hhrUserMapper,
                              HhrSupervisorSchoolMapper hhrSupervisorSchoolMapper,
                              UserSchoolMapper userSchoolMapper,
                              AccessStatisticService accessStatisticService,
                              IHhrUserService hhrUserService,
                              OrderMapper orderMapper) {
        this.sysUserMapper = sysUserMapper;
        this.hhrUserMapper = hhrUserMapper;
        this.hhrSupervisorSchoolMapper = hhrSupervisorSchoolMapper;
        this.userSchoolMapper = userSchoolMapper;
        this.accessStatisticService = accessStatisticService;
        this.hhrUserService = hhrUserService;
        this.orderMapper = orderMapper;
    }

    /**
     * 获取用户信息
     * @return
     */
    @Permission(menuname="获取用户信息", value="/getInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getInfo() {
        ShiroUser shiroUser = getShiroUser();
        String account = shiroUser.getAccount();
        log.info("当前登录用户信息：" + account);
        Map<String, Object> result = new HashMap<>();
        result.put("name", shiroUser.getName());
        result.put("phone", shiroUser.getPhone());
        StringBuffer sb = new StringBuffer();
        for(String str : shiroUser.getRoleNames()) {
            sb.append(str + " ");
        }
        result.put("roleNames", sb.toString());
        result.put("deptName", shiroUser.getDeptName());
        return ResponseData.success(result);
    }

    /**
     * 获取业务数据
     * @return
     */
    @Permission(menuname="获取订单统计", value="/getOrderStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getOrderStatistic() {

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

        ShiroUser shiroUser = getShiroUser();
        Integer id = shiroUser.getId();
        List<Integer> userIds = hhrUserService.getUserIds(shiroUser.getId(), shiroUser.getRoleNames());

        String today, toWeekStart, toWeekEnd, toMonthStart, toMonthEnd;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar nowDate = Calendar.getInstance();
        Calendar weekDate = Calendar.getInstance();

        // 统计已有订单当日、周、月的情况
        today = sdf.format(nowDate.getTime());
        
        // 获取本周
        int i = weekDate.get(Calendar.DAY_OF_WEEK);
        if(weekDate.get(Calendar.DAY_OF_WEEK) != 1) {
            weekDate.add(Calendar.DATE, 2 - weekDate.get(Calendar.DAY_OF_WEEK));
        }else{
            weekDate.add(Calendar.DATE, weekDate.get(Calendar.DAY_OF_WEEK) - 7);
        }
        toWeekStart = sdf.format(weekDate.getTime());
        weekDate.add(Calendar.DATE, 7);
        toWeekEnd = sdf.format(weekDate.getTime());

        log.info("周开始时间：" + toWeekStart);
        log.info("周结束时间：" + toWeekEnd);
        
        // 获取当月
        nowDate.set(Calendar.DATE, 1);
        toMonthStart = sdf.format(nowDate.getTime());
        nowDate.add(Calendar.MONTH, 1);
        toMonthEnd = sdf.format(nowDate.getTime());
        Map<String, Object> allOrders = hhrUserMapper.statisticAllOrderNum(userIds, today, toWeekStart, toWeekEnd, toMonthStart, toMonthEnd, false);
        resultMap.put("allOrders", allOrders);
        // 统计订单完成日、周、月情况
        Map<String, Object> completeOrders = hhrUserMapper.statisticAllOrderNum(userIds, today, toWeekStart, toWeekEnd, toMonthStart, toMonthEnd, true);
        resultMap.put("completeOrders", completeOrders);

        // TODO 查询订单排名

        return ResponseData.success(resultMap);
    }

    // 获取pv
    @Permission(menuname="获取pv", value="getPvStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getPvStatistic(String startDate, String endDate, String type) {
        // 判断身份
        ShiroUser shiroUser = getShiroUser();
        log.info("获取当前登录信息" + JSON.toJSONString(shiroUser));
        List<Integer> userIds = hhrUserService.getUserIds(shiroUser.getId(), shiroUser.getRoleNames());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> pvStatisticsEchartData = null;
        try {
            // 督导查询合伙人id去匹配
            pvStatisticsEchartData = accessStatisticService.getPvStatisticsEchartData(sdf.parse(startDate), sdf.parse(endDate), type, userIds);
        }catch(ParseException e) {
            return ResponseData.error("日期格式错误");
        }

        return ResponseData.success(pvStatisticsEchartData);
    }

    // 获取uv
    @Permission(menuname="获取uv", value="getUvStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getUvStatistic(String startDate, String endDate, String type) {
        // 判断身份
        ShiroUser shiroUser = getShiroUser();
        log.info("获取当前登录信息" + JSON.toJSONString(shiroUser));
        List<Integer> userIds = hhrUserService.getUserIds(shiroUser.getId(), shiroUser.getRoleNames());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 督导查询合伙人id去匹配
        Map<String, Object> uvStatisticsEchartData = null;
        try {
            // 督导查询合伙人id去匹配
            uvStatisticsEchartData = accessStatisticService.getUvStatisticsEchartData(sdf.parse(startDate), sdf.parse(endDate), type, userIds);
        }catch(ParseException e) {
            return ResponseData.error("日期格式错误");
        }

        return ResponseData.success(uvStatisticsEchartData);

    }

    /**
     * TODO 获取成员销量排名表
     * @return
     */
    @Permission(menuname="获取成员销量排名表", value="getUserSalesStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getUserSalesStatistic(String area, String school) {

        Map<String, Object> map = new HashMap<>();
        map.put("area", area);
        map.put("school", school);
        List<Map<String, Object>> userSalesStatistic = orderMapper.getUserSalesStatistic(map);
        Map<String, Object> stringObjectMap = this.transferEchartData(userSalesStatistic);
        return ResponseData.success(stringObjectMap);
    }

    /**
     * TODO 获取楼长的销售统计
     * @return
     */
    @Permission(menuname="获取楼长的销售统计", value="getLzSalesStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getLzSalesStatistic(String area, String school) {
        Map<String, Object> map = new HashMap<>();
        map.put("area", area);
        map.put("school", school);
        List<Map<String, Object>> getLzSalesStatistic = orderMapper.getLzSalesStatistic(map);
        Map<String, Object> stringObjectMap = this.transferEchartData(getLzSalesStatistic);
        return ResponseData.success(stringObjectMap);
    }

    /**
     * TODO 获取学校销量统计
     * @return
     */
    @Permission(menuname="获取学校销量统计", value="getSchoolSaleStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getSchoolSaleStatistic(String area, String school) {
        Map<String, Object> map = new HashMap<>();
        map.put("area", area);
        map.put("school", school);
        List<Map<String, Object>> getSchoolSaleStatistic = orderMapper.getSchoolSaleStatistic(map);
        Map<String, Object> stringObjectMap = this.transferEchartData(getSchoolSaleStatistic);
        return ResponseData.success(stringObjectMap);
    }

    /**
     * TODO 获取产品转换率
     * @return
     */
    @Permission(menuname="获取产品转换率", value="getProductTransferStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getProductTransferStatistic(String area, String school) {
        Map<String, Object> map = new HashMap<>();
        map.put("area", area);
        map.put("school", school);
        List<Map<String, Object>> getProductTransferStatistic = orderMapper.getProductTransferStatistic(map);
        Map<String, Object> stringObjectMap = this.transferEchartData(getProductTransferStatistic);
        return ResponseData.success(stringObjectMap);
    }

    /**
     * TODO 获取产品销售统计
     * @return
     */
    @Permission(menuname="获取产品销售统计", value="getProductSalesStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getProductSalesStatistic(String area, String school) {
        Map<String, Object> map = new HashMap<>();
        map.put("area", area);
        map.put("school", school);
        List<Map<String, Object>> getProductSalesStatistic = orderMapper.getProductSalesStatistic(map);
        Map<String, Object> stringObjectMap = this.transferEchartData(getProductSalesStatistic);
        return ResponseData.success(stringObjectMap);
    }

    /**
     * TODO 获取区域不达标的数据
     * @return
     */
    @Permission(menuname="获取区域不达标的数据", value="getAreaSalesNotStandard", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getAreaSalesNotStandard(String area, String school) {

        return null;
    }

    public Map<String, Object> transferEchartData(List<Map<String, Object>> maps) {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> name = new ArrayList<>();
        List<Float> num = new ArrayList<>();
        maps.forEach(map -> {
            if (map.get("name") != null) {
                name.add(map.get("name").toString());
            }
            if (map.get("num") != null) {
                num.add(Float.parseFloat(map.get("num").toString()));
            }
        });
        resultMap.put("name", name);
        resultMap.put("num", num);

        return resultMap;
    }

}
