package com.engine.salary.web;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.datacollection.dto.VariableItemListDTO;
import com.engine.salary.entity.datacollection.param.VariableArchiveImportHandleParam;
import com.engine.salary.entity.datacollection.param.VariableArchiveQueryParam;
import com.engine.salary.entity.datacollection.param.VariableArchiveSaveParam;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.excel.ExcelPreviewDTO;
import com.engine.salary.wrapper.VariableArchiveWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.time.LocalDate;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据采集-浮动薪酬
 * <p>Copyright: Copyright (c) 2024</p>
 * <p>Company: 泛微软件</p>
 *
 * @author xzy
 * @version 1.0
 **/
@Slf4j
public class VariableArchiveController {

    private VariableArchiveWrapper getVariableArchiveWrapper(User user) {
        return ServiceUtil.getService(VariableArchiveWrapper.class, user);
    }

    /**
     * 浮动薪酬列表
     *
     * @param request
     * @param response
     * @param queryParam
     * @return
     */
    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody VariableArchiveQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<VariableArchiveQueryParam, Map<String, Object>>(user).run(getVariableArchiveWrapper(user)::list, queryParam);
    }

    /**
     * 浮动薪酬明细
     *
     * @param request
     * @param response
     * @param queryParam
     * @return
     */
    @POST
    @Path("/getDetail")
    @Produces(MediaType.APPLICATION_JSON)
    public String getDetail(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody VariableArchiveQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<VariableArchiveQueryParam, Map<String, Object>>(user).run(getVariableArchiveWrapper(user)::getDetail, queryParam);
    }

    /**
     * 获取创建浮动薪酬档案时项目信息
     *
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/getCreateForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getCreateForm(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<VariableArchiveSaveParam, List<VariableItemListDTO>>(user).run(getVariableArchiveWrapper(user)::getCreateForm);
    }

    /**
     * 创建浮动薪酬档案
     *
     * @param request
     * @param response
     * @param saveParam
     * @return
     */
    @POST
    @Path("/createData")
    @Produces(MediaType.APPLICATION_JSON)
    public String createData(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody VariableArchiveSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        if (saveParam.getId() == null) {
            return new ResponseResult<VariableArchiveSaveParam, String>(user).run(getVariableArchiveWrapper(user)::createData, saveParam);
        } else {
            // 更新
            return new ResponseResult<VariableArchiveSaveParam, String>(user).run(getVariableArchiveWrapper(user)::updateData, saveParam);
        }
    }


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

            XSSFWorkbook workbook = getVariableArchiveWrapper(user).downloadTemplate(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;
        }
    }


    /**
     * 导出
     *
     * @param
     * @return
     */
    @POST
    @Path("/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response,  @RequestBody VariableArchiveQueryParam param) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            // VariableArchiveQueryParam param = buildParam(request);
            // String columns = request.getParameter("columns");
            // if (StringUtils.isNotBlank(columns)) {
            //     param.setColumns(Arrays.stream(columns.split(",")).collect(Collectors.toList()));
            // }

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

            String fileName = null;
            try {
                fileName = URLEncoder.encode("浮动薪酬" + LocalDate.now() + ".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;
        }
    }



    private VariableArchiveQueryParam buildParam(HttpServletRequest request) {
        VariableArchiveQueryParam param = new VariableArchiveQueryParam();

        String salaryMonthStr = request.getParameter("salaryMonth");
        if (StringUtils.isNotBlank(salaryMonthStr)) {
            param.setSalaryMonth(salaryMonthStr);
            param.setSalaryMonthDate(SalaryDateUtil.dateStrToLocalYearMonth(salaryMonthStr));
        }
        String username = request.getParameter("username");
        if (StringUtils.isNotBlank(username)) {
            param.setUsername(username);
        }

        String departmentIdStr = request.getParameter("departmentIds");
        if (StringUtils.isNotBlank(departmentIdStr)) {
            List<Long> departmentIds = Arrays.stream(departmentIdStr.split(",")).filter(NumberUtils::isCreatable).map(Long::valueOf).collect(Collectors.toList());
            param.setDepartmentIds(departmentIds);
        }
        String workcode = request.getParameter("workcode");
        if (StringUtils.isNotBlank(workcode)) {
            param.setWorkcode(workcode);
        }

        String hasData = request.getParameter("hasData");
        if (StringUtils.isNotBlank(hasData)) {
            param.setHasData(hasData.equals("true"));
        }

        return param;
    }

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

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


    /**
     * @description 删除
     * @return String
     * @author Harryxzy
     * @date 2024/08/08 14:41
     */
    @POST
    @Path("/deleteSelectData")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteSelectVariableArchive(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody VariableArchiveQueryParam variableArchiveQueryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Collection<Long>, String>(user).run(getVariableArchiveWrapper(user)::deleteSelectVariableArchive, variableArchiveQueryParam.getIds());
    }

}
