package jnpf.personnels.controller.web.salary;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import jnpf.base.ActionResult;
import jnpf.model.common.PayRollJsonItem;
import jnpf.model.hr.PersonSalaryHistoryVo;
import jnpf.model.personnels.dto.salary.FtbPersonnelRosterSalaryHistoryDTO;
import jnpf.model.personnels.dto.salary.FtbPersonnelsSalaryInfo;
import jnpf.model.personnels.dto.salary.FtbPersonnelsSalaryTemporaryStorageCreatDto;
import jnpf.model.personnels.po.FtbPersonnelsSecondmentManagement;
import jnpf.model.personnels.vo.salary.FtbPersonnelRosterSalaryVO;
import jnpf.model.personnels.vo.salary.FtbPersonnelsSalaryTemporaryStorageVo;
import jnpf.model.personnels.vo.salary.FtbPersonnelsSalaryVO;
import jnpf.model.vo.UserSalaryHistoryVo;
import jnpf.personnels.service.FtbPersonnelsSalaryService;
import jnpf.personnels.service.FtbPersonnelsSecondmentManagementService;
import jnpf.salary.QuerySalaryApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: web/app通用薪酬开放接口
 * @Author: peng.hao
 * @create: 2024/5/11:15:35
 */
@Slf4j
@RestController
@RequestMapping("/personnels-salary")
public class FtbPersonnelsSalaryController {

    @Autowired
    FtbPersonnelsSalaryService salaryService;

    @Autowired
    QuerySalaryApi querySalaryApi;

    @Resource
    FtbPersonnelsSecondmentManagementService ftbPersonnelsSecondmentManagementService;


    /**
     * 获取当前人员薪酬
     * 1.入职 使用薪酬配置 根据当前人加入职岗位职等获取薪酬
     * 2.转正  否 (根据userId+转正岗位职等获取薪酬) 是(同理)
     * 3.调岗  否 (根据userId+选择调整的组织岗位职等) 是(根据userId+调岗后的岗位Id+职等id)
     * 5.晋升  否 (根据userId+所属岗位/职等) 是(根据userId+晋升后岗位Id+职等Id)
     * @param postId 岗位id
     * @param rankId 职等id
     * @param userId 用户id
     */
    @GetMapping("/getPaidForYourPeople")
    public ActionResult<List<FtbPersonnelsSalaryInfo>> getTheCurrentPersonSSalary(@RequestParam(value = "userId",required = false) String userId,
                                                                                  @RequestParam(value = "rankId") String rankId,
                                                                                  @RequestParam(value = "postId") String postId) {
        return ActionResult.success(salaryService.getTheCurrentPersonSSalary(userId, rankId, postId));
    }
    /**
     * 保存薪酬信息
     */
    @PutMapping("/saveTheChangePayInformation")
    public ActionResult<String> saveTheChangePayInformation(@RequestBody FtbPersonnelsSalaryVO vo) {
        salaryService.saveTheChangePayInformation(vo.getSalaryList(),vo.getUserId(),vo.getDate(),
                vo.getUserInfoWithSalary(),vo.getUpdateType(),vo.getRemark(),vo.getOperationType(),0,vo.getSalaryType(), "");
        return ActionResult.success();
    }


    public static FtbPersonnelsSalaryInfo covert(PayRollJsonItem payRollJsonItem ) {
        if (payRollJsonItem == null) {
            return null;
        }
        FtbPersonnelsSalaryInfo ftbPersonnelsSalaryInfo = new FtbPersonnelsSalaryInfo();
        ftbPersonnelsSalaryInfo.setId(payRollJsonItem.getId());
        ftbPersonnelsSalaryInfo.setFIsForce(payRollJsonItem.getfIsForce());
        ftbPersonnelsSalaryInfo.setFName(payRollJsonItem.getfName());
        ftbPersonnelsSalaryInfo.setFRemark(payRollJsonItem.getfRemark());
        ftbPersonnelsSalaryInfo.setDecimalPlaces(payRollJsonItem.getfReservedBits());
        ftbPersonnelsSalaryInfo.setFSetType(payRollJsonItem.getfSetType());
        ftbPersonnelsSalaryInfo.setFCarryRule(payRollJsonItem.getfCarryRule());
        ftbPersonnelsSalaryInfo.setFItem(payRollJsonItem.getfItem());
        ftbPersonnelsSalaryInfo.setFSetValue(payRollJsonItem.getfSetValue());
        ftbPersonnelsSalaryInfo.setFTaxType(payRollJsonItem.getfTaxType());
        ftbPersonnelsSalaryInfo.setFValueType(payRollJsonItem.getfValueType());
        ftbPersonnelsSalaryInfo.setSort(payRollJsonItem.getfSort());
        ftbPersonnelsSalaryInfo.setFDesc(payRollJsonItem.getfDesc());
        ftbPersonnelsSalaryInfo.setSequenceType(payRollJsonItem.getSequenceType());
        ftbPersonnelsSalaryInfo.setFSort(payRollJsonItem.getfSort());
        ftbPersonnelsSalaryInfo.setFTypeSort(payRollJsonItem.getfTypeSort());
        ftbPersonnelsSalaryInfo.setGroupId(payRollJsonItem.getGroupId());
        ftbPersonnelsSalaryInfo.setGroupName(payRollJsonItem.getGroupName());
        ftbPersonnelsSalaryInfo.setGroupSort(String.valueOf(payRollJsonItem.getGroupSort()));

        return ftbPersonnelsSalaryInfo;
    }

    /**
     * 根据用户id，查询历史薪资变化记录
     *
     * @param dto 系统用户id 等查询参数
     * @return 包含花名册部分信息的历史记录信息
     */
    @GetMapping("/history/list")
    public ActionResult<List<FtbPersonnelRosterSalaryVO>> getSalaryHistoryByUserId(@SpringQueryMap FtbPersonnelRosterSalaryHistoryDTO dto) {

        return ActionResult.success(salaryService.getSalaryHistoryByUserId(dto));
    }

    /**
     * 根据原id和type，查询历史薪资变化记录详情
     *
     * @param id   历史记录的id
     * @param type 历史记录原样类型
     * @return 历史记录原样
     */
    @GetMapping("/history/detail")
    public ActionResult<PersonSalaryHistoryVo> getSalaryHistoryDetailByUserId(@RequestParam(value = "id") String id, @RequestParam(value = "type") String type) {
        return querySalaryApi.getSalaryHistoryDetailByUserId(id, type);
    }

    /**
     * 薪资临时存储接口
     */
    @PostMapping("/creatSalaryTemporaryStorage")
    public ActionResult<String> creatSalaryTemporaryStorage(@RequestBody FtbPersonnelsSalaryTemporaryStorageCreatDto creatDto){
        salaryService.creatSalaryTemporaryStorage(creatDto);
        return ActionResult.success();
    }
    /**
     * 薪资临时修改接口
     */
    @PutMapping("/updateSalaryTemporaryStorage")
    public ActionResult<String> updateSalaryTemporaryStorage(@RequestBody FtbPersonnelsSalaryTemporaryStorageCreatDto creatDto){
        salaryService.updateSalaryTemporaryStorage(creatDto);
        return ActionResult.success();
    }
    /**
     * 薪资临时查询接口
     * @param uerId 用户id
     * @param configType  1 入职审批配置  2 转正审批配置  3 调岗审批配置 4 离职审批配置 5 晋升审批配置
     */
    @GetMapping("/querySalaryTemporaryStorage")
    public ActionResult<FtbPersonnelsSalaryTemporaryStorageVo> querySalaryTemporaryStorage(@RequestParam String uerId,
                                                                                           @RequestParam String configType){
        FtbPersonnelsSalaryTemporaryStorageVo vo = salaryService.querySalaryTemporaryStorage(uerId,configType);

        return ActionResult.success(vo);
    }
    /**
     * 根据人和薪资生效时间查询是否有之前的薪酬数据
     * @return {
     * 	    [
     * 		 type : 生效的模块 (入职,转正,调岗,晋升)
     * 		 time : 生效时间 (具体薪资生效时间)
     * 	    ]
     * }
     */
    @GetMapping("/query-salary-by-userId-time")
    public ActionResult<List<Map<String,Object>>> querySalaryByUserIdAndTime(@RequestParam("userId") String user,
                                                                             @RequestParam ("date") Date date ) throws Exception {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        ActionResult<List<UserSalaryHistoryVo>> historyByChangeDate = querySalaryApi.getHistoryByChangeDate(format, user);
        log.error("获取数据000----------->"+ historyByChangeDate);
        if (historyByChangeDate == null ){
            return ActionResult.fail("获取薪酬数据失败,请稍后再试!");
        }
        List<UserSalaryHistoryVo> data = historyByChangeDate.getData();
        List<Map<String, Object>> maps = new ArrayList<>();
        if (data.stream().allMatch(item -> item.getFChangeDate() != null)) {
            for (UserSalaryHistoryVo userSalaryHistoryVo : data) {
                Map<String, Object> map = new HashMap<>();
                // 获取备注 1：转正  0：其他  2: 调岗 3 晋升 4 入职
                String fUserState = userSalaryHistoryVo.getFUserState();
                if ("1".equals(fUserState)){
                    fUserState = "转正";
                }else if ("2".equals(fUserState) || "3".equals(fUserState)){
                    fUserState = "调动";
                }else if ("4".equals(fUserState)){
                    fUserState = "入职";
                }else if ("5".equals(fUserState)){
                    fUserState = "薪酬审批调薪";
                }else if ("6".equals(fUserState)){
                    fUserState = "调动";
                }else if ("7".equals(fUserState)){
                    fUserState = "薪酬直接调薪";
                }else if ("8".equals(fUserState)){
                    fUserState = "薪酬编辑";
                } else if ("9".equals(fUserState)){
                    fUserState = "借调";
                }else if ("0".equals(fUserState)) {
                    fUserState = "导入";
                }else if ("10".equals(fUserState)) {
                    fUserState = "借调返岗";
                }
                map.put("type", fUserState);
                map.put("time", userSalaryHistoryVo.getFChangeDate());
                maps.add(map);
            }
        }
        return ActionResult.success(maps);
    }

    /**
     * 是否作废薪资
     * @param id 主键id
     * @param flag 0 不作废 1 作废
     * @param type 历史记录原样类型
     * @return
     */
    @GetMapping("/whether-to-voidWages")
    public ActionResult<String> whetherToVoidWages(@RequestParam("id") String id,
                                                   @RequestParam ("flag") String flag,
                                                   @RequestParam ("type") String type,
                                                   @RequestParam ("userId") String userId,
                                                   @RequestParam("changeDate") Date changeDate){
        ActionResult<PersonSalaryHistoryVo> byUserId = querySalaryApi.getSalaryHistoryDetailByUserId(id, type);
        if (byUserId ==  null){
            return ActionResult.fail("历史薪资记录获取失败");
        }
        PersonSalaryHistoryVo data = byUserId.getData();
        if (ObjectUtil.isEmpty(data)){
            return ActionResult.success("历史薪资记录无数据变更");
        }
        List<PayRollJsonItem> beforeItem = data.getBeforeItem();
        salaryService.whetherToVoidWages(userId,beforeItem,flag,changeDate);
        return ActionResult.success();
    }
    /**
     * 查询借调薪酬是否有交集
     */
    @GetMapping("/query-salary-intersection")
    public ActionResult<List<Map<String,Object>>> querySalaryIntersection(@RequestParam("userId") String userId,
                                                                          @RequestParam("date") Date date){
        List<FtbPersonnelsSecondmentManagement> serviceIdList = ftbPersonnelsSecondmentManagementService.salarySecondmentCrossover(userId,
                date);
        if(CollUtil.isNotEmpty(serviceIdList)){
            List<Map<String, Object>> hashMaps = serviceIdList.stream().map(v -> {
                Map<String, Object> map = new HashMap<>();
                map.put("startTime", v.getSecondmentStartTime());
                map.put("endTime", v.getSecondmentEndTime());
                return map;
            }).collect(Collectors.toList());
            return ActionResult.success(hashMaps);
        }
        return ActionResult.success();
    }
    /**
     * 查询借调薪酬与其他办理业务是否有交集
     */
    @GetMapping("/query-salary-intersection-with-other-business")
    public ActionResult<List<Map<String,Object>>> querySalaryIntersectionWithOtherBusiness(@RequestParam("userId") String userId,
                                                                                           @RequestParam("startData") Date startData,
                                                                                           @RequestParam("endData") Date endData) {
        List<Map<String,Object>>  result =   salaryService.querySalaryIntersectionWithOtherBusiness(userId, startData, endData);
        return ActionResult.success(result);
    }
}
