package jnpf.personnels.controller.app.apply;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.constant.MsgCode;
import jnpf.cultivate.utils.CultivatePerUtils;
import jnpf.entity.StoreEntity;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.personnels.dto.apply.FtbPersonnelsApplyCreateDto;
import jnpf.model.personnels.dto.regular.FtbPersonnelsForAppQueryDTO;
import jnpf.model.personnels.dto.regular.FtbPersonnelsSalaryAuditDto;
import jnpf.model.personnels.dto.staff.roster.StaffHomeDto;
import jnpf.model.personnels.vo.app.FtbPersonnelsBubbleCountVO;
import jnpf.model.personnels.vo.apply.FtbPersonnelsApplyVO;
import jnpf.model.personnels.vo.apply.FtbPersonnelsApplyWithPerVO;
import jnpf.permission.OrganizeApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.model.position.PositionInfoNewVO;
import jnpf.permission.model.user.UserInfoVO;
import jnpf.personnels.service.FtbPersonnelsPostApplyService;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.store.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * app人事岗位晋升申请表模块
 *
 * @author peng.hao
 */
@RestController
@RequestMapping("/app/personnels-apply")
public class    FtbPersonnelsPostApplyForAppController {

    @Resource
    FtbPersonnelsPostApplyService service;


    @Autowired
    UserApi userApi;

    @Autowired
    CultivatePerUtils cultivatePerUtils;


    @Autowired
    FtbPersonnelsStaffRosterService staffRosterService;

    @Resource
    StoreService storeService;

    @Autowired
    OrganizeApi organizeApi;

    /**
     * 获取岗位申请列表
     * @param dto 岗位申请查询参数
     * @param page 分页信息
     * @return 岗位申请列表结果
     */
    @GetMapping("/getList")
    public ActionResult<PageListVO<FtbPersonnelsApplyVO>> getList(FtbPersonnelsForAppQueryDTO dto,
                                                                  CultivatePage page) {
        PageListVO<FtbPersonnelsApplyVO> pageListVO = service.getListForApp(dto, page);
        return ActionResult.success(pageListVO);
    }


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


    /**
     * 初始化岗位申请
     *
     * @param createDto 岗位申请创建数据传输对象
     * @return v1.1 返回 1 标识为门店负责人,需要进行替换
     */
    @PostMapping("/initPromApplication")
    public ActionResult<String> initiateAPromotionApplication(
            @Validated @RequestBody FtbPersonnelsApplyCreateDto createDto) {
        createDto.setSource(0);
        createDto.setFlag("2");
        Map<String, String> map = cultivatePerUtils.coverPersonalIds(Collections.singletonList(createDto.getUserId()));
        if (map !=null){
            createDto.setSystemWokerId(map.get(createDto.getUserId()));
        }
        StaffHomeDto staffHomeDto = staffRosterService.queryWorkerHomeDetail(createDto.getUserId());
        if (ObjectUtil.isNotEmpty(staffHomeDto)){
            createDto.setCurrentPay(staffHomeDto.getCurrSalary());
        }
        UserInfoVO bossUser = userApi.getLeaderInfo(createDto.getOrgId(),createDto.getUserId(),createDto.getPostId(),createDto.getPostRankId());
        if (ObjectUtil.isNotEmpty(bossUser) && bossUser.getRealName() != null) {
            createDto.setImmediateSuperName(bossUser.getRealName());
            createDto.setOldImmediateSuperName(bossUser.getRealName());
        }
        if (ObjectUtil.isNotEmpty(bossUser) && bossUser.getId() != null) {
            createDto.setImmediateSuperId(bossUser.getId());
            createDto.setOldImmediateSuperId(bossUser.getId());
        }
        String s = service.initiateAPromotionApplication(createDto);
        return ActionResult.success(MsgCode.SU000.get(),s);
    }

    /**
     * 直接办理岗位申请
     */
    @PostMapping("/applyDirectlyForThePosition")
    public ActionResult<String> applyDirectlyForThePosition(
            @Validated @RequestBody FtbPersonnelsApplyCreateDto createDto) {
        extracted(createDto.getUserId(), createDto.getOrgId(),createDto.getPostId(),createDto.getPostRankId(),createDto);
        String s = service.initiateAPromotionApplication(createDto);
        return ActionResult.success(MsgCode.SU000.get(),s);
    }

    /**
     * 主管构建
     * @param userId
     * @param orgId
     * @param postId
     * @param postRankId
     * @param createDto
     */
    private void extracted(String userId,String orgId,String postId,String postRankId,FtbPersonnelsApplyCreateDto createDto) {
        UserInfoVO bossUser = userApi.getLeaderInfo(orgId, userId,postId,postRankId);
        // 将老的主管信息赋值
        if (ObjectUtil.isNotEmpty(bossUser) && bossUser.getRealName() != null) {
            createDto.setOldImmediateSuperName(bossUser.getRealName());
        }
        if (ObjectUtil.isNotEmpty(bossUser) && bossUser.getId() != null) {
            createDto.setOldImmediateSuperId(bossUser.getId());
        }
        // 只要如果晋升主管为空,则设置为之前的主管
        if (StringUtils.isEmpty(createDto.getImmediateSuperId()) && ObjectUtil.isNotEmpty(bossUser)
        && createDto.getOrgId().equals(createDto.getOrgCurrentId())){
            createDto.setImmediateSuperId(bossUser.getId());
            createDto.setImmediateSuperName(bossUser.getRealName());
        }
    }


    /**
     * 根据用户id和组织id 获取晋升通道晋升岗位
     */
    @GetMapping("/queryPostInfoByOrgAndUserId")
    @Deprecated(since = "培训v1.1废弃", forRemoval = true)
    public ActionResult<List<PositionInfoNewVO>> queryPostInfoByOrgAndUserId(@RequestParam("userId") String userId,
                                                                             @RequestParam("orgId") String orgId){
        List<PositionInfoNewVO> voList = service.queryPostInfoByOrgAndUserId(userId,orgId);
        return ActionResult.success(voList);
    }
    /**
     * 查询岗位申请详情
     * @param id 岗位申请主键id
     * @return 响应结果对象，包含岗位申请及相关信息
     */
    @GetMapping("/viewPromApplication/{id}")
    @Operation(summary = "查询岗位申请详情")
    public ActionResult<FtbPersonnelsApplyWithPerVO> viewPromApplication(@PathVariable("id") String id) {
        FtbPersonnelsApplyWithPerVO withPerVO = service.viewPromotionApplications(id,"1");
        return ActionResult.success(withPerVO);
    }

    /**
     * 审核岗位申请的接口
     * @param dto 岗位申请数据传输对象
     * @return 审核结果
     */
    @PutMapping("/auditPromApplication")
    @Operation(summary = "审核岗位申请")
    public ActionResult<String> auditPromotionPostApplication(@Validated @RequestBody FtbPersonnelsSalaryAuditDto dto) {
        service.auditPromotionPostApplication(dto);
        return ActionResult.success();
    }


    /**
     * 获取门店负责人详情
     * @param userId 门店负责人id
     * @return organizeName 组织名称   storeName   门店名称
     */
    @GetMapping("/getStoreManagerInfo")
    public ActionResult<List<Map<String,Object>>> getStoreManagerInfo(@RequestParam("userId") String userId) {
        LambdaQueryWrapper<StoreEntity> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(StoreEntity::getStoreheaduserid,userId);
        List<StoreEntity> list = storeService.list(objectLambdaQueryWrapper);
        List<Map<String, Object>> maps = list.stream().map(item -> {
            Map<String, Object> map = Maps.newHashMap();
            OrganizeEntity organize = organizeApi.getInfoById(item.getOrganizeid());
            map.put("organizeName", organize.getFullName());
            map.put("storeName", item.getStorename());
            return map;
        }).collect(Collectors.toList());
        return ActionResult.success(maps);
    }
}
