package com.engine.salary.web;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.datacollection.dto.AddUpDeductionDTO;
import com.engine.salary.entity.datacollection.dto.AddUpDeductionRecordDTO;
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.AddUpDeductionWrapper;
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 AddUpDeductionController {

    private AddUpDeductionWrapper getAddUpDeductionWrapper(User user) {
        return ServiceUtil.getService(AddUpDeductionWrapper.class, user);
    }

    /**
     * 数据采集-累计专项附加扣除列表的高级搜索
     *
     * @return
     */
    @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(getAddUpDeductionWrapper(user)::getSearchCondition, ParamUtil.request2Map(request));
    }


    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpDeductionQueryParam, PageInfo<AddUpDeductionDTO>>(user).run(getAddUpDeductionWrapper(user)::list, 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);
            AddUpDeductionQueryParam queryParam = buildParam(request);
            XSSFWorkbook workbook = getAddUpDeductionWrapper(user).downloadTemplate(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("/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            AddUpDeductionQueryParam param = buildParam(request);

            XSSFWorkbook workbook = getAddUpDeductionWrapper(user).export(param);

            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;
        }

    }


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

            AddUpDeductionQueryParam param = buildParam(request);

            XSSFWorkbook workbook = getAddUpDeductionWrapper(user).exportDetail(param);

            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 AddUpDeductionQueryParam buildParam(HttpServletRequest request) {
        AddUpDeductionQueryParam param = new AddUpDeductionQueryParam();
        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 declareMonth = request.getParameter("declareMonth");
        if (StringUtils.isNotBlank(declareMonth)) {
            param.setDeclareMonth(Arrays.stream(declareMonth.split(",")).map(e -> e + "-01 00:00:00").collect(Collectors.toList()));
            param.setDeclareMonthDate(Arrays.stream(declareMonth.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 accumulatedSpecialAdditionalDeductionId = request.getParameter("accumulatedSpecialAdditionalDeductionId");
        if (StringUtils.isNotBlank(accumulatedSpecialAdditionalDeductionId)) {
            param.setAccumulatedSpecialAdditionalDeductionId(Long.valueOf(accumulatedSpecialAdditionalDeductionId));
        }
        String hasData = request.getParameter("hasData");
        if (StringUtils.isNotBlank(hasData)) {
            param.setHasData("true".equals(hasData));
        }
        return param;
    }

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

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

    /**
     * @description 新建累计专项附加扣除
     * @return String
     * @author Harryxzy
     * @date 2022/10/26 14:23
     */
    @POST
    @Path("/createAddUpDeduction")
    @Produces(MediaType.APPLICATION_JSON)
    public String createAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionRecordParam addUpDeduction) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpDeductionRecordParam, Map<String, Object>>(user).run(getAddUpDeductionWrapper(user)::createAddUpDeduction, addUpDeduction);
    }

    /**
     * @description 获取累计专项附加扣除信息
     * @return String
     * @author Harryxzy
     * @date 2022/10/31 11:23
     */
    @POST
    @Path("/getAddUpDeduction")
    @Produces(MediaType.APPLICATION_JSON)
    public String getAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionQueryParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpDeductionQueryParam, AddUpDeductionRecordDTO>(user).run(getAddUpDeductionWrapper(user)::getAddUpDeduction, param);
    }


    /**
     * @description 编辑累计专项附加扣除
     * @return String
     * @author Harryxzy
     * @date 2022/10/25 14:08
     */
    @POST
    @Path("/editAddUpDeduction")
    @Produces(MediaType.APPLICATION_JSON)
    public String editAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionRecordParam addUpDeduction) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpDeductionRecordParam, Map<String, Object>>(user).run(getAddUpDeductionWrapper(user)::editAddUpDeduction, addUpDeduction);
    }

    /**
     * @description 累计专项附加扣除-删除所选
     * @return String
     * @author Harryxzy
     * @date 2022/10/27 14:08
     */
    @POST
    @Path("/deleteSelectAddUpDeduction")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteSelectAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionRecordDeleteParam deleteParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpDeductionRecordDeleteParam, Map<String, Object>>(user).run(getAddUpDeductionWrapper(user)::deleteSelectAddUpDeduction, deleteParam);
    }

    /**
     * @description 累计专项附加扣除-一键清空
     * @return String
     * @author Harryxzy
     * @date 2022/10/27 14:08
     */
    @POST
    @Path("/deleteAllAddUpDeduction")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteAllAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionRecordDeleteParam deleteParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddUpDeductionRecordDeleteParam, Map<String, Object>>(user).run(getAddUpDeductionWrapper(user)::deleteAllAddUpDeduction, deleteParam);
    }


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


    /**
     * 一键自动累计
     * @return
     */
    @POST
    @Path("/autoAddAll")
    @Produces(MediaType.APPLICATION_JSON)
    public String autoAddAll(@Context HttpServletRequest request, @Context HttpServletResponse response,
                             @RequestBody AddDeductionAutoAddParam param) {
        DateTime date = null;
        if (StrUtil.isNotEmpty(param.getYearMonth())) {
            try {
                date = DateUtil.parse(param.getYearMonth(), "yyyy-MM");
            } catch (Exception e) {
                //ignore
                // 放在service中处理，这里处理了页面上收不到
            }
        } else {
            date = DateUtil.beginOfMonth(new Date());
        }
        param.setYearMonthDate(date);
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<AddDeductionAutoAddParam, String>(user).run(getAddUpDeductionWrapper(user)::autoAddAll, param);
    }
}
