package jnpf.workflow.controller;

import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.MsgCode;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.entity.workflow.PunishmentsApproval;
import jnpf.entity.workflow.RewardApproval;
import jnpf.exception.LoginException;
import jnpf.model.workflow.dto.PunishmentsApprovalDto;
import jnpf.model.workflow.dto.RewardApprovalDto;
import jnpf.model.workflow.vo.PunishmentsApprovalVo;
import jnpf.model.workflow.vo.RewardApprovalVo;
import jnpf.util.JsonUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import jnpf.workflow.service.PunishmentsApprovalService;
import jnpf.workflow.service.RewardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 此模块已废除，奖惩审批由OA提供
 * @Author huanglinpan
 * @Date 2024/5/21 17:22
 * @Version 1.0 （版本号）
 */
@Slf4j
@RestController
@RequestMapping(value = "/approve")
@Deprecated(since = "人事v1.2", forRemoval = true)
public class RewardsPunishmentsApproveController {


    @Resource
    private RewardService rewardService;

    @Resource
    private PunishmentsApprovalService punishmentsApprovalService;

    @Autowired
    private ConfigValueUtil configValueUtil;


    /**
     * 新建奖励申请
     * @param dto 表单对象
     * @return java.lang.Object
     */
    @PostMapping("/reward/{id}")
    public Object create(@RequestBody @Valid RewardApprovalDto dto, @PathVariable("id") String id) {
        RewardApproval entity = JsonUtil.getJsonToBean(dto, RewardApproval.class);
        if (FlowStatusEnum.save.getMessage().equals(dto.getStatus())) {
            rewardService.saveReward(id, entity, dto);
            return ActionResult.success(MsgCode.SU002.get());
        }
        rewardService.submitReward(id, entity, dto);
        return ActionResult.success(MsgCode.SU006.get());
    }




    /**
     * 查询奖励审批记录
     * @param id 审批id
     * @return jnpf.base.ActionResult<jnpf.model.workflow.vo.ApplyAttendanceChangeVo>
     */
    @GetMapping(value = "/reward/{id}")
    public ActionResult<RewardApprovalVo> getAttendanceLeave(@PathVariable(value = "id") String id) {

        RewardApprovalVo vo = rewardService.getReward(id);
        return ActionResult.success(vo);
    }


    /**
     * 修改奖励申请
     * @param dto 表单对象
     * @param id 主键
     * @return java.lang.Object
     */
    @PutMapping("/reward/{id}")
    public Object update(@RequestBody @Valid RewardApprovalDto dto, @PathVariable("id") String id) {

        RewardApproval entity = JsonUtil.getJsonToBean(dto, RewardApproval.class);
        entity.setId(id);
        if (FlowStatusEnum.save.getMessage().equals(dto.getStatus())) {
            rewardService.saveReward(id, entity, dto);
            return ActionResult.success(MsgCode.SU002.get());
        }
        rewardService.submitReward(id, entity, dto);
        return ActionResult.success(MsgCode.SU006.get());
    }

    /**
     * 奖励审批通过/拒绝/撤回
     * @param tenantId 租户Id
     * @param applyId 审批Id
     * @param status 是否审核通过 0.待审核  1.通过 2.未通过 3.撤回
     */
    @GetMapping("/reward/pass")
    @NoDataSourceBind
    public void rewardApprove(@RequestParam(value = "tenantId") Integer tenantId, @RequestParam(value = "applyId") String applyId, @RequestParam(value = "status") Integer status) {
        log.info("/reward/pass tenantId:{},applyId:{},status:{}",tenantId,applyId,status);
        checkOutTenant(tenantId);
        rewardService.rewardApprove(applyId, status);
    }


    /**
     * 新建奖励申请
     * @param dto 表单对象
     * @return java.lang.Object
     */
    @PostMapping("/punishments/{id}")
    public Object createPunishments(@RequestBody @Valid PunishmentsApprovalDto dto, @PathVariable("id") String id) {
        PunishmentsApproval entity = JsonUtil.getJsonToBean(dto, PunishmentsApproval.class);
        if (FlowStatusEnum.save.getMessage().equals(dto.getStatus())) {
            punishmentsApprovalService.savePunishments(id, entity, dto);
            return ActionResult.success(MsgCode.SU002.get());
        }
        punishmentsApprovalService.submitPunishments(id, entity, dto);
        return ActionResult.success(MsgCode.SU006.get());
    }




    /**
     * 查询奖励审批记录
     * @param id 审批id
     * @return jnpf.base.ActionResult<jnpf.model.workflow.vo.ApplyAttendanceChangeVo>
     */
    @GetMapping(value = "/punishments/{id}")
    public ActionResult<PunishmentsApprovalVo> getPunishments(@PathVariable(value = "id") String id) {

        PunishmentsApprovalVo vo = punishmentsApprovalService.getPunishments(id);
        return ActionResult.success(vo);
    }


    /**
     * 修改奖励申请
     * @param dto 表单对象
     * @param id 主键
     * @return java.lang.Object
     */
    @PutMapping("/punishments/{id}")
    public Object updatePunishments(@RequestBody @Valid PunishmentsApprovalDto dto, @PathVariable("id") String id) {

        PunishmentsApproval entity = JsonUtil.getJsonToBean(dto, PunishmentsApproval.class);
        entity.setId(id);
        if (FlowStatusEnum.save.getMessage().equals(dto.getStatus())) {
            punishmentsApprovalService.savePunishments(id, entity, dto);
            return ActionResult.success(MsgCode.SU002.get());
        }
        punishmentsApprovalService.submitPunishments(id, entity, dto);
        return ActionResult.success(MsgCode.SU006.get());
    }

    /**
     * 惩罚审批通过/拒绝/撤回
     * @param tenantId 租户Id
     * @param applyId 审批Id
     * @param status 是否审核通过 0.待审核  1.通过 2.未通过 3.撤回
     */
    @GetMapping("/punishments/pass")
    @NoDataSourceBind
    public void punishmentsApprove(@RequestParam(value = "tenantId") String tenantId,@RequestParam(value = "applyId") String applyId,@RequestParam(value = "status") Integer status)  {
        log.info("punishments/pass tenantId:{},applyId:{},status:{}",tenantId,applyId,status);
        checkOutTenant(tenantId);
        punishmentsApprovalService.punishmentsApprove(applyId, status);
    }

    public void checkOutTenant(String tenantId) {
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
    }
}
