package com.ff.weijinxiao.controller;


import cn.hutool.core.util.StrUtil;
import com.ff.weijinxiao.domain.*;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.CUserService;
import com.ff.weijinxiao.service.ExpendService;
import com.ff.weijinxiao.service.OrderService;
import com.ff.weijinxiao.service.UserInfoService;
import com.ff.weijinxiao.util.JsonTool;
import com.ff.weijinxiao.util.RandomUtil;
import com.ff.weijinxiao.util.ResultTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户接口
 */
@RestController
@RequestMapping("api/userinfo")
@Api(value = "用户controller", tags = {"用户接口"})
public class UserInfoController {
    private Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    @Resource
    private OrderService orderService;

    @Resource
    private ExpendService expendService;

    public UserInfo getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return null;
        }

        CUser cUser = cUserService.findByOpenId(openId);
        if (null == cUser) {
            return null;
        }
        return cUser.getUserInfo();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
    public Map<String, Object> updateUserInfo(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        try {
            userInfoService.saveUserInfo(userInfo);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建用户信息", notes = "创建用户信息")
    public Map<String, Object> saveUserInfo(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        try {
            userInfoService.saveUserInfo(userInfo);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除用户信息", notes = "删除用户信息")
    public Map<String, Object> deleteUserInfo(@ApiParam(required = true, value = "用户id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        UserInfo userInfo = userInfoService.findById(id);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "用户不存在");
        }
        userInfoService.deleteById(id);
        return ResultTool.genSuccessResult("删除成功");
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查询用户信息", notes = "根据id查询用户信息")
    public Map<String, Object> findById(@ApiParam(required = true, value = "用户id") @RequestParam String id,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            UserInfo userInfo = userInfoService.findById(Integer.valueOf(id));
            if (null != userInfo) {
                result.put("data", userInfo);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询用户列表", notes = "查询用户列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "用户名字") @RequestParam(required = false) String phone,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        List<UserInfo> list = userInfoService.findList(param);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/listpage")
    @ApiOperation(value = "查询用户分页列表", notes = "查询用户分页列表")
    public Map<String, Object> findListPage(@ApiParam(required = false, value = "用户名字") @RequestParam(required = false) String phone,
                                            @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                            @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        Page<UserInfo> list = userInfoService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/wxapi/findbyid")
    @ApiOperation(value = "根据id查询用户信息", notes = "根据id查询用户信息")
    public Map<String, Object> wxfindById(@ApiParam(required = true, value = "用户id") @RequestParam String id,
                                          HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            UserInfo userInfo = userInfoService.findById(Integer.valueOf(id));
            if (null != userInfo) {
                result.put("data", userInfo);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建用户信息", notes = "创建用户信息")
    public Map<String, Object> wxsaveUserInfo(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                return null;
            }
            String openId = JwtHelper.parseToken(token);
            if (StringUtils.isBlank(openId)) {
                return null;
            }

            CUser cUser = cUserService.findByOpenId(openId);
            if (null == cUser) {
                return ResultTool.genSuccessResult("创建失败，登录信息错误");
            }
            userInfo.setUid(RandomUtil.genUId());
            userInfo = userInfoService.saveUserInfo(userInfo);
            cUser.setUserInfo(userInfo);
            cUserService.saveCUser(cUser);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @GetMapping("/wxapi/getdashboard")
    @ApiOperation(value = "首页信息", notes = "首页信息")
    public Map<String, Object> getDashBoard(@ApiParam(required = true, value = "统计维度 1=日 2=月 3=年 4=日期区间") @RequestParam Integer dim,
                                            @ApiParam(required = false, value = "指定统计日 格式yyyy-MM-dd") @RequestParam(required = false) String day,
                                            @ApiParam(required = false, value = "指定统计月 格式yyyy-MM") @RequestParam(required = false) String month,
                                            @ApiParam(required = false, value = "指定统计年 格式yyyy") @RequestParam(required = false) String year,
                                            @ApiParam(required = false, value = "当统计纬度为4时，开始日期:yyyy-MM-dd") @RequestParam(required = false) String beginDate,
                                            @ApiParam(required = false, value = "当统计纬度为4时，结束日期:yyyy-MM-dd") @RequestParam(required = false) String endDate,
                                            @ApiParam(required = false, value = "账本id") @RequestParam(required = false) Integer accountBookId,
                                            HttpServletRequest request) {
        logger.info("dim:" + dim + " day:" + day + " month:" + month + " year:" + year);
        logger.info("\ngetDashBoard token: {}\n", request.getHeader("token"));
        Map<String, Object> result = new HashMap<>();
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "登录信息获取失败");
            }
            if (null == dim || dim < 1 || dim > 3) {
                dim = 1;
            }
            //销售额
            Map<String, Object> orderParam = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            orderParam.put("GT_id", 0);
            orderParam.put("EQ_isDelete", 0);
            orderParam.put("EQ_uid", userInfo.getUid());
            orderParam.put("EQ_accountBook.id", userInfo.getAccountBookId());//查默认账本
            if (dim == 1) {
                String reportDay = "";
                if (StringUtils.isNotBlank(day)) {
                    reportDay = day;
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    reportDay = sdf.format(new Date());
                }
                orderParam.put("GTE_submitDate", reportDay + " 00:00:00");
                orderParam.put("LTE_submitDate", reportDay + " 23:59:59");
                param.put("GTE_dateStr", reportDay + " 00:00:00");
                param.put("LTE_dateStr", reportDay + " 23:59:59");
                logger.info("beginDay:" + reportDay + " 00:00:00" + "endDay:" + reportDay + " 23:59:59");
            } else if (dim == 2) {
                String beginDay = "";
                String endDay = "";
                if (StringUtils.isBlank(month)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    month = sdf.format(new Date());
                }
                beginDay = month + "-01 00:00:00";
                endDay = getLastDayOfMonth(Integer.valueOf(month.substring(0, 4)), Integer.valueOf(month.substring(5, 7))) + " 23:59:59";
                orderParam.put("GTE_submitDate", beginDay);
                orderParam.put("LTE_submitDate", endDay);
                param.put("GTE_dateStr", beginDay);
                param.put("LTE_dateStr", endDay);
                logger.info("beginDay:" + beginDay + " endDay:" + endDay);
            } else if (dim == 3) {
                if (StringUtils.isBlank(year)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(new Date());
                }
                String beginDay = year + "-01-01 00:00:00";
                String endDay = year + "-12-31 23:59:59";
                orderParam.put("GTE_submitDate", beginDay);
                orderParam.put("LTE_submitDate", endDay);
                param.put("GTE_dateStr", beginDay);
                param.put("LTE_dateStr", endDay);
                logger.info("beginDay:" + beginDay + " endDay:" + endDay);
            } else if (dim == 4) {
                if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
                    return ResultTool.genFailResult(ResultTool.ErrorCode_1, "开始日期和结束日期不能为空");
                }
                orderParam.put("GTE_submitDate", beginDate + " 00:00:00");
                orderParam.put("LTE_submitDate", endDate + " 23:59：59");
                param.put("GTE_dateStr", beginDate + " 00:00:00");
                param.put("LTE_dateStr", endDate + " 23:59：59");
            }
            List<Order> orderList = orderService.findList(orderParam);
            Double totalAmount = 0.0;//销售额
            Double totalFreight = 0.0;//运费
            Double totalCost = 0.0;//成本
            Double totalProfit = 0.0;//利润
            Double expendAmount = 0.0;//日常支出

            param.put("GT_id", 0);
            param.put("EQ_isDelete", 0);
            param.put("EQ_accountBook.id", userInfo.getAccountBookId());//查默认账本
            Page<Expend> list = expendService.findPage(1, 1000, param);
            if (null != list && list.getTotalElements() > 0) {
                List<Expend> data = list.getContent();
                for (Expend expend : data) {
                    expend.setUserName(userInfo.getWechatName());
                    expendAmount += expend.getMoney();
                }
            }

            if (null != orderList && orderList.size() > 0) {
                for (Order order : orderList) {
                    Double salesPrice = order.getSalesPrice();
                    if (null != salesPrice) {
                        totalAmount += salesPrice;
                    }
                    Double freight = order.getFreight();
                    if (null != freight) {
                        totalFreight += freight;
                    }
                    Double costPrice = order.getCostPrice();
                    if (null != costPrice) {
                        totalCost += costPrice;
                    }
                }
                totalProfit = new BigDecimal(totalAmount.toString()).subtract(new BigDecimal(totalFreight.toString())).subtract(new BigDecimal(totalCost.toString())).subtract(new BigDecimal(expendAmount)).doubleValue();
            }
            result.put("totalAmount", totalAmount);
            result.put("totalFreight", totalFreight);
            result.put("totalCost", totalCost);
            result.put("totalProfit", totalProfit);
            result.put("expendAmount", expendAmount);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }

    @GetMapping("/wxapi/getReport")
    @ApiOperation(value = "排行榜信息", notes = "供应商-商品-客户")
    public Map<String, Object> getTopInfo(@ApiParam(required = true, value = "统计维度 1=日 2=月 3=年 4=日期区间") @RequestParam Integer dim,
                                          @ApiParam(required = false, value = "指定统计日 格式yyyy-MM-dd") @RequestParam(required = false) String day,
                                          @ApiParam(required = false, value = "指定统计月 格式yyyy-MM") @RequestParam(required = false) String month,
                                          @ApiParam(required = false, value = "指定统计年 格式yyyy") @RequestParam(required = false) String year,
                                          @ApiParam(required = false, value = "当统计纬度为4时，开始日期:yyyy-MM-dd") @RequestParam(required = false) String beginDate,
                                          @ApiParam(required = false, value = "当统计纬度为4时，结束日期:yyyy-MM-dd") @RequestParam(required = false) String endDate,
                                          @ApiParam(required = true, value = "排行榜类型 1=供应商 2=商品 3=客户", defaultValue = "1") @RequestParam(required = true) Integer type,
                                          HttpServletRequest request) {
        //@ApiParam(required = false, value = "排序类型 1=利润 2=销量 3=销售额 4=库存量 5=购买量 6=消费额", defaultValue = "1") @RequestParam(required = false) Integer sortBy,
        logger.info("dim:" + dim + " day:" + day + " month:" + month + " year:" + year);
        Map<String, Object> result = new HashMap<>();

        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "登录信息获取失败");
            }

            if (null == dim || dim < 1 || dim > 3) {
                dim = 1;
            }

            if (dim == 1) {
                //按日
                String reportDay = "";
                if (StringUtils.isNotBlank(day)) {
                    reportDay = day;
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    reportDay = sdf.format(new Date());
                }
                String beginTime = reportDay + " 00:00:00";
                String endTime = reportDay + " 23:59:59";
                if (type == 1) {
                    List<Object[]> list = userInfoService.getSupplierReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<SupplierReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            SupplierReport supplierReport = new SupplierReport();
                            if (null != object[0]) {
                                supplierReport.setSupplierName(object[0].toString());
                            } else {
                                supplierReport.setSupplierName("");
                            }
                            if (null != object[1]) {
                                supplierReport.setStockNum(Double.parseDouble(object[1].toString()));
                            } else {
                                supplierReport.setStockNum(0.0);
                            }
                            if (null != object[2]) {
                                supplierReport.setSelledNum(Double.parseDouble(object[2].toString()));
                            } else {
                                supplierReport.setSelledNum(0.0);
                            }
                            if (null != object[3]) {
                                supplierReport.setAmount(Double.parseDouble(object[3].toString()));
                            } else {
                                supplierReport.setAmount(0.0);
                            }
                            if (null != object[4]) {
                                supplierReport.setProfit(Double.parseDouble(object[4].toString()));
                            } else {
                                supplierReport.setProfit(0.0);
                            }
                            data.add(supplierReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 2) {
                    List<Object[]> list = userInfoService.getProductReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<GoodsReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            GoodsReport goodsReport = new GoodsReport();
                            if (null != object[0]) {
                                goodsReport.setGoodsName(object[0].toString());
                            } else {
                                goodsReport.setGoodsName("");
                            }
                            if (null != object[1]) {
                                goodsReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                goodsReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                goodsReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                goodsReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                goodsReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                goodsReport.setProfit(0.0);
                            }
                            data.add(goodsReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 3) {
                    List<Object[]> list = userInfoService.getCustomerReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<CustomerReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            CustomerReport customerReport = new CustomerReport();
                            if (null != object[0]) {
                                customerReport.setCustomerName(object[0].toString());
                            } else {
                                customerReport.setCustomerName("");
                            }
                            if (null != object[1]) {
                                customerReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                customerReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                customerReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                customerReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                customerReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                customerReport.setProfit(0.0);
                            }
                            data.add(customerReport);
                        }
                        result.put("data", data);
                    }
                }
                result.put("code", 10000);
                result.put("message", "查询成功");
                return result;

            } else if (dim == 2) {
                //按月
                String beginTime = "";
                String endTime = "";
                if (StringUtils.isBlank(month)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    month = sdf.format(new Date());
                }
                beginTime = month + "-01 00:00:00";
                endTime = getLastDayOfMonth(Integer.valueOf(month.substring(0, 4)), Integer.valueOf(month.substring(5, 7))) + " 23:59:59";
                logger.info("beginTime:" + beginTime + " endDay:" + endTime);
                if (type == 1) {
                    List<Object[]> list = userInfoService.getSupplierReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<SupplierReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            SupplierReport supplierReport = new SupplierReport();
                            if (null != object[0]) {
                                supplierReport.setSupplierName(object[0].toString());
                            } else {
                                supplierReport.setSupplierName("");
                            }
                            if (null != object[1]) {
                                supplierReport.setStockNum(Double.parseDouble(object[1].toString()));
                            } else {
                                supplierReport.setStockNum(0.0);
                            }
                            if (null != object[2]) {
                                supplierReport.setSelledNum(Double.parseDouble(object[2].toString()));
                            } else {
                                supplierReport.setSelledNum(0.0);
                            }
                            if (null != object[3]) {
                                supplierReport.setAmount(Double.parseDouble(object[3].toString()));
                            } else {
                                supplierReport.setAmount(0.0);
                            }
                            if (null != object[4]) {
                                supplierReport.setProfit(Double.parseDouble(object[4].toString()));
                            } else {
                                supplierReport.setProfit(0.0);
                            }
                            data.add(supplierReport);
                        }
                        result.put("data", data);
                        return result;
                    }
                } else if (type == 2) {
                    List<Object[]> list = userInfoService.getProductReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<GoodsReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            GoodsReport goodsReport = new GoodsReport();
                            if (null != object[0]) {
                                goodsReport.setGoodsName(object[0].toString());
                            } else {
                                goodsReport.setGoodsName("");
                            }
                            if (null != object[1]) {
                                goodsReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                goodsReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                goodsReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                goodsReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                goodsReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                goodsReport.setProfit(0.0);
                            }
                            data.add(goodsReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 3) {
                    List<Object[]> list = userInfoService.getCustomerReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<CustomerReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            CustomerReport customerReport = new CustomerReport();
                            if (null != object[0]) {
                                customerReport.setCustomerName(object[0].toString());
                            } else {
                                customerReport.setCustomerName("");
                            }
                            if (null != object[1]) {
                                customerReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                customerReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                customerReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                customerReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                customerReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                customerReport.setProfit(0.0);
                            }
                            data.add(customerReport);
                        }
                        result.put("data", data);
                    }
                }
                result.put("code", 10000);
                result.put("message", "查询成功");
                return result;
            } else if (dim == 3) {
                //按年
                if (StringUtils.isBlank(year)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(new Date());
                }
                String beginTime = year + "-01-01 00:00:00";
                String endTime = year + "-12-31 23:59:59";

                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
                if (type == 1) {
                    List<Object[]> list = userInfoService.getSupplierReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<SupplierReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            SupplierReport supplierReport = new SupplierReport();
                            if (null != object[0]) {
                                supplierReport.setSupplierName(object[0].toString());
                            } else {
                                supplierReport.setSupplierName("");
                            }
                            if (null != object[1]) {
                                supplierReport.setStockNum(Double.parseDouble(object[1].toString()));
                            } else {
                                supplierReport.setStockNum(0.0);
                            }
                            if (null != object[2]) {
                                supplierReport.setSelledNum(Double.parseDouble(object[2].toString()));
                            } else {
                                supplierReport.setSelledNum(0.0);
                            }
                            if (null != object[3]) {
                                supplierReport.setAmount(Double.parseDouble(object[3].toString()));
                            } else {
                                supplierReport.setAmount(0.0);
                            }
                            if (null != object[4]) {
                                supplierReport.setProfit(Double.parseDouble(object[4].toString()));
                            } else {
                                supplierReport.setProfit(0.0);
                            }
                            data.add(supplierReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 2) {
                    List<Object[]> list = userInfoService.getProductReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<GoodsReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            GoodsReport goodsReport = new GoodsReport();
                            goodsReport.setGoodsName(object[0].toString());
                            if (null != object[0]) {
                                goodsReport.setGoodsName(object[0].toString());
                            } else {
                                goodsReport.setGoodsName("");
                            }
                            if (null != object[1]) {
                                goodsReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                goodsReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                goodsReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                goodsReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                goodsReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                goodsReport.setProfit(0.0);
                            }
                            data.add(goodsReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 3) {
                    List<Object[]> list = userInfoService.getCustomerReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<CustomerReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            CustomerReport customerReport = new CustomerReport();
                            if (null != object[0]) {
                                customerReport.setCustomerName(object[0].toString());
                            } else {
                                customerReport.setCustomerName("");
                            }
                            if (null != object[1]) {
                                customerReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                customerReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                customerReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                customerReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                customerReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                customerReport.setProfit(0.0);
                            }
                            data.add(customerReport);
                        }
                        result.put("data", data);
                    }
                }
                result.put("code", 10000);
                result.put("message", "查询成功");
                return result;
            } else if (dim == 4) {
                if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
                    return ResultTool.genFailResult(ResultTool.ErrorCode_1, "开始日期和结束日期不能为空");
                }

                String beginTime = beginDate + " 00:00:00";
                String endTime = endDate + " 23:59：59";

                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
                if (type == 1) {
                    List<Object[]> list = userInfoService.getSupplierReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<SupplierReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            SupplierReport supplierReport = new SupplierReport();
                            if (null != object[0]) {
                                supplierReport.setSupplierName(object[0].toString());
                            } else {
                                supplierReport.setSupplierName("");
                            }
                            if (null != object[1]) {
                                supplierReport.setStockNum(Double.parseDouble(object[1].toString()));
                            } else {
                                supplierReport.setStockNum(0.0);
                            }
                            if (null != object[2]) {
                                supplierReport.setSelledNum(Double.parseDouble(object[2].toString()));
                            } else {
                                supplierReport.setSelledNum(0.0);
                            }
                            if (null != object[3]) {
                                supplierReport.setAmount(Double.parseDouble(object[3].toString()));
                            } else {
                                supplierReport.setAmount(0.0);
                            }
                            if (null != object[4]) {
                                supplierReport.setProfit(Double.parseDouble(object[4].toString()));
                            } else {
                                supplierReport.setProfit(0.0);
                            }
                            data.add(supplierReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 2) {
                    List<Object[]> list = userInfoService.getProductReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<GoodsReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            GoodsReport goodsReport = new GoodsReport();
                            goodsReport.setGoodsName(object[0].toString());
                            if (null != object[0]) {
                                goodsReport.setGoodsName(object[0].toString());
                            } else {
                                goodsReport.setGoodsName("");
                            }
                            if (null != object[1]) {
                                goodsReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                goodsReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                goodsReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                goodsReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                goodsReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                goodsReport.setProfit(0.0);
                            }
                            data.add(goodsReport);
                        }
                        result.put("data", data);
                    }
                } else if (type == 3) {
                    List<Object[]> list = userInfoService.getCustomerReport(userInfo.getUid(), beginTime, endTime);
                    if (null != list && list.size() > 0) {
                        List<CustomerReport> data = new ArrayList<>();
                        for (Object[] object : list) {
                            CustomerReport customerReport = new CustomerReport();
                            if (null != object[0]) {
                                customerReport.setCustomerName(object[0].toString());
                            } else {
                                customerReport.setCustomerName("");
                            }
                            if (null != object[1]) {
                                customerReport.setSelledNum(Double.parseDouble(object[1].toString()));
                            } else {
                                customerReport.setSelledNum(0.0);
                            }
                            if (null != object[2]) {
                                customerReport.setAmount(Double.parseDouble(object[2].toString()));
                            } else {
                                customerReport.setAmount(0.0);
                            }
                            if (null != object[3]) {
                                customerReport.setProfit(Double.parseDouble(object[3].toString()));
                            } else {
                                customerReport.setProfit(0.0);
                            }
                            data.add(customerReport);
                        }
                        result.put("data", data);
                    }
                }
                result.put("code", 10000);
                result.put("message", "查询成功");
                return result;

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        int lastDay = cal.getMinimum(Calendar.DATE);
        cal.set(Calendar.DAY_OF_MONTH, lastDay - 1);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());

        return lastDayOfMonth;
    }

    @GetMapping("/wxapi/businessReport")
    @ApiOperation(value = "进销记录", notes = "进货-出货-收款")
    public Map<String, Object> businessReport(@ApiParam(required = true, value = "统计维度 1=日 2=月 3=年 4=日期区间") @RequestParam Integer dim,
                                              @ApiParam(required = false, value = "指定统计日 格式yyyy-MM-dd") @RequestParam(required = false) String day,
                                              @ApiParam(required = false, value = "指定统计月 格式yyyy-MM") @RequestParam(required = false) String month,
                                              @ApiParam(required = false, value = "指定统计年 格式yyyy") @RequestParam(required = false) String year,
                                              @ApiParam(required = false, value = "当统计纬度为4时，开始日期:yyyy-MM-dd") @RequestParam(required = false) String beginDate,
                                              @ApiParam(required = false, value = "当统计纬度为4时，结束日期:yyyy-MM-dd") @RequestParam(required = false) String endDate,
                                              @ApiParam(required = true, value = "排行榜类型 1=进货 2=出货 3=收款", defaultValue = "1") @RequestParam(required = true) Integer type,
                                              @ApiParam(required = false, value = "商品名称") @RequestParam(required = false) String goodsName,
                                              @ApiParam(required = false, value = "创建用户uid") @RequestParam(required = false) String uid,
                                              HttpServletRequest request) {
        logger.info("dim:" + dim + " day:" + day + " month:" + month + " year:" + year);
        Map<String, Object> result = new HashMap<>();
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "登录信息获取失败");
            }

            if (null == dim || dim < 1 || dim > 3) {
                dim = 1;
            }
            String searchUid = "";
            if (StrUtil.isNotBlank(uid)) {
                searchUid = uid;
            } else {
                searchUid = userInfo.getUid();
            }

            if (dim == 1) {
                //按日
                String reportDay = "";
                if (StringUtils.isNotBlank(day)) {
                    reportDay = day;
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    reportDay = sdf.format(new Date());
                }
                String beginTime = reportDay + " 00:00:00";
                String endTime = reportDay + " 23:59:59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
                if (type == 1) {
                    //进货
                    return getReport1(searchUid, goodsName, beginTime, endTime);
                } else if (type == 2) {
                    //出货
                    return getReport2(searchUid, goodsName, beginTime, endTime);
                } else if (type == 3) {
                    //收款
                    return getReport3(userInfo.getUid(), beginTime, endTime);
                }
            } else if (dim == 2) {
                //按月
                String beginTime = "";
                String endTime = "";
                if (StringUtils.isBlank(month)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    month = sdf.format(new Date());
                }
                beginTime = month + "-01 00:00:00";
                endTime = getLastDayOfMonth(Integer.valueOf(month.substring(0, 4)), Integer.valueOf(month.substring(5, 7))) + " 23:59:59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
                if (type == 1) {
                    //进货
                    return getReport1(searchUid, goodsName, beginTime, endTime);
                } else if (type == 2) {
                    //出货
                    return getReport2(searchUid, goodsName, beginTime, endTime);
                } else if (type == 3) {
                    //收款
                    return getReport3(userInfo.getUid(), beginTime, endTime);
                }
            } else if (dim == 3) {
                //按年
                if (StringUtils.isBlank(year)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(new Date());
                }
                String beginTime = year + "-01-01 00:00:00";
                String endTime = year + "-12-31 23:59:59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
                if (type == 1) {
                    //进货
                    return getReport1(searchUid, goodsName, beginTime, endTime);
                } else if (type == 2) {
                    //出货
                    return getReport2(searchUid, goodsName, beginTime, endTime);
                } else if (type == 3) {
                    //收款
                    return getReport3(userInfo.getUid(), beginTime, endTime);
                }
            } else if (dim == 4) {
                if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
                    return ResultTool.genFailResult(ResultTool.ErrorCode_1, "开始日期和结束日期不能为空");
                }
                String beginTime = "";
                String endTime = "";
                beginTime = beginDate + " 00:00:00";
                endTime = endDate + " 23:59：59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
                if (type == 1) {
                    //进货
                    return getReport1(searchUid, goodsName, beginTime, endTime);
                } else if (type == 2) {
                    //出货
                    return getReport2(searchUid, goodsName, beginTime, endTime);
                } else if (type == 3) {
                    //收款
                    return getReport3(userInfo.getUid(), beginTime, endTime);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    Map<String, Object> getReport1(String uid, String goodsName, String beginTime, String endTime) {
        Map<String, Object> result = new HashMap<>();
        List<Object[]> list = userInfoService.getBusinessReport1(uid, goodsName, beginTime, endTime);
        if (null != list && list.size() > 0) {
            List<BusinessReport> data = new ArrayList<>();
            Double purchaseNumber = 0.0;
            Double purchasePrice = 0.0;
            for (Object[] object : list) {
                BusinessReport businessReport = new BusinessReport();
                if (null != object[0]) {
                    businessReport.setSubmitDate(object[0].toString());
                } else {
                    businessReport.setSubmitDate("");
                }
                if (null != object[1]) {
                    purchaseNumber += Double.parseDouble(object[1].toString());
                }
                if (null != object[2]) {
                    businessReport.setPurchasePrice(Double.parseDouble(object[2].toString()));
                } else {
                    businessReport.setPurchasePrice(0.0);
                }
                if (null != object[1] && null != object[2]) {
                    purchasePrice += Double.parseDouble(object[1].toString()) * Double.parseDouble(object[2].toString());
                }
                if (null != object[3]) {
                    businessReport.setSellPrice(Double.parseDouble(object[3].toString()));
                } else {
                    businessReport.setSellPrice(0.0);
                }
                if (null != object[4]) {
                    businessReport.setStockNumber(Double.parseDouble(object[4].toString()));
                } else {
                    businessReport.setStockNumber(0.0);
                }
                if (null != object[5]) {
                    businessReport.setSupplierName(object[5].toString());
                } else {
                    businessReport.setSupplierName("");
                }
                if (null != object[6]) {
                    businessReport.setGoodsName(object[6].toString());
                } else {
                    businessReport.setGoodsName("");
                }
                if (null != object[7]) {
                    businessReport.setGoodsImage(object[7].toString());
                } else {
                    businessReport.setGoodsImage("");
                }
                if (null != object[8]) {
                    businessReport.setRemark(object[8].toString());
                } else {
                    businessReport.setRemark("");
                }
                data.add(businessReport);
            }
            result.put("purchaseNumber", purchaseNumber);
            result.put("purchasePrice", purchasePrice);
            result.put("data", data);
            result.put("code", 10000);
            result.put("message", "获取进货成功");
            return result;
        } else {
            result.put("purchaseNumber", 0.0);
            result.put("purchasePrice", 0.0);
            result.put("data", null);
            result.put("code", 10001);
            result.put("message", "没有数据");
            return result;
        }
    }

    Map<String, Object> getReport2(String uid, String goodsName, String beginTime, String endTime) {
        Map<String, Object> result = new HashMap<>();
        List<Object[]> list = userInfoService.getBusinessReport2(uid, goodsName, beginTime, endTime);
        if (null != list && list.size() > 0) {
            List<BusinessReport> data = new ArrayList<>();
            Double sellNumber = 0.0;
            Double sellPrice = 0.0;
            for (Object[] object : list) {
                BusinessReport businessReport = new BusinessReport();
                if (null != object[0]) {
                    businessReport.setSubmitDate(object[0].toString());
                } else {
                    businessReport.setSubmitDate("");
                }
/*                if (null != object[1]) {
                    purchaseNumber += Double.parseDouble(object[1].toString());
                }*/
                if (null != object[2]) {
                    businessReport.setPurchasePrice(Double.parseDouble(object[2].toString()));
                } else {
                    businessReport.setPurchasePrice(0.0);
                }
/*                if (null != object[1] && null != object[2]) {
                    purchasePrice += Double.parseDouble(object[1].toString()) * Double.parseDouble(object[2].toString());
                }*/
                if (null != object[3]) {
                    businessReport.setSellPrice(Double.parseDouble(object[3].toString()));
                } else {
                    businessReport.setSellPrice(0.0);
                }
                if (null != object[4]) {
                    businessReport.setStockNumber(Double.parseDouble(object[4].toString()));
                } else {
                    businessReport.setStockNumber(0.0);
                }
                if (null != object[5]) {
                    businessReport.setSupplierName(object[5].toString());
                } else {
                    businessReport.setSupplierName("");
                }
                if (null != object[6]) {
                    businessReport.setGoodsName(object[6].toString());
                } else {
                    businessReport.setGoodsName("");
                }
                if (null != object[7]) {
                    businessReport.setGoodsImage(object[7].toString());
                } else {
                    businessReport.setGoodsImage("");
                }
                if (null != object[8]) {
                    businessReport.setRemark(object[8].toString());
                } else {
                    businessReport.setRemark("");
                }
                if (null != object[9]) {
                    businessReport.setSelledNum(Double.parseDouble(object[9].toString()));
                    sellNumber += Double.parseDouble(object[9].toString());
                }
                if (null != object[10]) {
                    businessReport.setSelledMoney(Double.parseDouble(object[10].toString()));
                    sellPrice += Double.parseDouble(object[10].toString());
                }
                if (null != object[11]) {
                    businessReport.setIsSend(Integer.valueOf(object[11].toString()));
                }
                if (null != object[12]) {
                    businessReport.setIsReceived(Integer.valueOf(object[12].toString()));
                }
                data.add(businessReport);
            }
            result.put("sellNumber", sellNumber);
            result.put("sellPrice", sellPrice);
            result.put("data", data);
            result.put("code", 10000);
            result.put("message", "获取出货成功");
            return result;
        } else {
            result.put("sellNumber", 0.0);
            result.put("sellPrice", 0.0);
            result.put("data", null);
            result.put("code", 10001);
            result.put("message", "没有数据");
            return result;
        }
    }

    Map<String, Object> getReport3(String uid, String beginTime, String endTime) {
        Map<String, Object> result = new HashMap<>();
        List<Object[]> list = userInfoService.getBusinessReport3(uid, beginTime, endTime);
        if (null != list && list.size() > 0) {
            List<Object> data = new ArrayList<>();
            Double realReceive = 0.0;
            for (Object[] object : list) {
                Map<String, Object> map = new HashMap<>();
                if (null != object[0]) {
                    map.put("amount", Double.parseDouble(object[0].toString()));
                    realReceive += Double.parseDouble(object[0].toString());
                } else {
                    map.put("amount", 0.0);
                }
                if (null != object[1]) {
                    map.put("payWay", object[1].toString());
                } else {
                    map.put("payWay", "1");
                }
                data.add(map);
            }
            result.put("realReceive", realReceive);
            result.put("data", data);
            result.put("code", 10000);
            result.put("message", "获取收款成功");
            return result;
        } else {
            result.put("realReceive", 0.0);
            result.put("data", null);
            result.put("code", 10001);
            result.put("message", "没有数据");
            return result;
        }
    }

    public static void main(String[] args) {
        String temp = JwtHelper.generateToken("oEdwL0XMjqFZgR7fH6KU4FxKu7OQ");

        System.out.println(temp);
    }
}
