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

import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
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.msg.auth.PageResult;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.xxfc.platform.order.biz.TotalPerformanceBiz;
import com.xxfc.platform.order.pojo.QueryCriteria;
import com.xxfc.platform.order.contant.enumerate.BookkeepingTypeEnum;
import com.xxfc.platform.order.pojo.ReturnOrderAmount;
import com.xxfc.platform.order.pojo.TotalOrderRevenue;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 总业绩报表
 *
 * @author Administrator
 */

@RestController()
@RequestMapping("/report/form")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "总业绩统计")
@IgnoreClientToken
@IgnoreUserToken
public class TotalPerformanceStatementController extends CommonBaseController {
    private final TotalPerformanceBiz totalPerformanceBiz;
    private final HttpServletRequest request;
    private final UserAuthConfig userAuthConfig;
    private final UserFeign userFeign;
    private final VehicleFeign vehicleFeign;
    private final Integer HIGHEST_AUTHORITY = 1;

    @PostMapping("/list")
    public ObjectRestResponse statisticalData(@RequestBody QueryCriteria queryCriteria) throws Exception {

        UserDTO userDTO = userFeign.userinfoByToken(userAuthConfig.getToken(request)).getData();

        //获取用户权限
        List<Integer> Jurisdiction = null;

        //是否有查询所有数据的权限
        if (!HIGHEST_AUTHORITY.equals(userDTO.getDataAll())) {
            List<BranchCompany> branchCompanies = vehicleFeign.companyAll(userDTO.getDataAll(), userDTO.getDataCompany(), userDTO.getDataZone());
            Jurisdiction = branchCompanies.parallelStream().map(BranchCompany::getId).collect(Collectors.toList());

        }
        queryCriteria.setJurisdiction(Jurisdiction);

        if (BookkeepingTypeEnum.ENTER.getCode().equals(queryCriteria.getType())) {
            TotalOrderRevenue totalOrderRevenue = totalPerformanceBiz.entryStatisticalData(queryCriteria);
            return ObjectRestResponse.succ(totalOrderRevenue);
        }else if (BookkeepingTypeEnum.OUT.getCode().equals(queryCriteria.getType())){
            List<ReturnOrderAmount> returnOrderAmounts = totalPerformanceBiz.outStatisticalData(queryCriteria);
            return ObjectRestResponse.succ(PageResult.nowPageResult(queryCriteria.getPage(),queryCriteria.getLimit(),returnOrderAmounts));
        }
      return ObjectRestResponse.succ();
    }

    @PostMapping("/excel")
    public void exportTotalPerformance(@RequestBody QueryCriteria queryCriteria, HttpServletResponse response) throws Exception {

        try {
            String name = DateTimeFormatter.ofPattern("YYYYMMddHHmmss").format(LocalDateTime.now());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");

            String filename  = String.format("%s.xlsx",name);
            response.setHeader("Content-Disposition","attachment;filename="+filename);
            ServletOutputStream outputStream = response.getOutputStream();
            if (BookkeepingTypeEnum.ENTER.getCode().equals(queryCriteria.getType())) {

                totalPerformanceBiz.exportEntry(queryCriteria, name, outputStream);
            }else if (BookkeepingTypeEnum.OUT.getCode().equals(queryCriteria.getType())){
                totalPerformanceBiz.exportAccount(queryCriteria, name, outputStream);
            }else {
                throw new BaseException("无相关数据");
            }
            response.setCharacterEncoding("UTF-8");

        } catch (IOException e) {
           throw new BaseException("导入数据失败");
        }

    }
}
