package jnpf.personnels.controller.app.employmentapply;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.model.personnels.dto.staff.employment.FtbPersonnelsStaffEmploymentApplyDto;
import jnpf.model.personnels.req.employment.AddStaffEmploymentApplyReq;
import jnpf.model.personnels.req.employment.AddStaffEmploymentApplyResultDto;
import jnpf.model.personnels.req.employment.EmploymentApplyCheckDto;
import jnpf.model.personnels.req.employment.QueryAppStaffEmploymentApplyListReq;
import jnpf.model.personnels.req.roster.CheckOrgAndPosAndRankExistVo;
import jnpf.model.personnels.req.roster.ConfirmOnDutyReq;
import jnpf.model.personnels.vo.app.FtbPersonnelsBubbleCountVO;
import jnpf.model.personnels.vo.employment.CheckPhoneStatusVo;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.PositionEntity;
import jnpf.permission.model.position.PositionGradesInfoVO;
import jnpf.personnels.service.FtbPersonnelsStaffEmploymentApplyService;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.personnels.utils.PersonnelOrgUtils;
import jnpf.util.FtbUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * app员工入职表模块
 *
 * @author xxxxx
 */
@Slf4j
@RestController
@RequestMapping("/app/personnels-staff-employment-apply")
@Deprecated(since = "人事v2.0")
public class FtbPersonnelsStaffEmploymentApplyAppController {


    @Autowired
    private FtbPersonnelsStaffEmploymentApplyService staffEmploymentApplyService;


    @Autowired
    private FtbPersonnelsStaffRosterService staffRosterService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PersonnelOrgUtils personnelOrgUtils;


    /**
     * 查询预入职
     *
     * @param req
     * @return {@link ActionResult}<{@link FtbPersonnelsStaffEmploymentApplyDto}>
     */
    @GetMapping("/query-list")
    public ActionResult<PageListVO<FtbPersonnelsStaffEmploymentApplyDto>> pageLists(@Validated QueryAppStaffEmploymentApplyListReq req) {
        String loginUserId = UserProvider.getLoginUserId();
        PageInfo<FtbPersonnelsStaffEmploymentApplyDto> pageVo = staffEmploymentApplyService.getAppPageList(req, loginUserId);
        return ActionResult.page(pageVo.getList(), FtbUtil.getPagination(pageVo));
    }


    /**
     * 我的审批,抄送,小气泡统计数
     * @param flag "1" 我的审批 "2" 抄送
     */
    @GetMapping("/getListCont")
    public ActionResult<FtbPersonnelsBubbleCountVO> getListCont(@RequestParam String flag) {
        FtbPersonnelsBubbleCountVO  countVO = staffEmploymentApplyService.getListCont(flag);
        return ActionResult.success(countVO);
    }


    /**
     * 检测校验组织/岗位/职级是否存在
     *
     * @param vo
     * @return
     * * 0：成功
     * * 1：失败：组织被删除
     * * 2：失败：岗位被删除
     * * 3：失败：职等被删除
     */
    @GetMapping("/checkOrgPositionRankExist")
    public ActionResult<Integer> checkOrgPositionRankExist(CheckOrgAndPosAndRankExistVo vo) {
        ConfirmOnDutyReq confirmOnDutyReq = BeanUtil.copyProperties(vo, ConfirmOnDutyReq.class);
        Integer checkStatus = checkOrgPositionRank(confirmOnDutyReq);
        return ActionResult.success(checkStatus);
    }

    /**
     * 确认到岗
     *
     * @param req 入职参数
     * @return {@link ActionResult}<{@link String}>
     */
    @PostMapping("/confirm-on-duty")
    public ActionResult<AddStaffEmploymentApplyResultDto> confirmOnDuty(@Validated @RequestBody ConfirmOnDutyReq req) {
        String lockKey = "ConfirmOnDuty:" + req.getPhone();
        Integer checkStatus = checkOrgPositionRank(req);
        if(!checkStatus.equals(0)){
            AddStaffEmploymentApplyResultDto dto = new AddStaffEmploymentApplyResultDto();
            dto.setId("");
            dto.setStatus(checkStatus);
            return ActionResult.success("成功", dto);
        }
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS)) {
            try {
                String id = staffRosterService.confirmOnDuty(req);
                AddStaffEmploymentApplyResultDto dto = new AddStaffEmploymentApplyResultDto();
                dto.setId(id);
                dto.setStatus(0);
                return ActionResult.success("成功", dto);
            } catch (Exception e) {
                log.error("确认到岗失败", e);
                return ActionResult.fail(e.getMessage());
            } finally {
                redisTemplate.delete(lockKey);
            }
        } else {
            throw new RuntimeException("提交中,请稍候");
        }
    }

    private Integer checkOrgPositionRank(ConfirmOnDutyReq req) {
        OrganizeEntity organizeEntity = personnelOrgUtils.queryOrganizeInfo(req.getCurrOrg());
        if(null==organizeEntity){
            return 1;
        }
        PositionEntity positionEntity = personnelOrgUtils.queryPosition(req.getCurrPosition());
        if(null==positionEntity){
            return 2;
        }
        PositionGradesInfoVO positionGradesInfoVO = personnelOrgUtils.queryRank(req.getCurrRank());
        if(null==positionGradesInfoVO){
            return 3;
        }
        return 0;
    }


    /**
     * 获取员工入职记录详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("/query-detail/{id}")
    public ActionResult<FtbPersonnelsStaffEmploymentApplyDto> get(@PathVariable("id") String id) {
        FtbPersonnelsStaffEmploymentApplyDto info = staffEmploymentApplyService.getInfo(id);
        return ActionResult.success(info);
    }


    /**
     * 办理入职
     *
     * @param req 入职参数
     * @return {@link ActionResult}<{@link String}>
     */
    @PostMapping("/handle-join-job")
    public ActionResult<String> handleJoinJob(@Validated @RequestBody AddStaffEmploymentApplyReq req) {
        String id = staffEmploymentApplyService.insertData(req);
        return ActionResult.success("成功", id);
    }

    /**
     * 审批
     *
     * @param id 主键id，必传
     * @return
     */

    @PutMapping("/approval/{id}")
    public ActionResult approval(@PathVariable("id") String id, @RequestBody EmploymentApplyCheckDto dto) {
        dto.setId(id);
        staffEmploymentApplyService.approval(dto);
        return ActionResult.success();
    }



    /**
     * 重新办理
     *
     * @param id 主键id，必传
     * @return
     */
    @PutMapping("/re-approval/{id}")
    public ActionResult reApproval(@PathVariable("id") String id, @RequestBody AddStaffEmploymentApplyReq dto) {
        staffEmploymentApplyService.reApproval(id, dto);
        return ActionResult.success();
    }


    /**
     * 删除
     *
     * @param id 主键id，必传
     * @return {@link ActionResult}
     */
    @DeleteMapping("/delete/{id}")
    public ActionResult delete(@PathVariable("id") String id) {
        staffEmploymentApplyService.deleteData(id);
        return ActionResult.success();
    }


    /**
     * 办理入职发送短信
     *
     * @param phone 手机号，必传
     * @return
     */
    @PutMapping("/send-phone-msg/{phone}")
    @Deprecated(since = "人事v1.3", forRemoval = true)
    public ActionResult sendPhoneMsg(@PathVariable("phone") String phone) {
        staffEmploymentApplyService.sendPhoneMsg(phone);
        return ActionResult.success("发送成功");

    }


    /**
     * 查询邀请码接口
     *
     * @return
     */
    @GetMapping("/query-code")
    public ActionResult<String> queryCode() {
        String code = staffEmploymentApplyService.queryCode();
        return ActionResult.success("成功", code);
    }

    /**
     * 办理入职,检测用户在系统中的状态
     * 0、系统不存在该用户  1、该手机号等待入职 2、该手机号等待入职审批  302、试用 303、正式  304、待离职  305 离职 306 试岗 4-该手机号已被拉入黑名单
     *
     * @param phone 手机号
     * @return
     */
    @GetMapping("/check-phone-status/{phone}")
    public ActionResult<CheckPhoneStatusVo> checkPhoneStatus(@PathVariable("phone") String phone) {
        String status = staffEmploymentApplyService.checkPhoneStatus(phone);
        CheckPhoneStatusVo vo = new CheckPhoneStatusVo();
        vo.setStatus(status);
        return ActionResult.success(vo);
    }

    /**
     * 保存短链
     *
     * @param id       入职表ID
     * @param shortUrl 短链
     * @return
     */
    @PutMapping("/save-short-url/{id}")
    public ActionResult saveShortUrl(@PathVariable("id") String id, @RequestParam("shortUrl") String shortUrl) {
        staffEmploymentApplyService.saveShortUrl(id, shortUrl);
        return ActionResult.success();
    }
}
