package com.yifu.cloud.plus.v1.business.controller.vacation;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.business.entity.vacation.TBusLeave;
import com.yifu.cloud.plus.v1.business.service.vacation.TBusLeaveService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.BusinessEmployeeExtendByLeave;
import com.yifu.cloud.plus.v1.yifu.archives.vo.UpdateEmployeeExtendRedundancyDTO;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * B端离职信息表
 *
 * @author hgw
 * @date 2021-08-17 17:02:47
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tbusleave")
@Tag(name = "B端离职信息表")
public class TBusLeaveController {

     private final TBusLeaveService tBusLeaveService;

	 private final ArchivesDaprUtil daprUtil;

     /**
      * 简单分页查询
      *
      * @param page      分页对象
      * @param tBusLeave B端离职信息表
      * @return
      */
	 @Operation(summary = "简单分页查询", description = "简单分页查询")
	 @GetMapping("/page")
     public R<IPage<TBusLeave>> getTBusLeavePage(Page<TBusLeave> page, TBusLeave tBusLeave) {
          return new R<>(tBusLeaveService.getTBusLeavePage(page, tBusLeave));
     }

     /**
      * 获取list
      *
      * @param tBusLeave B端离职信息表
      * @return
      */
	 @Operation(summary = "获取list", description = "获取list")
	 @GetMapping("/getTBusLeaveList")
     public R<List<TBusLeave>> getTBusLeaveList(TBusLeave tBusLeave) {
          return new R<>(tBusLeaveService.getTBusLeaveList(tBusLeave));
     }


     /**
      * 通过id查询单条记录
      *
      * @param id
      * @return R
      */
	 @Operation(summary = "id查询", description = "id查询")
	 @GetMapping("/{id}")
     public R<TBusLeave> getById(@PathVariable("id") String id) {
          return new R<>(tBusLeaveService.getById(id));
     }

     /**
      * 新增记录
      *
      * @param tBusLeave
      * @return R
      */
	 @Operation(summary = "新增", description = "新增")
	 @PostMapping
//     @PreAuthorize("@pms.hasPermission('yifu-hro-business:tbusleave_add')")
     public R<Boolean> save(@RequestBody TBusLeave tBusLeave) {
          YifuUser user = SecurityUtils.getUser();
          if (user != null && user.getId() != null) {
               tBusLeave.setCreateUserId(String.valueOf(user.getId()));
               tBusLeave.setCreateTime(LocalDateTime.now());
               tBusLeave.setCreateUserName(user.getNickname());
               this.updateEmpInfo(tBusLeave);
               return new R<>(tBusLeaveService.save(tBusLeave));
          } else {
               return R.failed("未获取到登录人信息！");
          }
     }

     /**
      * @param leave
      * @Description: 单个更新人员信息
	  * @Author: huyc
	  * @Date: 2023/1/6 11:14
      * @return: void
      **/
     private void updateEmpInfo(TBusLeave leave) {
          List<UpdateEmployeeExtendRedundancyDTO> dtoList = new ArrayList<>();
          UpdateEmployeeExtendRedundancyDTO dto = new UpdateEmployeeExtendRedundancyDTO();
          dto.setEmpIdcard(leave.getIdCard());
          dto.setBusinessLeaveDate(leave.getLeaveDate());
          dto.setBusinessLeaveReason(leave.getLeaveReason());
          dto.setBusinessWorkingStatus(CommonConstants.ONE_STRING);
          dtoList.add(dto);
          daprUtil.updateEmployeeExtendRedundancy(dtoList);
     }

     /**
      * @param leaveList
      * @Description: 批量更新人员信息
	  * @Author: huyc
	  * @Date: 2023/1/6 11:14
      * @return: void
      **/
     private void batchUpdateEmpInfo(List<TBusLeave> leaveList) {
          if (leaveList != null && !leaveList.isEmpty()) {
               List<UpdateEmployeeExtendRedundancyDTO> dtoList = new ArrayList<>();
               UpdateEmployeeExtendRedundancyDTO dto;
               for (TBusLeave leave : leaveList) {
                    dto = new UpdateEmployeeExtendRedundancyDTO();
                    dto.setEmpIdcard(leave.getIdCard());
                    dto.setBusinessLeaveDate(leave.getLeaveDate());
                    dto.setBusinessLeaveReason(leave.getLeaveReason());
                    dto.setBusinessWorkingStatus(CommonConstants.ONE_STRING);
                    dtoList.add(dto);
               }
               daprUtil.updateEmployeeExtendRedundancy(dtoList);
          }
     }


     /**
      * 导入
      *
      * @return R
      */
	 @Operation(summary = "导入", description = "导入")
	 @PostMapping("/importLeave")
     public R<List<ErrorMessage>> importLeave(@RequestBody List<TBusLeave> leaveList) {
          if (leaveList == null || leaveList.isEmpty()) {
               return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
          }
          YifuUser user = SecurityUtils.getUser();
          if (user == null || user.getId() == null) {
               return R.failed("未获取到登录人信息！");
          }
          LocalDateTime nows = LocalDateTime.now();
          List<ErrorMessage> errorList = new ArrayList<>();
          R<Map<String, BusinessEmployeeExtendByLeave>> dataR = daprUtil.getInfoByLeaveMap();
          Map<String, BusinessEmployeeExtendByLeave> empMap;
          if (dataR != null && dataR.getData() != null && !dataR.getData().isEmpty()) {
               empMap = dataR.getData();
          } else {
               return R.failed("未获取到基础服务-人员附属信息！");
          }
          int i = 1;
          List<TBusLeave> updateLsit = new ArrayList<>();
		  TBusLeave tBusLeaveExit;
          for (TBusLeave tBusLeave : leaveList) {
               i++;
			   if (Common.isNotNull(tBusLeave.getTeleNo())) {
				   tBusLeaveExit = tBusLeaveService.getOne(Wrappers.<TBusLeave>query().lambda()
						   .eq(TBusLeave::getTeleNo, tBusLeave.getTeleNo())
						   .last(CommonConstants.LAST_ONE_SQL));
				   if (Common.isNotNull(tBusLeaveExit)) {
					   errorList.add(new ErrorMessage(i, "已存在对应电信工号'" + tBusLeave.getTeleNo() + "'的离职数据！"));
					   continue;
				   }
			   } else {
				  errorList.add(new ErrorMessage(i, "'" + "'电信工号不可为空！"));
				  continue;
			  }
			  if (Common.isEmpty(tBusLeave.getLeaveDate()) || Common.isEmpty(tBusLeave.getLeavePostDate())
                       || Common.isEmpty(tBusLeave.getLeaveReason()) || tBusLeave.getLeaveReason().length() > 200) {
                    // 判断并拦截
                    this.judgeLeave(errorList, i, tBusLeave);
               } else {
                    // 导入
                    this.saveAndJudge(user, nows, errorList, empMap, i, updateLsit, tBusLeave);
               }
          }
          // 更新人员信息
          this.batchUpdateEmpInfo(updateLsit);
		  if (errorList.isEmpty()) {
			  errorList = null;
		  }
          return R.ok(errorList,"操作成功");
     }

     /**
      * @param errorList
      * @param i
      * @param tBusLeave
      * @Description: 判断离职原因等
      * @Author: hgw
      * @Date: 2021/8/24 16:19
      * @return: void
      **/
     private void judgeLeave(List<ErrorMessage> errorList, int i, TBusLeave tBusLeave) {
          String error;
          if (Common.isEmpty(tBusLeave.getLeaveDate())) {
               error = "'" + tBusLeave.getTeleNo() + "'工号无离职日期，无法导入！";
               errorList.add(new ErrorMessage(i, error));
          }
          if (Common.isEmpty(tBusLeave.getLeavePostDate())) {
               error = "'" + tBusLeave.getTeleNo() + "'工号无离岗日期，无法导入！";
               errorList.add(new ErrorMessage(i, error));
          }
          if (Common.isEmpty(tBusLeave.getLeaveReason())) {
               error = "'" + tBusLeave.getTeleNo() + "'工号无离职原因，无法导入！";
               errorList.add(new ErrorMessage(i, error));
          }
          if (Common.isNotNull(tBusLeave.getLeaveReason()) && tBusLeave.getLeaveReason().length() > 200) {
               error = "'" + tBusLeave.getTeleNo() + "'工号离职原因超过200字符，无法导入！";
               errorList.add(new ErrorMessage(i, error));
          }
     }

     /**
      * @Description: 保存和判断
      * @Author: huyc
      * @Date: 2023/1/6 11:14
      * @return: void
      **/
     private void saveAndJudge(YifuUser user, LocalDateTime nows, List<ErrorMessage> errorList
             , Map<String, BusinessEmployeeExtendByLeave> empMap, int i, List<TBusLeave> updateLsit, TBusLeave tBusLeave) {
          BusinessEmployeeExtendByLeave empInfo;
          String error;
          String userName = user.getNickname();
          String userId = String.valueOf(user.getId());
          if (Common.isNotNull(tBusLeave.getTeleNo())) {
               empInfo = empMap.get(tBusLeave.getTeleNo());
               if (empInfo != null) {
                    if (Common.isNotNull(empInfo.getBusinessWorkingStatus()) && CommonConstants.ONE_STRING.equals(empInfo.getBusinessWorkingStatus())) {
                         error = "'" + tBusLeave.getTeleNo() + "'工号员工已离职，请核实无误后再操作！";
                         errorList.add(new ErrorMessage(i, error));
                    } else {
                         tBusLeave.setDeptId(empInfo.getDepartId());
                         tBusLeave.setDeptName(empInfo.getDepartName());
                         tBusLeave.setDeptTreeLogo(empInfo.getDepartCode());
                         tBusLeave.setName(empInfo.getEmpName());
                         tBusLeave.setIdCard(empInfo.getEmpIdcard());
                         tBusLeave.setPost(empInfo.getBusinessPost());
                         tBusLeave.setCreateTime(nows);
                         tBusLeave.setCreateUserId(userId);
                         tBusLeave.setCreateUserName(userName);
                         tBusLeaveService.save(tBusLeave);
                         updateLsit.add(tBusLeave);
                    }
               } else {
                    error = "电信工号未匹配到人员附属信息：'" + tBusLeave.getTeleNo() + "'";
                    errorList.add(new ErrorMessage(i, error));
               }
          }
     }

     /**
      * 修改记录
      *
      * @param tBusLeave
      * @return R
      */
     @SysLog("修改B端离职信息表")
	 @Operation(summary = "修改", description = "修改")
	 @PutMapping
//     @PreAuthorize("@pms.hasPermission('yifu-hro-business:tbusleave_edit')")
     public R<Boolean> update(@RequestBody TBusLeave tBusLeave) {
          this.updateEmpInfo(tBusLeave);
          return new R<>(tBusLeaveService.updateById(tBusLeave));
     }

     /**
      * 通过id删除一条记录
      *
      * @param id
      * @return R
      */
     @SysLog("假删除B端离职信息表")
	 @Operation(summary = "假删除", description = "假删除")
     @DeleteMapping("/{id}")
//     @PreAuthorize("@pms.hasPermission('yifu-hro-business:tbusleave_del')")
     public R<Boolean> removeById(@PathVariable String id) {
          TBusLeave tBusLeave = new TBusLeave();
          tBusLeave.setId(id);
          tBusLeave.setDeleteFlag(1);
          return new R<>(tBusLeaveService.updateById(tBusLeave));
     }

}
