package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.OperatingReport;
import com.ym.mec.biz.dal.page.OperatingReportQueryInfo;
import com.ym.mec.biz.service.OperatingReportService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Api(tags = "经营报表服务")
@RequestMapping("operatingReport")
@RestController
public class OperatingReportController extends BaseController {

    @Autowired
    private OperatingReportService operatingReportService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;

    @ApiOperation("报表列表")
    @GetMapping(value = "/queryPage")
    @PreAuthorize("@pcs.hasPermissions('operatingReport/queryPage')")
    public HttpResponseResult<PageInfo<OperatingReport>> queryPage(OperatingReportQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                return failed("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))) {
                    return failed("非法请求");
                }
            }
        }
        if (queryInfo.getMonth() != null) {
            queryInfo.setStartTime(DateUtil.getFirstDayOfMonth(queryInfo.getMonth()));
            queryInfo.setEndTime(DateUtil.getLastDayOfMonth(queryInfo.getMonth()));
        }
        return succeed(operatingReportService.queryPage(queryInfo));
    }


    @ApiOperation(value = "经营报表导出")
    @GetMapping("/export")
    @PreAuthorize("@pcs.hasPermissions('operatingReport/export')")
    public void operatingReport(OperatingReportQueryInfo queryInfo, HttpServletResponse response) throws IOException {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new IOException("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
                throw new IOException("用户所在分部异常");
            } else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if (!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))) {
                    throw new IOException("非法请求");
                }
            }
        }
        if (queryInfo.getMonth() != null) {
            queryInfo.setStartTime(DateUtil.getFirstDayOfMonth(queryInfo.getMonth()));
            queryInfo.setEndTime(DateUtil.getLastDayOfMonth(queryInfo.getMonth()));
        }
        queryInfo.setRows(65000);
        queryInfo.setType("organ");
        PageInfo<OperatingReport> pageList = operatingReportService.queryPage(queryInfo);
        if (pageList.getTotal() <= 0) {
            response.setStatus(200);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream outputStream = response.getOutputStream();
        try {

            String[] header = {"分部", "销售收入（元）", "服务收入（元）","其他收入（元）", "业务退费（元）", "收入合计（元）", "销售成本（元）", "固定支出（元）", "变动支出（元）", "分摊费用（元）", "成本费用合计（元）", "利润（元）"};
            String[] body = {"organName", "sellAmount", "serviceAmount","otherIncome", "refundAmount", "incomeTotal", "sellCost", "expensesAmount", "variableCost", "distributionAmount", "costAmount", "profit"};
            HSSFWorkbook workbook = POIUtil.multipleSheetExportExcel(header, body, pageList.getRows(), null);


            queryInfo.setType("school");
            pageList = operatingReportService.queryPage(queryInfo);
            String[] header2 = {"分部", "学校", "销售收入（元）", "服务收入（元）","其他收入（元）", "业务退费（元）", "收入合计（元）", "销售成本（元）", "固定支出（元）", "变动支出（元）", "分摊费用（元）", "成本费用合计（元）", "利润（元）"};
            String[] body2 = {"organName", "schoolName", "sellAmount", "serviceAmount","otherIncome", "refundAmount", "incomeTotal", "sellCost", "expensesAmount", "variableCost", "distributionAmount", "costAmount", "profit"};
            workbook = POIUtil.multipleSheetExportExcel(header2, body2, pageList.getRows(), workbook);

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=cooperationOrgan-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
