package com.yifu.cloud.plus.v1.yifu.archives.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TBusinessEmployeeExtendInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.archives.service.TBusinessEmployeeExtendInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeContractInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeProjectService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.EmpBusinessConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ServiceNameConstants;
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.security.annotation.Inner;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * B端员工档案相关接口
 * @Author fxj
 * @Date 2020-08-25
 * @return
 **/
@RestController
@AllArgsConstructor
@RequestMapping(value = "/customerBusiness/temployeeBusiness")
@Tag(name = "员工档案B端接口")
@Slf4j
public class EmployeeBusinessController {

    private final TEmployeeProjectService tEmployeeProjectService;

    private final TEmployeeContractInfoService tEmployeeContractInfoService;

    private final TBusinessEmployeeExtendInfoService businessEmployeeExtendInfoService;

	@Operation(description = "B端花名册简单分页查询")
	@GetMapping("/page")
	public R<IPage<BusinessEmployeeExtendListVO>> getTEmployeeBusinessPage(Page page, THroBusinessUserQuery query) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null) {
			return R.failed("请登录!");
		}

		if (!R.isSuccess(businessPowerCheck(query))) {
			return R.failed(businessPowerCheck(query).getMsg());
		}
		return new R<>(tEmployeeProjectService.getTEmployeeBusinessPage(page, query));
	}

	/**
	 * 通过id查询单条记录
	 *
	 * @param id
	 * @return R
	 */
	@Operation(description = "B端获取员工的相关信息")
	@GetMapping("/getEmployeeBusinessInfoById")
	public R<EmployeeBusinessDetailVo> getEmployeeBusinessInfoById(@RequestParam(value = "id") String id, @RequestParam("settleDomain") String settleDomain) {
		if (!Common.isNotNull(id)){
			return R.failed("员工ID不可为空！");
		}
		return new R<>(tEmployeeProjectService.getEmployeeBusinessInfoById(id, settleDomain));
	}

	/**
	 * 通过id查询单条记录
	 *
	 * @param id
	 * @return R
	 */
	@Operation(description = "B端获取员工及B端附属信息")
	@GetMapping("/getEmployeeBusinessVoById")
	public R<EmployeeBusinessVo> getEmployeeBusinessVoById(@RequestParam(value = "id") String id) {
		if (!Common.isNotNull(id)){
			return R.failed("员工ID不可为空！");
		}
		return tEmployeeProjectService.getEmployeeBusinessVoById(id);
	}

	/**
	 * b端人员信息编辑拓展信息
	 * @description: b端人员信息编辑拓展信息
	 * @param dto
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 * @author: wangweiguo
	 * @date: 2021/8/10
	 */
	@Operation(description = "编辑：b端人员信息编辑拓展信息")
	@PutMapping("/updateEmployInfoByExtendId")
	public R<Boolean> updateEmployInfoByExtendId(@RequestBody @Valid UpdateBusinessEmployeeExtendDTO dto) {
		TBusinessEmployeeExtendInfo tBusinessEmployeeExtendInfo = businessEmployeeExtendInfoService.getDataById(dto.getExtendId());
		if (null == tBusinessEmployeeExtendInfo) {
			tBusinessEmployeeExtendInfo = new TBusinessEmployeeExtendInfo();
		}
		tBusinessEmployeeExtendInfo.setId(dto.getExtendId());
		BeanUtil.copyProperties(dto, tBusinessEmployeeExtendInfo, CopyOptions.create().setIgnoreNullValue(true));
		if (StringUtils.isBlank(tBusinessEmployeeExtendInfo.getEmpName())) {
			TEmployeeProject employeeInfo = this.tEmployeeProjectService.lambdaQuery().eq(TEmployeeProject::getEmpIdcard, dto.getEmpIdcard()).last(CommonConstants.LAST_ONE_SQL).one();
			if (null != employeeInfo) {
				tBusinessEmployeeExtendInfo.setEmpName(employeeInfo.getEmpName());
			}
		}
		return businessEmployeeExtendInfoService.saveOrUpdateData(tBusinessEmployeeExtendInfo);
	}

	/**
	 * b端人员信息批量导入更新人员信息拓展表
	 * @description: 批量更新：b端人员信息批量导入更新人员信息拓展表
	 * @param jsonStr
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 * @author: wangweiguo
	 * @date: 2021/8/10
	 */
	@Operation(description = "批量更新：b端人员信息批量导入更新人员信息拓展表")
	@PutMapping("/batchUpdateEmployeeExtendByJsonStr")
	public R<List<ErrorMessage>> batchUpdateEmployeeExtendByJsonStr(@RequestBody String jsonStr) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		if (CollUtil.isEmpty(user.getSettleIdList())) {
			return R.failed(CommonConstants.NO_SETTLE_DOMAIN_AUTH);
		}
		List<TEmployeeProject> employeeInfoList = tEmployeeProjectService.lambdaQuery().in(TEmployeeProject::getDeptId, user.getSettleIdList()).list();
		if (CollUtil.isEmpty(employeeInfoList)) {
			return R.failed(CommonConstants.HRO_EMPLOYEE_NULL);
		}

		HashMap<String, TEmployeeProject> empInfoMap = Common.listToHashMapByKey(employeeInfoList, "empIdcard");
		return businessEmployeeExtendInfoService.batchUpdateEmployeeExtendByJsonStr(jsonStr, empInfoMap);
	}

	/**
	 * b端人员信息导出
	 * @description: 导出：b端人员信息导出
	 * @param query
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 * @author: wangweiguo
	 * @date: 2021/8/10
	 */
	@Operation(description = "导出：b端人员信息导出")
	@GetMapping("/exportByParams")
	public R<List<BusinessEmployeeExtentExcelVO>> exportByParams(THroBusinessUserQuery query) {
		if (!R.isSuccess(businessPowerCheck(query))) {
			return R.failed(businessPowerCheck(query).getMsg());
		}
		return this.tEmployeeProjectService.exportByParams(query);
	}

	/**
	 * 更新人员信息冗余字段
	 * @description: 更新人员信息冗余字段
	 * @param dtoList
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.List<ErrorMessage>>
	 * @author: wangweiguo
	 * @date: 2021/8/12
	 */
	@Inner
	@PostMapping("/inner/updateEmployeeExtendRedundancy")
	public Boolean updateEmployeeExtendRedundancy(@RequestBody List<UpdateEmployeeExtendRedundancyDTO> dtoList) {
		return this.businessEmployeeExtendInfoService.updateEmployeeExtendRedundancy(dtoList);
	}

	/**
	 * 按身份证单个更新证件冗余信息
	 * @author: fxj
	 * @date 2021-08-23
	 * @param dto
	 * @return
	 */
	@Inner
	@PostMapping("/inner/updateEmpExtendCertInfo")
	public boolean updateEmpExtendCertInfo(@RequestBody UpdateEmployeeExtendRedundancyDTO dto) {
		return this.businessEmployeeExtendInfoService.updateEmpExtendCertInfo(dto);
	}

	/**
	 * 根据身份证号获取拓展信息列表
	 * @description: 根据身份证号获取拓展信息列表
	 * @param idCardList
	 * @return: com.yifu.cloud.v1.common.core.util.R<List<TBusinessEmployeeExtendInfo>>
	 * @author: wangweiguo
	 * @date: 2021/8/16
	 */
	@Inner
	@PostMapping("/inner/getListByIdCartList")
	public BusinessEmployeeListVo getListByIdcartList(@RequestBody List<String> idCardList) {
		BusinessEmployeeListVo vo = new BusinessEmployeeListVo();
		if (CollUtil.isEmpty(idCardList)) {
			return vo;
		}
		vo.setEmpList(businessEmployeeExtendInfoService.getListByIdCardList(idCardList));
		return vo;
	}

	/**
	 * 查询-列表：内部服务调用，获取所有非离职员工拓展表信息
	 * @description: 查询-列表：内部服务调用，获取所有非离职员工拓展表信息
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.util.List<com.yifu.cloud.v1.hrms.api.vo.basic.BusinessEmployeeExtendVO>>
	 * @author: wangweiguo
	 * @date: 2021/8/17
	 */
	@Inner
	@PostMapping("/inner/getNotLeaveExtendList")
	public TBusinessDataListVo getNotLeaveExtendList() {
		return this.businessEmployeeExtendInfoService.getNotLeaveExtendList();
	}

	/**
	 * @param
	 * @Description: 获取所有附属信息
	 * @Author: hgw
	 * @Date: 2021/8/18 16:46
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.util.Map < java.lang.String, com.yifu.cloud.v1.hrms.api.vo.basic.BusinessEmployeeExtendByLeave>>
	 **/
	@Inner
	@PostMapping("/inner/getInfoByLeaveMap")
	public Map<String, BusinessEmployeeExtendByLeave> getInfoByLeaveMap() {
		return this.businessEmployeeExtendInfoService.getInfoByLeaveMap();
	}


	/**
	 * @description: 校验数据权限
	 * @param query
	 * @return: com.yifu.cloud.v1.common.core.util.R
	 * @author: wangweiguo
	 * @date: 2021/8/11
	 */
	private R businessPowerCheck(THroBusinessUserQuery query) {
		YifuUser user = SecurityUtils.getUser();
		if (null == query){
			query = new THroBusinessUserQuery();
		}
		// 如果有姓名 按姓名查询  清空结算主体（产品要求结算主体和姓名查询互斥）
		// hrob2.0 去掉该判断，因为能查到不是b端的人员信息 --wwg 2021-08-12
//        if (Common.isNotNull(query.getEmpName()))
//            query.setSettleDomainId(null)
//            return R.success("success")

		List<String> settleDomainIds = new ArrayList<>();
		boolean flag =  !SecurityUtils.isHaveAllOrg(ServiceNameConstants.CLIENT_ID_HR_B, user);
		if (flag){
			settleDomainIds = user.getSettleIdList();
			if (Common.isEmpty(settleDomainIds)) {
				return R.failed(EmpBusinessConstants.noSettleDomainAuth);
			}
			query.setSettleDomainIds(settleDomainIds);
			// 无权限提示  有权限 按结算主体/项目ID 查询
			if (Common.isNotNull(query.getSettleDomainId()) && checkUserAuth(query.getSettleDomainId(), settleDomainIds)){
				return R.failed(EmpBusinessConstants.noSettleDomainAuth);
			}
			// 管理员权限特殊处理
		}else {
			if (Common.isEmpty(query.getSettleDomainId()) && Common.isEmpty(query.getDepartId())){
				return R.failed("项目和部门不可同时为空");
			}
		}
		if (Common.isNotNull(settleDomainIds)){
			query.setSettleDomainIds(settleDomainIds);
		}
		return R.ok();
	}

	/**
	 * 查看有无权限：无权限 true  有权限 false
	 * @Author fxj
	 * @Date 2020-09-04
	 * @param idStr
	 * @param settleDomainIds
	 * @return
	 **/
	public static boolean checkUserAuth(String idStr, List<String> settleDomainIds) {
		for (String id:settleDomainIds){
			if (id.equals(idStr)){
				return  false;
			}
		}
		return true;
	}

    /**
     * 查询-列表：内部服务调用，获取所有员工拓展表信息
     * @description: 查询-列表：内部服务调用，获取所有非离职员工拓展表信息
     * @return: R<List<TBusinessEmployeeExtendInfo>>
     * @author: wangweiguo
     * @date: 2021/8/25
     */
    @Inner
    @PostMapping("/inner/getAllExtendList")
    public TBusinessDataListVo getAllExtendList() {
		TBusinessDataListVo vo = new TBusinessDataListVo();
		List<TBusinessEmployeeExtendInfo> list = this.businessEmployeeExtendInfoService.list();
		vo.setExtendInfo(list);
        return vo;
    }

	/**
	 * 查询-列表：内部服务调用，根据电工编号查询扩展表信息
	 * @return: R<TBusinessEmployeeExtendInfo>
	 * @author: wangweiguo
	 * @date: 2021/8/31
	 */
	@Inner
	@PostMapping("/inner/getExtendByBusinessTelecomNumber")
	public TBusinessEmployeeExtendInfo getExtendByBusinessTelecomNumber(@RequestBody String businessTelecomNumber) {
		return this.businessEmployeeExtendInfoService.lambdaQuery()
				.eq(TBusinessEmployeeExtendInfo::getBusinessTelecomNumber, businessTelecomNumber)
				.last(CommonConstants.LAST_ONE_SQL)
				.one();
	}

	/**
	 * B端合同列表查询接口
	 * @Author fxj
	 * @Date 2020-08-25
	 * @param page
	 * @param contractBusinessPageVo
	 * @param flag  0 按3个月内到期提醒  1 不安提醒查询
	 * @return
	 **/
	@Operation(description = "B端合同列表查询接口（flag： 0-按3个月内到期提醒 1-不安提醒查询）")
	@GetMapping("/getContractBusinessPage")
	public R<IPage<EmpContractBusinessPageVo>> getContractBusinessPage(Page<EmpContractBusinessPageVo> page
			, EmpContractBusinessPageVo contractBusinessPageVo, Integer flag) {
		if (null == flag){
			flag = 1;
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null) {
			return R.failed("请登录!");
		}
		if (null == contractBusinessPageVo){
			contractBusinessPageVo =  new EmpContractBusinessPageVo();
		}
		contractBusinessPageVo.setIsObsolete(CommonConstants.ZERO_STRING);
		// 如果有姓名 按姓名查询  清空结算主体（产品要求结算主体和姓名查询互斥）
		if (Common.isNotNull(contractBusinessPageVo.getEmpName())){
			contractBusinessPageVo.setSettleDomain(null);
		}
		List<String> settleDomainIds = new ArrayList<>();
		if (!SecurityUtils.isHaveAllOrg(ServiceNameConstants.CLIENT_ID_HR_B, user)){
			settleDomainIds = user.getSettleIdList();
			if (Common.isEmpty(settleDomainIds)) {
				return R.failed(EmpBusinessConstants.noSettleDomainAuth);
			}
			if (Common.isNotNull(contractBusinessPageVo.getSettleDomain())){
				// 无权限提示  有权限 按结算主体/项目ID 查询
				if (checkUserAuth(contractBusinessPageVo.getSettleDomain(),settleDomainIds)){
					return R.failed(EmpBusinessConstants.noSettleDomainAuth);
				}
				settleDomainIds = null;
			}
			// 管理员权限特殊处理
		}else {
			if (Common.isEmpty(contractBusinessPageVo.getSettleDomain())){
				return new R<>(null);
			}
		}
		return new R<>(tEmployeeContractInfoService.getContractBusinessPage(page, contractBusinessPageVo, settleDomainIds, flag));
	}

	/**
	 * B端查询合同到期提醒数（查询3个月内到期的合同）
	 * @Author fxj
	 * @Date 2020-08-25
	 * @param
	 * @return
	 **/
	@Operation(description = "B端查询合同到期提醒数（查询3个月内到期的合同）")
	@GetMapping("/getContractBusinessAlertCount")
	public R<Integer> getContractBusinessAlertCount() {
		YifuUser user = SecurityUtils.getUser();
		if (user == null) {
			return R.failed("请登录!");
		}
		List<String> settleDomainIds = new ArrayList<>();
		if (!SecurityUtils.isHaveAllOrg(ServiceNameConstants.CLIENT_ID_HR_B, user)){
			settleDomainIds = user.getSettleIdList();
			if (settleDomainIds == null || settleDomainIds.isEmpty()) {
				return R.failed(EmpBusinessConstants.noSettleDomainAuth);
			}
		}
		return new R<>(tEmployeeContractInfoService.getContractBusinessAlertCount(settleDomainIds));
	}

	/**
	 * B端查询对应员工指定合同ID之外的其他合同信息
	 * @Author fxj
	 * @Date 2020-08-25
	 * @param empId
	 * @param contractId
	 * @return
	 **/
	@Operation(description = "B端查询对应员工指定合同ID之外的其他合同信息")
	@GetMapping("/getOtherContractBusinessInfo")
	public R<List<EmpContractBusinessPageVo>> getOtherContractBusinessInfo(@RequestParam(value = "empId")String empId,@RequestParam(value = "contractId", required = true)String contractId) {
		return new R<>(tEmployeeContractInfoService.getOtherContractBusinessInfo(empId,contractId));
	}

	/**
	 * @param businessTelecomNumber
	 * @Description: 根据电信编号，获取附属信息
	 * @Author: hgw
	 * @Date: 2021/8/18 17:06
	 * @return: com.yifu.cloud.v1.common.core.util.R<com.yifu.cloud.v1.hrms.api.entity.basic.TBusinessEmployeeExtendInfo>
	 **/
	@Operation(description = "根据电信编号，获取附属信息")
	@PostMapping("/getByBusinessTelecomNumber")
	public R<TBusinessEmployeeExtendInfo> getByBusinessTelecomNumber(@RequestParam String businessTelecomNumber) {
		return new R<>(businessEmployeeExtendInfoService.getByBusinessTelecomNumber(businessTelecomNumber));
	}

}
