package com.engine.salary.web;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.taxagent.dto.TaxAgentFormDTO;
import com.engine.salary.entity.taxagent.dto.TaxAgentManageRangeEmployeeDTO;
import com.engine.salary.entity.taxagent.dto.TaxAgentManageRangeFormDTO;
import com.engine.salary.entity.taxagent.dto.TaxAgentManageRangeListDTO;
import com.engine.salary.entity.taxagent.param.*;
import com.engine.salary.entity.taxagent.po.TaxAgentBasePO;
import com.engine.salary.entity.taxagent.po.TaxAgentExtRangePO;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.wrapper.TaxAgentBaseWrapper;
import com.engine.salary.wrapper.TaxAgentSubAdminWrapper;
import com.engine.salary.wrapper.TaxAgentWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.apache.commons.lang3.StringUtils;
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.*;
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.*;

public class TaxAgentController {

    private TaxAgentBaseWrapper getTaxAgentBaseWrapper(User user) {
        return ServiceUtil.getService(TaxAgentBaseWrapper.class, user);
    }

    private TaxAgentSubAdminWrapper getTaxAgentSubAdminWrapper(User user) {
        return ServiceUtil.getService(TaxAgentSubAdminWrapper.class, user);
    }

    private TaxAgentWrapper getTaxAgentWrapper(User user) {
        return ServiceUtil.getService(TaxAgentWrapper.class, user);
    }

    /**
     * 是否是薪酬模块总管理员
     */
    @GET
    @Path("/isChief")
    @Produces(MediaType.APPLICATION_JSON)
    public String isChief(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, Boolean>(user).run(getTaxAgentWrapper(user)::isChief, (long) user.getUID());
    }

    /**
     * 权限信息
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/permission")
    @Produces(MediaType.APPLICATION_JSON)
    public String permission(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, Map<String, Boolean>>(user).run(getTaxAgentWrapper(user)::permission, (long) user.getUID());
    }

    /* ****** 基础信息 start ***********************************************************************************************/

    /**
     * 获取个税扣缴义务人基础信息表单
     *
     * @return
     */
    @GET
    @Path("/base/getForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getBaseFrom(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, TaxAgentBasePO>(user).run(getTaxAgentBaseWrapper(user)::getFrom);
    }

    /**
     * 保存个税扣缴义务人基础信息
     *
     * @param saveBaseParam
     * @return
     */
    @POST
    @Path("/base/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveBase(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSaveBaseParam saveBaseParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentSaveBaseParam, String>(user).run(getTaxAgentBaseWrapper(user)::save, saveBaseParam);
    }
    /* ******* 基础信息 end ***********************************************************************************************/

    /* ******* 个税扣缴义务人 start ***********************************************************************************************/

    /**
     * 个税扣缴义务人列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentQueryParam, PageInfo<Map<String, Object>>>(user).run(getTaxAgentWrapper(user)::list, queryParam);
    }

    //查询个税扣缴义务人下面的代缴机构")
    @GET
    @Path("/paymentAgency/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String paymentAgencyList(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        TaxAgentQueryParam queryParam = new TaxAgentQueryParam();
        queryParam.setIds(Collections.singleton(id));
        return new ResponseResult<TaxAgentQueryParam, List<Map<String, Object>>>(user).run(getTaxAgentWrapper(user)::paymentAgencyList, queryParam);
    }

    //保存个税扣缴义务人下的代缴机构")
    @POST
    @Path("/paymentAgency/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String paymentAgencySave(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentSaveParam, String>(user).run(getTaxAgentWrapper(user)::paymentAgencySave, saveParam);
    }


    /**
     * 获取个税扣缴义务人表单
     *
     * @param id 表单id
     * @return 表单对象
     */
    @GET
    @Path("/getForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getFrom(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, TaxAgentFormDTO>(user).run(getTaxAgentWrapper(user)::getFrom, id);
    }

    /**
     * 新建个税扣缴义务人
     *
     * @param saveParam 个税扣缴义务人保存参数
     * @return 个税扣缴义务人id
     */
    @POST
    @Path("/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String save(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentSaveParam, String>(user).run(getTaxAgentWrapper(user)::save, saveParam);
    }

    /**
     * 编辑个税扣缴义务人
     *
     * @param saveParam
     * @return
     */
    @POST
    @Path("/update")
    @Produces(MediaType.APPLICATION_JSON)
    public String update(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentSaveParam, String>(user).run(getTaxAgentWrapper(user)::update, saveParam);
    }

    /**
     * 更换管理员校验
     *
     * @param checkParam
     * @return
     */
    @POST
    @Path("/adminChangeCheck")
    @Produces(MediaType.APPLICATION_JSON)
    public String adminChangeCheck(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentAdminChangeCheckParam checkParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentAdminChangeCheckParam, Boolean>(user).run(getTaxAgentWrapper(user)::adminChangeCheck, checkParam);
    }

    /**
     * 删除个税扣缴义务人
     *
     * @param ids
     * @return
     */
    @POST
    @Path("/delete")
    @Produces(MediaType.APPLICATION_JSON)
    public String delete(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody List<Long> ids) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<List<Long>, String>(user).run(getTaxAgentWrapper(user)::delete, ids);
    }

    /**
     * 人员范围列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/range/listInclude")
    @Produces(MediaType.APPLICATION_JSON)
    public String rangeListInclude(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentRangeQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentRangeQueryParam, PageInfo<TaxAgentManageRangeListDTO>>(user).run(getTaxAgentWrapper(user)::listRangeInclude, queryParam);
    }

    /**
     * 人员范围排除列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/range/listExclude")
    @Produces(MediaType.APPLICATION_JSON)
    public String rangeListExclude(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentRangeQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentRangeQueryParam, PageInfo<TaxAgentManageRangeListDTO>>(user).run(getTaxAgentWrapper(user)::listRangeExclude, queryParam);
    }

    //获取人员范围表单")
    @POST
    @Path("/range/getForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getRangeFrom(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<String, TaxAgentManageRangeFormDTO>(user).run(getTaxAgentWrapper(user)::getRangeFrom);
    }

    //保存人员范围
    @POST
    @Path("/range/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentRangeSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentRangeSaveParam, String>(user).run(getTaxAgentWrapper(user)::saveRange, saveParam);
    }



    //删除人员范围
    @POST
    @Path("/range/delete")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Collection<Long>, String>(user).run(getTaxAgentWrapper(user)::deleteRange, ids);
    }

    //外部人员
    @POST
    @Path("/range/listExt")
    @Produces(MediaType.APPLICATION_JSON)
    public String listExt(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentRangeExtQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentRangeExtQueryParam, PageInfo<TaxAgentExtRangePO>>(user).run(getTaxAgentWrapper(user)::listExt, queryParam);
    }


    @POST
    @Path("/range/ext/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveExtRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentManageRangeExtSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentManageRangeExtSaveParam, String>(user).run(getTaxAgentWrapper(user)::saveExtRange, saveParam);
    }

    //删除外部人员范围
    @POST
    @Path("/range/ext/delete")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteExtRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Collection<Long>, String>(user).run(getTaxAgentWrapper(user)::deleteExtRange, ids);
    }

    /**
     * 下载人员范围导入模板
     *
     * @return
     */
    @GET
    @Path("/range/downloadTemplate")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response downloadTemplateRange(@Context HttpServletRequest request, @Context HttpServletResponse response ,@QueryParam(value = "taxAgentId") Long taxAgentId) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            TaxAgentPO taxAgent = taxAgentId == null ? null : getTaxAgentWrapper(user).getTaxAgentService(user).getById(taxAgentId);
            TaxAgentRangeDownloadTemplateParam build = TaxAgentRangeDownloadTemplateParam.builder().taxAgentId(taxAgentId).build();
            XSSFWorkbook workbook = getTaxAgentWrapper(user).exportImportTemplate(build);
            String time = LocalDate.now().toString();
            String fileName = Objects.isNull(taxAgent) ? "人员范围导入模板" + time : taxAgent.getName() + "人员范围导入模板" + 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();
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 预览人员范围导入模板
     *
     * @return
     */
    @POST
    @Path("/range/preview")
    @Produces(MediaType.APPLICATION_JSON)
    public String preview(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentImportParam, Map<String, Object>>(user).run(getTaxAgentWrapper(user)::preview, importParam);
    }

    /**
     * 个税扣缴义务人人员范围导入
     *
     * @return
     */
    @POST
    @Path("/range/importData")
    @Produces(MediaType.APPLICATION_JSON)
    public String importEmployeeRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<TaxAgentImportParam, Map<String, Object>>(user).run(getTaxAgentWrapper(user)::importData, importParam);
    }

    /**
     * 个税扣缴义务人下拉列表
     *
     * @return
     */
    @GET
    @Path("/selectList")
    @Produces(MediaType.APPLICATION_JSON)
    public String selectList(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        boolean needAuth = !StringUtils.equals("true", request.getParameter("isShare"));
        return new ResponseResult<Boolean, List<Map<String, Object>>>(user).run(getTaxAgentWrapper(user)::selectList, needAuth);
    }

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


    @GET
    @Path("/getEmpListInTaxAgent")
    @Produces(MediaType.APPLICATION_JSON)
    public String getEmpListInTaxAgent(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, List<TaxAgentManageRangeEmployeeDTO>>(user).run(getTaxAgentWrapper(user)::getEmpListInTaxAgent, id);
    }


    //同步人员范围
    @POST
    @Path("/range/sync")
    @Produces(MediaType.APPLICATION_JSON)
    public String syncRange(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, String>(user).run(getTaxAgentWrapper(user)::syncRange);
    }

    /* ******* 个税扣缴义务人 end ***********************************************************************************************/

    /* ******* 分管理员 start ***********************************************************************************************/

    /**
     * 分管理员列表
     *
     * @param queryParam
     * @return
     */
//    @POST
//    @Path("/subAdmin/list")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String subAdminList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSubAdminQueryParam queryParam) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminQueryParam, PageInfo<TaxAgentSubAdminListDTO>>(user).run(getTaxAgentSubAdminWrapper(user)::list, queryParam);
//    }

    /**
     * 获取分管理员基础设置表单
     *
     * @return
     */
//    @POST
//    @Path("/subAdmin/getBaseForm")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String getSubAdminBaseFrom(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSubAdminBaseFormParam baseFormParam) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminBaseFormParam, TaxAgentSubAdminBaseFormDTO>(user).run(getTaxAgentSubAdminWrapper(user)::getBaseFrom, baseFormParam);
//    }

    /**
     * 分管理员基础设置保存
     *
     * @param saveParam
     * @return
     */
//    @POST
//    @Path("/subAdmin/saveBase")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String saveSubAdminBase(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSubAdminBaseSaveParam saveParam) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminBaseSaveParam, String>(user).run(getTaxAgentSubAdminWrapper(user)::saveBase, saveParam);
//    }

    /**
     * 删除个税扣缴义务人分管理员
     *
     * @param ids
     * @return
     */
//    @POST
//    @Path("/subAdmin/delete")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String deleteSubAdmin(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<Collection<Long>, String>(user).run(getTaxAgentSubAdminWrapper(user)::delete, ids);
//    }

    //分管理员的管理范围列表
//    @POST
//    @Path("/subAdmin/range/listInclude")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String subAdminRangeListInclude(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSubAdminRangeQueryParam queryParam) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminRangeQueryParam, PageInfo<TaxAgentManageRangeListDTO>>(user).run(getTaxAgentSubAdminWrapper(user)::listRangeInclude, queryParam);
//    }

    //分管理员的管理范围排除列表
//    @POST
//    @Path("/subAdmin/range/listExclude")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String subAdminRangeListExclude(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSubAdminRangeQueryParam queryParam) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminRangeQueryParam, PageInfo<TaxAgentManageRangeListDTO>>(user).run(getTaxAgentSubAdminWrapper(user)::listRangeExclude, queryParam);
//    }

    //获取分管理员的管理范围表单
//    @POST
//    @Path("/subAdmin/range/getForm")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String getSubAdminRangeFrom(@Context HttpServletRequest request, @Context HttpServletResponse response) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminRangeQueryParam, TaxAgentManageRangeFormDTO>(user).run(getTaxAgentSubAdminWrapper(user)::getRangeFrom);
//    }

    //保存分管理员的管理范围
//    @POST
//    @Path("/subAdmin/range/save")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String saveSubAdminRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody TaxAgentSubAdminRangeSaveParam saveParam) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<TaxAgentSubAdminRangeSaveParam, TaxAgentManageRangeFormDTO>(user).run(getTaxAgentSubAdminWrapper(user)::saveRange, saveParam);
//    }

    //删除分管理员的管理范围
//    @POST
//    @Path("/subAdmin/range/delete")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String deleteSubAdminRange(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
//        User user = HrmUserVarify.getUser(request, response);
//        return new ResponseResult<Collection<Long>, String>(user).run(getTaxAgentSubAdminWrapper(user)::deleteRange, ids);
//    }

    /******** 分管理员 end ***********************************************************************************************/


}
