package jnpf.personnels.controller.web.turnover;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.enums.FtbPersonnelsAuditTaskEnum;
import jnpf.model.personnels.dto.base.FtbPersonnelsBaseForOA;
import jnpf.model.personnels.dto.base.PersonnelsQueryDTO;
import jnpf.model.personnels.dto.turnover.FtbDepUserDTO;
import jnpf.model.personnels.dto.turnover.FtbPersonnelsTurnoverCreateDTO;
import jnpf.model.personnels.dto.turnover.FtbPersonnelsTurnoverDTO;
import jnpf.model.personnels.po.FtbPersonnelsTurnoverManagement;
import jnpf.model.personnels.vo.turnover.FtbPersonnelsTurOrgInfo;
import jnpf.model.personnels.vo.turnover.FtbPersonnelsTurnoverInfoVO;
import jnpf.model.personnels.vo.turnover.FtbPersonnelsTurnoverManagementVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.FtbPersonnelsTurnoverManagementApi;
import jnpf.personnels.service.FtbPersonnelsRegularManagementService;
import jnpf.personnels.service.FtbPersonnelsSecondmentManagementService;
import jnpf.personnels.service.FtbPersonnelsTransferManageService;
import jnpf.personnels.service.FtbPersonnelsTurnoverManagementService;
import jnpf.util.NoDataSourceBind;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * web离职管理模块
 *
 * @author peng.hao
 */
@RestController
@RequestMapping("/web/personnels-turnover")
@Slf4j
public class FtbPersonnelsTurnoverManagementController implements FtbPersonnelsTurnoverManagementApi {

    @Resource
    FtbPersonnelsTurnoverManagementService service;

    @Resource
    private FtbPersonnelsTransferManageService ftbPersonnelsTransferManageService;

    @Resource
    private FtbPersonnelsRegularManagementService ftbPersonnelsRegularManagementService;

    @Resource
    FtbPersonnelsSecondmentManagementService ftbPersonnelsSecondmentManagementService;

    /**
     * 离职管理列表
     *
     * @param dto 人事变动查询参数
     * @return 查询结果
     */
    @PostMapping("/list-query")
    public ActionResult<PageListVO<FtbPersonnelsTurnoverManagementVO>> getTurnoverList(@RequestBody PersonnelsQueryDTO dto){
        CultivatePage page = new CultivatePage();
        page.setCurrentPage(dto.getCurrentPage());
        page.setPageSize(dto.getPageSize());
        PageListVO<FtbPersonnelsTurnoverManagementVO> listVO = service.getTurnoverList(dto,page);
        return ActionResult.success(listVO);
    }

    /**
     * 离职列表导出
     *
     * @param dto 人事变动查询参数
     * @return 查询结果
     */
    @PostMapping("/list-query-export")
    public void getTurnoverListExport( @RequestBody PersonnelsQueryDTO dto, HttpServletResponse response) throws IOException {
      service.getTurnoverListExport(dto,response);
    }

    /**
     * 获取辞职审批流程详情
     *
     * @param id 流程id
     * @return 返回辞职审批流程详情结果
     */
    @GetMapping("/details-process/{id}")
    public ActionResult<FtbPersonnelsTurnoverInfoVO> detailsOfResignationApprovalProcess(@PathVariable("id")String id){
        FtbPersonnelsTurnoverInfoVO info =  service.detailsOfResignationApprovalProcess(id);
        return ActionResult.success(info);
    }

    /**
     * 获取辞职审批流程详情
     *
     * @param id 流程id
     * @return 返回辞职审批流程详情结果
     */
    @GetMapping("/details-process")
    public ActionResult<FtbPersonnelsTurnoverInfoVO> detailsOfResignationApprovalProcessWithId(@RequestParam("id")String id){
        FtbPersonnelsTurnoverInfoVO info =  service.detailsOfResignationApprovalProcess(id);
        return ActionResult.success(info);
    }
    /**
     * 获取辞职审批流程详情(for oa)
     *
     * @param id 流程id
     * @return 返回辞职审批流程详情结果
     */
    @GetMapping("/details-process-with-taskInfoId")
    public ActionResult<FtbPersonnelsTurnoverInfoVO> detailsOfResignationApprovalProcessWithTaskInfoId(@RequestParam("id")String id){
        FtbPersonnelsTurnoverManagement one = service.lambdaQuery().eq(FtbPersonnelsTurnoverManagement::getTaskInfoId, id).one();
        if (ObjectUtil.isEmpty(one)){
            return ActionResult.fail("暂无用户离职详情!");
        }
        FtbPersonnelsTurnoverInfoVO info =  service.detailsOfResignationApprovalProcess(one.getId());
        return ActionResult.success(info);
    }


    /**
     * 申请辞职 (包含重新办理)
     *
     * @param createDTO 创建DTO对象
     * @return   "1" 为是否为审批人 2 是否为门店负责人 3是否存在角色组 "4" 是否有直系下属 6签了电子合同 7签的纸制合同
     */
    @PostMapping("/saveOrUpdate-apply-resignation")
    public ActionResult<String> applyForResignation(@Validated  @RequestBody FtbPersonnelsTurnoverCreateDTO createDTO){
        return ActionResult.success("" , service.applyForResignation(createDTO));

    }

    /**
     * 申请辞职 (oa提交)
     *
     * @param createDTO 创建DTO对象
     * @return
     */
    @PostMapping("/saveOrUpdate-apply-resignation-for-oa")
    public ActionResult<Void> applyForResignatioForOA(@Validated  @RequestBody FtbPersonnelsTurnoverCreateDTO createDTO){
        ActionResult<Void> map = service.applyForResignatioForOA(createDTO);
        return map;

    }

    /**
     * 获取用户绑定审批结果
     * @param flag 用户离职申请信息
     * @return 动态数据
     */
    @GetMapping("/get-user-bound-approval")
    @Deprecated(since = "已弃用")
    public ActionResult<List<Map<String,Object>>> getUserBoundApproval(@RequestParam("flag") String flag,
                                                                       @RequestParam("userId") String userId){
        return ActionResult.success(service.getUserBoundApproval(flag,userId));
    }

    /**
     * 删除辞职申请
     *
     * @param ids 应用程序的ID
     * @return 返回String类型的ActionResult对象
     */
    @DeleteMapping("/delete-application")
    public ActionResult<String> deleteResignationApplication(@RequestBody List<String> ids){
        service.deleteResignationApplicationWithId(ids);
        return ActionResult.success();
    }

    /**
     * 撤销辞职申请(oa)
     *
     * @param id 应用程序的ID
     * @return 返回String类型的ActionResult对象
     */
    @GetMapping("/withdraw-application")
    public ActionResult<String> withdrawResignationApplication( String id,String taskId){
        service.withdrawResignationApplication(id,taskId);
        return ActionResult.success();
    }
    /**
     * 审核离职申请
     *
     * @param auditDto 审核DTO对象
     * @return   "1" 为是否为审批人 2 是否为门店负责人 3是否存在角色组
     */
    @PutMapping("/review-resignation-application")
    @Deprecated(since = "已弃用")
    public ActionResult<String> reviewResignationApplication(@RequestBody FtbPersonnelsTurnoverDTO auditDto ){
        String string = service.reviewResignationApplication(auditDto);
        return ActionResult.success(string);
    }

    /**
     * 审核离职申请(for oa)
     *
     * @param auditDto 审核DTO对象
     * @return
     */
    @PostMapping("/review-resignation-application-oa")
    public ActionResult<Void> reviewResignationApplicationWithOA(@RequestBody FtbPersonnelsTurnoverDTO auditDto ){
        ActionResult<Void> map = service.reviewResignationApplicationWithOA(auditDto);
        return map;
    }

    /**
     * 审核离职申请前置校验
     *
     * @return 返回Map类型的ActionResult对象 message : "" , code: 1001 1002 1003
     */
    @GetMapping("/resignation-pre-check")
    public ActionResult<Void> resignationPreCheck(FtbPersonnelsBaseForOA dto){
        ActionResult<Void> map = service.resignationPreCheck(dto.getUserIds().get(0),dto.getTaskFlag());
        return map;
    }

    @GetMapping("/closeUserAccountRegularlyAfterResignation")
    @Override
    public ActionResult<String> closeUserAccountRegularlyAfterResignation(@RequestParam("tenantId") String tenantId){
        try {
            service.closeUserAccountRegularlyAfterResignation(tenantId);
        }catch (Exception e) {
            log.error("关闭用户账户定时任务失败",e);
        }
        try {
            // 同步转正状态
            ftbPersonnelsRegularManagementService.syncRegularStatus(tenantId);
        }catch (Exception e){
            log.error("同步转正状态失败",e);
        }
        try {
            // 调动生效定时任务
            ftbPersonnelsTransferManageService.transferEffectScheduledTask(tenantId);
        }catch (Exception e){
            log.error("调动生效定时任务失败",e);
        }
        try {
            // 定时任务检测当借调结束后薪资生成 借调返岗
            ftbPersonnelsSecondmentManagementService.checkSecondmentEnd(tenantId);
        }catch (Exception e){
            log.error("定时任务检测当借调结束后薪资生成 借调返岗失败",e);
        }

        return ActionResult.success();
    }

    /**
     * 离职用户已签署离职协议
     * @param userId 用户id
     * @return
     */
    @GetMapping("/user-has-sign-an-agreement")
    @Override
    public Boolean userHasSignedASeparationAgreement(@RequestParam("userId") String userId,@RequestParam("flag") Integer flag) {
        return service.userHasSignedASeparationAgreement(userId, flag);
    }

    @Override
    public List<FtbPersonnelsTurnoverManagementVO> queryTurnoverList() {
        return service.queryTurnoverList();
    }

    /**
     * 查询当前数据是否存在离职审批
     * @param id 主键id
     * @return
     */
    @GetMapping("/query-user-have-turnover")
    public ActionResult<Boolean> queryWhetherTheUserHasTheResignationProcess(@RequestParam("id") String id){
        LambdaQueryWrapper<FtbPersonnelsTurnoverManagement> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbPersonnelsTurnoverManagement::getId,id);
        lambdaQuery.eq(FtbPersonnelsTurnoverManagement::getEnableMark,0);
       List<Integer> list = new ArrayList<>();
        list.add(FtbPersonnelsAuditTaskEnum.UNDER_REVIEW.getCode());
        list.add(FtbPersonnelsAuditTaskEnum.EXAMINATION_PASSED.getCode());
        list.add(FtbPersonnelsAuditTaskEnum.AUDIT_NOT_PASSED.getCode());
        list.add(FtbPersonnelsAuditTaskEnum.CANCEL.getCode());
        lambdaQuery.in(FtbPersonnelsTurnoverManagement::getTurnoverStatus,list);
        long count = service.count(lambdaQuery);
        Boolean flag = false;
        if (count > 0){
            flag = true;
        }
        return ActionResult.success(flag);
    }

    /**
     * 根据userId获取当前人员离职是的组织信息
     */
    @GetMapping("/get-user-organize-info")
    public ActionResult<FtbPersonnelsTurOrgInfo> getUserOrganizeInfo(@RequestParam(name = "userId",required = false) String userId,
                                                                     @RequestParam(name = "phone",required = false) String phone){
        return ActionResult.success(service.getUserOrganizeInfo(userId,phone));
    }

    /**
     * 获取离职人员信息
     * 1.按多个userId
     * 2.按多个组织id
     * 3.按多个岗位id
     */
    @PostMapping("/get-dep-user")
    public List<UserBoundVO> getInformationAboutTheDepartingPerson(@RequestBody FtbDepUserDTO dto){
        return service.getInformationAboutTheDepartingPerson(dto);
    }

    @PostMapping("/not-token-get-dep-user")
    @NoDataSourceBind
    public List<UserBoundVO> getInformationAboutTheDepartingPersonNotToken(@RequestBody FtbDepUserDTO dto){
        if(StringUtil.isNotEmpty(dto.getTenantId())){
            try {
                TenantDataSourceUtil.switchTenant(dto.getTenantId());
            } catch (LoginException e) {
                throw new RuntimeException(e);
            }
        }
        return service.getInformationAboutTheDepartingPerson(dto);
    }
}
