package com.engine.salary.web;

import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.datacollection.dto.AddUpSituationDTO;
import com.engine.salary.entity.datacollection.dto.AddUpSituationRecordDTO;
import com.engine.salary.entity.datacollection.param.*;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.wrapper.AddUpSituationWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
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.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
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.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 往期累计
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
@Slf4j
public class AddUpSituationController {
    private AddUpSituationWrapper getAddUpSituationWrapper(User user) {
        return ServiceUtil.getService(AddUpSituationWrapper.class, user);
    }

    @GET
    @Path("/getSearchCondition")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSearchCondition(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::getSearchCondition);
    }


    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationQueryParam, PageInfo<AddUpSituationDTO>>(user).run(getAddUpSituationWrapper(user)::list, queryParam);
    }

    @POST
    @Path("/getDetailList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getDetailList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationQueryParam, PageInfo<AddUpSituationRecordDTO>>(user).run(getAddUpSituationWrapper(user)::getDetailList, queryParam);
    }


    @GET
    @Path("/downloadTemplate")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response getAll(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            AddUpSituationQueryParam queryParam = buildParam(request);

            XSSFWorkbook workbook = getAddUpSituationWrapper(user).downloadTemplate(queryParam);

            String fileName = "往期累计情况导入模板" + LocalDate.now();

            try {
                fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
            }

            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();

        } catch (Exception e) {
            log.error("往期累计情况导入模板导出异常", e);
            throw e;
        }
    }


    /**
     * 导出
     *
     * @param
     * @return
     */
    @GET
    @Path("/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            AddUpSituationQueryParam queryParam = buildParam(request);

            XSSFWorkbook workbook = getAddUpSituationWrapper(user).export(queryParam);

            String fileName = "往期累计情况" + LocalDate.now();
            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();
        } catch (Exception e) {
            log.error("往期累计情况导出异常", e);
            throw e;
        }
    }


    /**
     * 导出明细
     *
     * @param
     * @return
     */
    @GET
    @Path("/exportDetail")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportDetail(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            AddUpSituationQueryParam queryParam = buildParam(request);

            XSSFWorkbook workbook = getAddUpSituationWrapper(user).exportDetail(queryParam);

            String fileName = "累计情况明细" + LocalDate.now();
            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();
        } catch (Exception e) {
            log.error("累计情况明细导出异常", e);
            throw e;
        }
    }

    @Nullable
    private AddUpSituationQueryParam buildParam(HttpServletRequest request) {
        AddUpSituationQueryParam param = new AddUpSituationQueryParam();
        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            param.setIds(Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        String keyword = request.getParameter("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            param.setKeyword(keyword);
        }
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            param.setId(Long.valueOf(id));
        }
        String year = request.getParameter("year");
        if (StringUtils.isNotBlank(year)) {
            param.setYear(Integer.valueOf(year));
        }

        String taxYearMonth = request.getParameter("taxYearMonth");
        if (StringUtils.isNotBlank(taxYearMonth)) {
            param.setTaxYearMonth(Arrays.asList(taxYearMonth.split(",")));
            param.setTaxYearMonthDate(Arrays.stream(taxYearMonth.split(",")).map(e -> e + "-01 00:00:00").map(SalaryDateUtil::dateStrToLocalTime).collect(Collectors.toList()));
        }

        String username = request.getParameter("username");
        if (StringUtils.isNotBlank(username)) {
            param.setUsername(username);
        }
        String employeeId = request.getParameter("employeeId");
        if (StringUtils.isNotBlank(employeeId)) {
            param.setEmployeeId(Long.valueOf(employeeId));
        }
        String taxAgentId = request.getParameter("taxAgentId");
        if (StringUtils.isNotBlank(taxAgentId)) {
            param.setTaxAgentId(Long.valueOf(taxAgentId));
        }
        String departmentIds = request.getParameter("departmentIds");
        if (StringUtils.isNotBlank(departmentIds)) {
            param.setDepartmentIds(Arrays.stream(departmentIds.split(",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        String jobNum = request.getParameter("jobNum");
        if (StringUtils.isNotBlank(jobNum)) {
            param.setJobNum(jobNum);
        }
        String idNo = request.getParameter("idNo");
        if (StringUtils.isNotBlank(idNo)) {
            param.setIdNo(idNo);
        }
        String hiredate = request.getParameter("hiredate");
        if (StringUtils.isNotBlank(hiredate)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            List<Date> dates = Arrays.stream(hiredate.split(",")).map(d -> {
                try {
                    return format.parse(d);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }).collect(Collectors.toList());
            param.setHiredate(dates);
        }
        String mobile = request.getParameter("mobile");
        if (StringUtils.isNotBlank(mobile)) {
            param.setMobile(mobile);
        }
        String accumulatedSituationId = request.getParameter("accumulatedSituationId");
        if (StringUtils.isNotBlank(accumulatedSituationId)) {
            param.setAccumulatedSituationId(Long.valueOf(accumulatedSituationId));
        }
        String hasData = request.getParameter("hasData");
        if (StringUtils.isNotBlank(hasData)) {
            param.setHasData("true".equals(hasData));
        }
        return param;
    }

    //导入
    @POST
    @Path("/importAddUpSituation")
    @Produces(MediaType.APPLICATION_JSON)
    public String importAddUpSituation(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationImportParam, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::importAddUpSituation, importParam);
    }

    /**
     * @description 编辑数据
     * @return String
     * @author Harryxzy
     * @date 2022/10/27 21:10
     */
    @POST
    @Path("/editAddUpSituation")
    @Produces(MediaType.APPLICATION_JSON)
    public String editAddUpSituation(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationParam addUpSituation) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationParam, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::editAddUpSituation, addUpSituation);
    }

    /**
     * @description 获取往期累计情况
     * @return String
     * @author Harryxzy
     * @date 2022/10/31 13:59
     */
    @POST
    @Path("/getAddUpSituation")
    @Produces(MediaType.APPLICATION_JSON)
    public String getAddUpSituation(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationParam addUpSituation) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationParam,AddUpSituationRecordDTO>(user).run(getAddUpSituationWrapper(user)::getAddUpSituation, addUpSituation);
    }

    /**
     * @description 新建数据
     * @return String
     * @author Harryxzy
     * @date 2022/10/27 21:10
     */
    @POST
    @Path("/createAddUpSituation")
    @Produces(MediaType.APPLICATION_JSON)
    public String createAddUpSituation(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationParam addUpSituation) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationParam, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::createAddUpSituation, addUpSituation);
    }

    /**
     * @description 删除所选数据
     * @return String
     * @author Harryxzy
     * @date 2022/10/27 21:10
     */
    @POST
    @Path("/deleteSelectAddUpSituation")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteSelectAddUpSituation(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationDeleteParam addUpSituationDeleteParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationDeleteParam, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::deleteSelectAddUpSituation, addUpSituationDeleteParam);
    }

    /**
     * @description 一键清空
     * @return String
     * @author Harryxzy
     * @date 2022/10/27 21:10
     */
    @POST
    @Path("/deleteAllAddUpSituation")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteAllAddUpSituation(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationDeleteParam addUpSituationDeleteParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpSituationDeleteParam, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::deleteAllAddUpSituation, addUpSituationDeleteParam);
    }

    @POST
    @Path("/preview")
    @Produces(MediaType.APPLICATION_JSON)
    public String preview(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpSituationImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> map = ParamUtil.request2Map(request);
        map.put("importParam", importParam);
        return new ResponseResult<AddUpSituationImportParam, Map<String, Object>>(user).run(getAddUpSituationWrapper(user)::preview, importParam);
    }


}
