package com.yd.csf.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ProjectEnum;
import com.yd.common.enums.TenantEnum;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiCsfClientUserService;
import com.yd.csf.feign.dto.csfclientuser.ApiCsfClientUserDTO;
import com.yd.csf.feign.enums.ClientRoleEnum;
import com.yd.csf.feign.request.csfclientuser.ApiCsfClientUserAddRequest;
import com.yd.csf.feign.request.csfclientuser.ApiCsfClientUserPageRequest;
import com.yd.csf.feign.response.csfclientuser.ApiCsfClientUserPageResponse;
import com.yd.csf.service.dto.query.QueryCsfClientUserDTO;
import com.yd.csf.service.model.CsfClientUser;
import com.yd.csf.service.model.PolicyFollow;
import com.yd.csf.service.service.ICsfClientUserService;
import com.yd.user.feign.client.clientuser.ApiClientUserFeignClient;
import com.yd.user.feign.request.clientuser.ApiClientUserConditionListRequest;
import com.yd.user.feign.response.clientuser.ApiClientUserDetailResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Slf4j
@Service
public class ApiCsfClientUserServiceImpl implements ApiCsfClientUserService {

    @Resource
    private ICsfClientUserService csfClientUserService;

    @Resource
    private ApiClientUserFeignClient apiClientUserFeignClient;

    /**
     * 分页查询-人员信息
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiCsfClientUserPageResponse>> page(ApiCsfClientUserPageRequest request) {
        return null;
    }


    /**
     * 新增-人员信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(ApiCsfClientUserAddRequest request) {
        if (request.getUserDTO() == null) {
            throw new BusinessException("人员基本信息不能为空");
        }
        ApiCsfClientUserDTO userDTO = request.getUserDTO();
        //校验手机号的唯一性
        List<CsfClientUser> csfClientUserList = csfClientUserService.queryList(QueryCsfClientUserDTO.builder()
                .phone(userDTO.getPhone())
                .isMy(false)
                .build());
        if (CollectionUtils.isNotEmpty(csfClientUserList)) {
            throw new BusinessException("手机号已经存在");
        }
        //手机号+租户ID+项目ID->查询中心客户端用户表用户记录
        ApiClientUserConditionListRequest conditionListRequest = new ApiClientUserConditionListRequest();
        //租户ID
        conditionListRequest.setTenantBizId(TenantEnum.YD.getTenantBizId());
        //项目ID
        conditionListRequest.setProjectBizId(ProjectEnum.CSF_PC.getProjectBizId());
        //手机号
        conditionListRequest.setPhone(userDTO.getPhone());
        //手机号+租户ID+项目ID->查询中心客户端用户表用户记录
        Result<List<ApiClientUserDetailResponse>> result = apiClientUserFeignClient.conditionList(conditionListRequest);
        ApiClientUserDetailResponse response = null;
        if (result.getCode() == 200 && CollectionUtils.isNotEmpty(result.getData())) {
            response = new ApiClientUserDetailResponse();
            List<ApiClientUserDetailResponse> responses = result.getData();
            response = responses.get(0);
        }
        //新增人员信息入库
        CsfClientUser csfClientUser = new CsfClientUser();
        BeanUtils.copyProperties(userDTO,csfClientUser);
        if (response != null) {
            //中心用户记录不为空，获取中心用户ID保存
            csfClientUser.setClientUserBizId(response.getClientUserBizId());
        }else {
            //中心用户记录为空，远程调用接口->创建中心用户 TODO

        }
        csfClientUser.setCsfClientUserBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_CSF_CLIENT_USER.getCode()));
        //绑定的客户端角色表表唯一业务ID列表（多个分号分隔）
        csfClientUser.setRoleBizIds(CollectionUtils.isNotEmpty(userDTO.getRoleBizIdList()) ? String.join(";",userDTO.getRoleBizIdList()) : "");
        //绑定的基本法配置表唯一业务ID列表（多个分号分隔）
        csfClientUser.setRuleBizIds(CollectionUtils.isNotEmpty(userDTO.getRuleBizIdList()) ? String.join(";",userDTO.getRuleBizIdList()) : "");
        csfClientUserService.saveOrUpdate(csfClientUser);

        //根据选择的角色，对应更新相关的表（转介人表、签单员表、合伙人表等）
        List<String> roleBizIdList = userDTO.getRoleBizIdList();
        if (roleBizIdList != null && roleBizIdList.contains(ClientRoleEnum.ZJR.getItemValue())) {
            // 处理转介人逻辑 => 更新或新增转介人信息 TODO
        }
        if (roleBizIdList != null && roleBizIdList.contains(ClientRoleEnum.QDY.getItemValue())) {
            // 处理签单员逻辑 => 更新或新增签单员信息 TODO
        }
        if (roleBizIdList != null && roleBizIdList.contains(ClientRoleEnum.HHR.getItemValue())) {
            // 处理合伙人逻辑 TODO
        }
        return null;
    }


}
