package com.xxfc.platform.order.rest.background;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.wxiaoqi.security.admin.entity.BaseUserMemberLevel;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.biz.DailyMembersOrderStatisticsBiz;
import com.xxfc.platform.order.biz.DailyTravelOrderStatisticsBiz;
import com.xxfc.platform.order.biz.DailyVehicleOrderStatisticsBiz;
import com.xxfc.platform.order.biz.OrderStatisticsBiz;
import com.xxfc.platform.order.entity.OrderStatistics;
import com.xxfc.platform.order.pojo.HomePageOrderData;
import com.xxfc.platform.order.pojo.MembersOrderDto;
import com.xxfc.platform.order.pojo.OrderQuery;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
@RestController
@RequestMapping("orderStatistics")
@Api(description = "每月总的订单统计")
public class OrderStatisticsController extends BaseController<OrderStatisticsBiz, OrderStatistics> {
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    private HttpServletResponse response;
    /**
     * 租车订单
     */
    private final Integer TYPE_VEHICLE = 1;

    /**
     * 旅游订单
     */
    private final Integer TYPE_TOUR = 2;

    /**
     * 购买会员订单
     */
    private final Integer TYPE_MEMBER = 3;

    /**
     * 月总数据
     */
    private final Integer TYPE_TOTAL = 4;

    /**
     * 数据权限
     */
    private final Integer DATA_AUTHORITY = 1;

    @Autowired
    private DailyVehicleOrderStatisticsBiz vehicleBiz;


    @Autowired
    private DailyTravelOrderStatisticsBiz TravelBiz;

    @Autowired
    private DailyMembersOrderStatisticsBiz membersBiz;

    @Autowired
    private VehicleFeign vehicleFeign;


    @ApiOperation("获取订单统计数据")
    @GetMapping("/findAll/{type}")
    public ObjectRestResponse findAll(@PathVariable Integer type) {

        try {
            ObjectRestResponse<UserDTO> userDTOObjectRestResponse
                    = userFeign.userinfoByToken(userAuthConfig.getToken(getRequest()));
            if (userDTOObjectRestResponse == null || userDTOObjectRestResponse.getData() == null) {
                throw new BaseException("token失效!");
            }
            UserDTO user = userDTOObjectRestResponse.getData();
            List<Integer> companyIds = null;
            if (!DATA_AUTHORITY.equals(user.getDataAll())) {
                companyIds = vehicleFeign.getCompanyIds(user.getDataZone(), user.getDataCompany()).getData();
            }
            //只统计租车订单
            if (TYPE_VEHICLE.equals(type)) {
                return ObjectRestResponse.succ(baseBiz.getVehicleHomePageOrderData(companyIds));
            }
            //只统计旅游订单
            if (TYPE_TOUR.equals(type)) {
                return ObjectRestResponse.succ(baseBiz.getTourHomePageOrderData(companyIds));
            }
            //只统计会员订单
            if (TYPE_MEMBER.equals(type)&&DATA_AUTHORITY.equals(user.getDataAll())) {
                return ObjectRestResponse.succ(baseBiz.getMemberHomePageOrderData(companyIds));
            }
            //所有订单
            if (TYPE_TOTAL.equals(type)) {
                return ObjectRestResponse.succ(baseBiz.getTotalOrder(companyIds,user.getDataAll()));
            }
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "参数错误!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ObjectRestResponse.createDefaultFail();
        }

    }
    @PostMapping("/order")
    @ApiOperation(value = "会员统计")
    public ObjectRestResponse<List<MembersOrderDto>> getMemberOrderStatisticsData(@RequestBody OrderQuery query) throws ParseException {
        if (query.getEndTime() != null) {
            query.setEndTime(query.getEndTime() + (24 * 60 * 60 * 1000));
        }
        //获取会员等级信息
        List<BaseUserMemberLevel> memberLevels = userFeign.levels();
        //获取会员订单统计信息
        return ObjectRestResponse.succ(baseBiz.getMemberOrderStatistics(memberLevels, query));
    }


    @PostMapping("/excel")
    @ApiOperation(value = "下载excel表")
    public void downloadExcel(@RequestBody OrderQuery query) throws Exception {
        if (query.getEndTime() != null) {
            query.setEndTime(query.getEndTime() + (24 * 60 * 60 * 1000));
        }
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<BaseUserMemberLevel> memberLevels = userFeign.levels();
        List<MembersOrderDto> list = baseBiz.getMemberOrderStatistics(memberLevels, query).getList();
        List<HashMap<Object, Object>> rows = baseBiz.getRows(list, memberLevels);

        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=hwddtj.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);


    }
}
