package com.jeeplus.test.changes.dimission.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.constant.enums.LogTypeEnum;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.changes.dimission.domain.ChangesDimission;
import com.jeeplus.test.changes.dimission.service.ChangesDimissionService;
import com.jeeplus.test.changes.dimission.service.dto.ChangesDimissionDTO;
import com.jeeplus.test.changes.dimission.service.mapstruct.ChangesDimissionWrapper;
import com.jeeplus.test.roster.domain.RosterBase;
import com.jeeplus.test.roster.service.RosterBaseService;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api("异动管理-离职")
@RestController
@RequestMapping(value = "/changes/dimission")
public class ChangesDimissionController {

    @Resource
    private ChangesDimissionService changesDimissionService;
    @Resource
    private RosterBaseService rosterBaseService;

    public List<String> getIntersection(List<String> list1,List<String> list2,List<String> list3){
        if(list1.size()!=0 && list2.size()!=0 && list3.size()!=0){
            List<String> intersection = (List<String>) CollectionUtils.intersection(list1, list2);
            return (List<String>) CollectionUtils.intersection(intersection, list3);
        }else if(list1.size()!=0 && list2.size()!=0 && list3.size()==0) {
            return (List<String>) CollectionUtils.intersection(list1, list2);
        }else if(list1.size()!=0 && list2.size()==0 && list3.size()!=0) {
            return (List<String>) CollectionUtils.intersection(list1, list3);
        }else if(list1.size()==0 && list2.size()!=0 && list3.size()!=0) {
            return (List<String>) CollectionUtils.intersection(list2, list3);
        }else if(list1.size()!=0 && list2.size()==0 && list3.size()==0) {
            return list1;
        }else if(list1.size()==0 && list2.size()!=0 && list3.size()==0) {
            return list2;
        }else if(list1.size()==0 && list2.size()==0 && list3.size()!=0) {
            return list3;
        }
        return null;
    }
    /**
     * 查询离职列表
     * @param changesDimissionDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询离职列表")
    @PreAuthorize("hasAuthority('changes:dimission:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<ChangesDimissionDTO>> data(ChangesDimissionDTO changesDimissionDTO, Page<ChangesDimissionDTO> page) throws Exception {
        ChangesDimission changesDimission = ChangesDimissionWrapper.INSTANCE.toEntity(changesDimissionDTO);
        QueryWrapper<ChangesDimission> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( changesDimission, ChangesDimission.class );
        if(ObjectUtil.isNotEmpty(changesDimissionDTO)){
            if(ObjectUtil.isNotEmpty(changesDimissionDTO.getRosterBaseDTO())){
                if(StringUtils.isNotBlank(changesDimissionDTO.getRosterId())
                        ||StringUtils.isNotBlank(changesDimissionDTO.getRosterBaseDTO().getOfficeId())
                        ||StringUtils.isNotBlank(changesDimissionDTO.getRosterBaseDTO().getMobile())){
                    List<String> rosterIdsName = new ArrayList<>();
                    List<String> rosterIdsOfficeId = new ArrayList<>();
                    List<String> rosterIdsMobile = new ArrayList<>();
                    if(StringUtils.isNotBlank(changesDimissionDTO.getRosterId())){
                        if(StringUtils.isNotBlank(changesDimissionDTO.getRosterId())) {
                            rosterIdsName.add(changesDimissionDTO.getRosterId());
                        }
                    }
                    if(StringUtils.isNotBlank(changesDimissionDTO.getRosterBaseDTO().getOfficeId())){
                        List<String> collect = rosterBaseService.list(new QueryWrapper<RosterBase>().lambda().eq(RosterBase::getOfficeId, changesDimissionDTO.getRosterBaseDTO().getOfficeId()))
                                .stream().map(RosterBase::getId).collect(Collectors.toList());
                        rosterIdsOfficeId.addAll(collect);
                        if(CollectionUtil.isNotEmpty(collect)) {
                            rosterIdsOfficeId.addAll(collect);
                        }else{
                            return ResponseEntity.ok(null);
                        }
                    }
                    if(StringUtils.isNotBlank(changesDimissionDTO.getRosterBaseDTO().getMobile())){
                        List<String> collect = rosterBaseService.list(new QueryWrapper<RosterBase>().lambda().like(RosterBase::getMobile, changesDimissionDTO.getRosterBaseDTO().getMobile()))
                                .stream().map(RosterBase::getId).collect(Collectors.toList());
                        rosterIdsMobile.addAll(collect);
                        if(CollectionUtil.isNotEmpty(collect)) {
                            rosterIdsMobile.addAll(collect);
                        }else{
                            return ResponseEntity.ok(null);
                        }
                    }
                    List<String> ids = getIntersection(rosterIdsName,rosterIdsOfficeId,rosterIdsMobile);
                    if(CollectionUtil.isNotEmpty(ids)){
                        queryWrapper.lambda().in(ChangesDimission::getRosterId,ids);
                    }else{
                        return ResponseEntity.ok(null);
                    }
                }
            }
        }
        IPage<ChangesDimissionDTO> result = changesDimissionService.findList (page,queryWrapper);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询离职数据
     * @param id
     * @return
     */
    @ApiLog("查询离职详情")
    @PreAuthorize ("hasAnyAuthority('changes:dimission:view','changes:dimission:add','changes:dimission:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        ChangesDimissionDTO changesDimissionDTO = changesDimissionService.queryById ( id );
        return ResponseEntity.ok (changesDimissionDTO);
    }

    /**
     * 修改/新增离职
     * @param changesDimissionDTO
     * @return
     */
    @ApiLog(value = "修改/新增离职", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('changes:dimission:save','changes:dimission:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody ChangesDimissionDTO changesDimissionDTO) {
        return changesDimissionService.saveDimission(changesDimissionDTO);
    }

    /**
     * 保存离职审批
     * @param changesDimissionDTO
     * @return
     */
    @ApiLog(value = "保存离职审批", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('changes:dimission:save','changes:dimission:edit')")
    @PostMapping("saveCheck")
    public ResponseEntity saveCheck(@Valid @RequestBody ChangesDimissionDTO changesDimissionDTO) {
        changesDimissionService.saveDimission(changesDimissionDTO);
        return ResponseUtil.newInstance().add("businessTable", "changes_dimission_audit").add("businessId", changesDimissionDTO.getId()).ok ("操作成功");
    }

    /**
     * 删除离职
     * @param ids
     * @return
     */
    @ApiLog(value = "删除离职", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('changes:dimission:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return changesDimissionService.deleteByIds(ids);
    }

    /**
     * 取消确认
     * @param id
     * @return
     */
    @ApiLog(value = "取消确认", type = LogTypeEnum.SAVE)
    @GetMapping("updateStatus")
    public ResponseEntity updateStatus(String id) {
        return changesDimissionService.updateStatus(id);
    }

    /**
     * 同意、驳回、撤回   离职审批
     * @param changesDimissionDTO
     */
    @ApiLog(value = "同意/驳回/撤回离职审批", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('changes:dimission:save','changes:dimission:edit')")
    @PostMapping("updateVettingStatusById")
    public void updateVettingStatusById(@Valid @RequestBody ChangesDimissionDTO changesDimissionDTO) {
        changesDimissionService.updateVettingStatusById(changesDimissionDTO);
    }
}
