package com.engine.salary.web;

import cn.hutool.core.util.BooleanUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.siaccount.param.InspectAccountParam;
import com.engine.salary.entity.siaccount.po.InsuranceAccountInspectPO;
import com.engine.salary.entity.siarchives.param.InsuranceArchivesListParam;
import com.engine.salary.entity.siexport.param.InsuranceExportParam;
import com.engine.salary.enums.siaccount.PaymentStatusEnum;
import com.engine.salary.service.SIAccountService;
import com.engine.salary.service.impl.SIAccountServiceImpl;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.wrapper.SIExportWrapper;
import com.engine.salary.wrapper.SIImportWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.Nullable;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/4/18
 * @Version V1.0
 **/
public class SIExportController {

    public SIAccountService getService(User user) {
        return ServiceUtil.getService(SIAccountServiceImpl.class, user);
    }

    public SIExportWrapper getSIExportWrapper(User user) {
        return ServiceUtil.getService(SIExportWrapper.class,user);
    }

    public SIImportWrapper getSIImportWrapper(User user) {
        return ServiceUtil.getService(SIImportWrapper.class,user);
    }

    @GET
    @Path("/archives/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        InsuranceArchivesListParam param = buildParam(request);
        User user = HrmUserVarify.getUser(request, response);
        XSSFWorkbook workbook = getSIExportWrapper(user).export(param);
        String time = LocalDate.now().toString();
        String fileName = "福利档案报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }



    @GET
    @Path("/archives/exportInspect")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportInspect(@Context HttpServletRequest request, @Context HttpServletResponse response,
                           @QueryParam("ids")List<Long> ids,@QueryParam("billMonth") String billMonth) {
        InspectAccountParam param = InspectAccountParam.builder().ids(ids).billMonth(billMonth).build();
        User user = HrmUserVarify.getUser(request, response);
//        SIAccountBiz siAccountBiz = new SIAccountBiz();
//        List<InsuranceAccountInspectPO> insuranceAccountInspectPOS = siAccountBiz.allInspects(param.getIds(), param.getBillMonth());
        List<InsuranceAccountInspectPO> insuranceAccountInspectPOS = getService(user).allInspects(param.getIds(), param.getBillMonth());
        InsuranceArchivesListParam req = new InsuranceArchivesListParam();
        req.setEmployeeIds(insuranceAccountInspectPOS.stream().map(InsuranceAccountInspectPO::getEmployeeId).distinct().collect(Collectors.toList()));
        XSSFWorkbook workbook = getSIExportWrapper(user).export(req);
        String time = LocalDate.now().toString();
        String fileName = "核算异常人员档案报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }




    @GET
    @Path("/common/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportAccount(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                  @QueryParam("billMonth") String billMonth,@QueryParam("paymentOrganization") String paymentOrganization) {
        InsuranceExportParam param = InsuranceExportParam.builder().billMonth(billMonth).paymentOrganization(paymentOrganization).build();
        User user = HrmUserVarify.getUser(request, response);
        XSSFWorkbook workbook = getSIExportWrapper(user).exportAccount(PaymentStatusEnum.COMMON.getValue(),param);
        String time = LocalDate.now().toString();
        String fileName = "正常缴纳核算报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }


    @GET
    @Path("/supplementary/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportSupplementary(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                        @QueryParam("billMonth") String billMonth,@QueryParam("paymentOrganization") String paymentOrganization) {
        InsuranceExportParam param = InsuranceExportParam.builder().billMonth(billMonth).paymentOrganization(paymentOrganization).build();
        User user = HrmUserVarify.getUser(request, response);
        XSSFWorkbook workbook = getSIExportWrapper(user).exportAccount(PaymentStatusEnum.REPAIR.getValue(),param);
        String time = LocalDate.now().toString();
        String fileName = "补缴核算报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }

    /**
     * 福利台账-退差核算数据导出
     */
    @GET
    @Path("/recession/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportRecession(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                        @QueryParam("billMonth") String billMonth,@QueryParam("creator") Long creator,@QueryParam("paymentOrganization") String paymentOrganization) {
        InsuranceExportParam param = InsuranceExportParam.builder().billMonth(billMonth).creator(creator).paymentOrganization(paymentOrganization).build();
        User user = HrmUserVarify.getUser(request, response);
        XSSFWorkbook workbook = getSIExportWrapper(user).exportAccount(PaymentStatusEnum.RECESSION.getValue(),param);
        String time = LocalDate.now().toString();
        String fileName = "退差核算报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }


    /**
     * 福利台账-补差核算数据导出
     */
    @GET
    @Path("/balance/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportBalance(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                    @QueryParam("billMonth") String billMonth, @QueryParam("paymentOrganization") String paymentOrganization) {
        InsuranceExportParam param = InsuranceExportParam.builder().billMonth(billMonth).paymentOrganization(paymentOrganization).build();
        User user = HrmUserVarify.getUser(request, response);
        XSSFWorkbook workbook = getSIExportWrapper(user).exportAccount(PaymentStatusEnum.BALANCE.getValue(),param);
        String time = LocalDate.now().toString();
        String fileName = "补差核算报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }

    @GET
    @Path("/overView/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportOverView(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                   @QueryParam("billMonth") String billMonth,@QueryParam("paymentOrganization") String paymentOrganization) {
        InsuranceExportParam param = InsuranceExportParam.builder().billMonth(billMonth).paymentOrganization(paymentOrganization).build();
        User user = HrmUserVarify.getUser(request, response);
        XSSFWorkbook workbook = getSIExportWrapper(user).exportOverView(param);
        String time = LocalDate.now().toString();
        String fileName = "总览报表" + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }

    @GET
    @Path("/exportCurrentData")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportTemplate(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        InsuranceArchivesListParam param = buildParam(request);
        User user = HrmUserVarify.getUser(request, response);
//        SIAccountBiz siAccountBiz = new SIAccountBiz();
        if (param.getInspectAll() != null && param.getInspectAll()) {
//            List<InsuranceAccountInspectPO> insuranceAccountInspectPOS = siAccountBiz.allInspects(param.getIds(), param.getBillMonth());
            List<InsuranceAccountInspectPO> insuranceAccountInspectPOS = getService(user).allInspects(param.getIds(), param.getBillMonth());
            param.setEmployeeIds(insuranceAccountInspectPOS.stream().map(InsuranceAccountInspectPO::getEmployeeId).distinct().collect(Collectors.toList()));
        }
        XSSFWorkbook workbook = getSIImportWrapper(user).exportTemplate(param);
        String time = LocalDate.now().toString();
        String fileName = "";
        if (BooleanUtil.isTrue(param.getTemplateFlag())) {
            fileName = SalaryI18nUtil.getI18nLabel( 100571, "社保福利档案模板");
        } else {
            fileName = SalaryI18nUtil.getI18nLabel( 94629, "社保福利档案");
        }
        fileName = fileName + time;
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };
        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }

    @Nullable
    private InsuranceArchivesListParam buildParam(HttpServletRequest request) {
        InsuranceArchivesListParam param = new InsuranceArchivesListParam();
        String userName = request.getParameter("userName");
        if (StringUtils.isNotBlank(userName)) {
            param.setUserName(userName);
        }
        String jobNum = request.getParameter("jobNum");
        if (StringUtils.isNotBlank(jobNum)) {
            param.setUserName(jobNum);
        }
        String departmentIds = request.getParameter("departmentIds");
        if (StringUtils.isNotBlank(departmentIds)) {
            param.setDepartmentIds(Arrays.stream(departmentIds.split(",")).map(BigDecimal::new).collect(Collectors.toList()));
        }
        String statuses = request.getParameter("statuses");
        if (StringUtils.isNotBlank(statuses)) {
            param.setStatuses(Arrays.stream(statuses.split(",")).map(String::valueOf).collect(Collectors.toList()));
        }
        String positions = request.getParameter("positions");
        if (StringUtils.isNotBlank(positions)) {
            param.setPositions(Arrays.stream(positions.split(",")).map(BigDecimal::new).collect(Collectors.toList()));
        }
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String hiredate = request.getParameter("hiredate");
        if (StringUtils.isNotBlank(hiredate)) {
            param.setHireDate(hiredate.split(","));
        }
        String dimissionDate = request.getParameter("dimissionDate");
        if (StringUtils.isNotBlank(dimissionDate)) {
            param.setDimissionDate(dimissionDate.split(","));
        }
        String hiredateStart = request.getParameter("hiredateStart");
        if (StringUtils.isNotBlank(hiredateStart)) {
            param.setHiredateStart(hiredateStart);
        }
        String hiredateEnd = request.getParameter("hiredateEnd");
        if (StringUtils.isNotBlank(hiredateEnd)) {
            param.setHiredateEnd(hiredateEnd);
        }
        String dimissionDateStart = request.getParameter("dimissionDateStart");
        if (StringUtils.isNotBlank(dimissionDateStart)) {
            param.setDimissionDateStart(dimissionDateStart);
        }
        String dimissionDateEnd = request.getParameter("dimissionDateEnd");
        if (StringUtils.isNotBlank(dimissionDateEnd)) {
            param.setDimissionDateEnd(dimissionDateEnd);
        }
        String siSchemeId = request.getParameter("siSchemeId");
        if (StringUtils.isNotBlank(siSchemeId)) {
            param.setSiSchemeId(Long.valueOf(siSchemeId));
        }
        String fundSchemeId = request.getParameter("fundSchemeId");
        if (StringUtils.isNotBlank(fundSchemeId)) {
            param.setFundSchemeId(Long.valueOf(fundSchemeId));
        }
        String otherSchemeId = request.getParameter("otherSchemeId");
        if (StringUtils.isNotBlank(otherSchemeId)) {
            param.setOtherSchemeId(Long.valueOf(otherSchemeId));
        }
        String employeeIds = request.getParameter("employeeIds");
        if (StringUtils.isNotBlank(employeeIds)) {
            param.setEmployeeIds(Arrays.stream(employeeIds.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        String keyword = request.getParameter("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            param.setKeyword(keyword);
        }
        String dataSource = request.getParameter("dataSource");
        if (StringUtils.isNotBlank(dataSource)) {
            param.setDataSource(dataSource);
        }

        String exportData = request.getParameter("exportData");
        if (StringUtils.isNotBlank(exportData)) {
            param.setExportData(Boolean.valueOf(exportData));
        }
        String inspectAll = request.getParameter("inspectAll");
        if (StringUtils.isNotBlank(inspectAll)) {
            param.setInspectAll(Boolean.valueOf(inspectAll));
        }

        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            param.setIds(Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        }

        String billMonth = request.getParameter("billMonth");
        if (StringUtils.isNotBlank(billMonth)) {
            param.setBillMonth(billMonth);
        }
        String templateFlag = request.getParameter("templateFlag");
        if (StringUtils.isNotBlank(templateFlag)) {
            param.setTemplateFlag(Boolean.valueOf(templateFlag));
        }

        return param;
    }

}
