package com.sunxung.factoring.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.ServiceException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.BeanUtilsProxy;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.entity.CommonVO;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.sys.ClientUserDO;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.sys.request.ClientUserQueryRequest;
import com.sunxung.factoring.entity.sys.request.DistributePMRequest;
import com.sunxung.factoring.entity.sys.request.DistributeRMRequest;
import com.sunxung.factoring.entity.sys.vo.ClientUserVO;
import com.sunxung.factoring.mapper.sys.ClientUserMapper;
import com.sunxung.factoring.service.sys.ClientUserService;
import com.sunxung.factoring.service.sys.UserService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.xml.bind.ValidationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ClientUserServiceImpl extends ServiceImpl<ClientUserMapper, ClientUserDO> implements
    ClientUserService {


  @Autowired
  private UserService userService;

  @Override
  public GridPage<ClientUserVO> pageList(ClientUserQueryRequest clientUserQueryRequest) {

    Page<Object> objects = PageHelper.startPage(clientUserQueryRequest.getPage(),
        clientUserQueryRequest.getRows());
    List<ClientUserVO> clientUserVOS = this.baseMapper.pageList(clientUserQueryRequest);
    if (!CollectionUtils.isEmpty(clientUserVOS)) {
      for (ClientUserVO vo : clientUserVOS) {
        vo.setList(this.baseMapper.getCompanyByClientUserId(vo.getId()));
      }
    }
    return new GridPage<>(clientUserQueryRequest.getRows(), clientUserQueryRequest.getPage(),
        objects.getTotal(), clientUserVOS);
  }

  /**
   * 认领
   *
   * @param clientUserId
   */
  @Override
  public void receive(Long clientUserId) {
    //认领
    Long id = ThreadLocalUtil.getUser().getId();
    ClientUserDO clientUserDO = this.baseMapper.selectById(clientUserId);
    if (clientUserDO == null) {
      throw new ValidatorException("400", "数据不存在请刷新页面");
    }
    clientUserDO.setProjectManager(id);
    this.baseMapper.updateById(clientUserDO);
  }


  @Override
  public void distributeProjectManager(Long clientUserId, Long projectManagerId) {
    ClientUserDO clientUserDO = this.baseMapper.selectById(clientUserId);
    if (clientUserDO == null) {
      throw new ValidatorException("400", "数据不存在请刷新页面");
    }
    clientUserDO.setProjectManager(projectManagerId);
    this.baseMapper.updateById(clientUserDO);
  }


  /**
   * 分配风险经理
   * @param clientUserId
   * @param riskManagerId
   */
  @Override
  public void distributeRiskManager(Long clientUserId, Long riskManagerId) {
    ClientUserDO clientUserDO = this.baseMapper.selectById(clientUserId);
    if (clientUserDO == null) {
      throw new ValidatorException("400", "数据不存在请刷新页面");
    }
    clientUserDO.setRiskManager(riskManagerId);
    this.baseMapper.updateById(clientUserDO);
  }


  @Override
  @Transactional
  public void distributeProjectManagers(DistributePMRequest distributePMRequest) {
    List<Long> userIds = distributePMRequest.getUserIds();
    if(!CollectionUtils.isEmpty(userIds)){
        for(Long id:userIds){
          ClientUserDO clientUserDO = this.baseMapper.selectById(id);
          if(clientUserDO!=null){
            clientUserDO.setProjectManager(distributePMRequest.getProjectManagerId());
            this.baseMapper.updateById(clientUserDO);
          }
        }
    }
  }

  @Override
  @Transactional
  public void distributeRiskManagers(DistributeRMRequest distributeRMRequest) {
    List<Long> userIds = distributeRMRequest.getUserIds();
    if(!CollectionUtils.isEmpty(userIds)){
      for(Long id:userIds){
        ClientUserDO clientUserDO = this.baseMapper.selectById(id);
        if(clientUserDO!=null){
          clientUserDO.setRiskManager(distributeRMRequest.getRiskManagerId());
          this.baseMapper.updateById(clientUserDO);
        }
      }
    }
  }

  /**
   *  查询项目经理
   * @param clientUserId
   * @return
   */
  @Override
  public List<CommonVO> getPMs(Long clientUserId) {
    if(clientUserId==null){
      List<User> userByRoleId = userService.findUserByRoleId(17L);
      List<CommonVO> commonVOs = BeanUtilsProxy.copyPropertiesList(userByRoleId, CommonVO.class);
      return commonVOs;
    }
    ClientUserDO clientUserDO = this.baseMapper.selectById(clientUserId);
    if(clientUserDO==null){
      throw new ValidatorException("400", "数据不存在请刷新页面");
    }
    Long orgId = clientUserDO.getOrgId();

    List<Long> userIdByOrgId = Lists.newArrayList();
    if(orgId!=null){
       userIdByOrgId = userService.findUserIdByOrgId(orgId);
    }
    List<User> userByRoleId = userService.findUserByRoleId(17L);
    if(!CollectionUtils.isEmpty(userIdByOrgId)){
        for(User u:userByRoleId){
          if(userIdByOrgId.indexOf(u.getId())<0){
             userByRoleId.remove(u);
          }
        }
    }
    List<CommonVO> commonVOs = BeanUtilsProxy.copyPropertiesList(userByRoleId, CommonVO.class);
    return commonVOs;
  }


  /**
   * 查询风险经理
   * @return
   */
  @Override
  public List<CommonVO> getRMs() {
    List<User> userByRoleId = userService.findUserByRoleId(6L);
    if(!CollectionUtils.isEmpty(userByRoleId)){
      List<CommonVO> commonVOS = BeanUtilsProxy.copyPropertiesList(userByRoleId, CommonVO.class);
      return commonVOS;
    }
    return null;
  }

  @Override
  @Transactional
  public void systemDistribute() throws ParseException {
    List<Long> list = com.google.common.collect.Lists.newArrayList(3088L,2L,3216L,3328L,3500L,3381L,3004L,1769L,2466L,256L,445L,1574L,2706L,2483L,744L,675L,546L);
    List<Long> list1 = com.google.common.collect.Lists.newArrayList(896L,914L,144L,1037L,1279L,1402L,1175L);
    List<Long> list2 = com.google.common.collect.Lists.newArrayList(2066L,2285L,2425L,2850L,2747L,1787L,1916L);

    Long xayyzx = 2L;  //西安运营中心
    Long zcglzx = 8L;     //资产管理中心
    Long shyyzx = 3L;     //上海运营中心
    Long szyyzx = 14L;  //深圳运营中心

    List<ClientUserDO> userList = new ArrayList<>();
    List<ClientUserDO> userList1 = new ArrayList<>();
    List<ClientUserDO> userList2 = new ArrayList<>();

    LambdaQueryWrapper<ClientUserDO> lambdaQueryWrapper = new LambdaQueryWrapper<ClientUserDO>();
    lambdaQueryWrapper.isNull(ClientUserDO::getProjectManager);
    List<ClientUserDO> allList = this.list(lambdaQueryWrapper);
    if(!CollectionUtils.isEmpty(allList)){
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

      for(ClientUserDO user:allList){
        Date gmtCreate = user.getGmtCreate();
        Date nowDate = new Date();
        String gmtCreateStr = simpleDateFormat.format(gmtCreate);
        String nowDateStr = simpleDateFormat.format(nowDate);
        Date gmtCreateResult = simpleDateFormat.parse(gmtCreateStr);
        Date nowDateResult = simpleDateFormat.parse(nowDateStr);
        if((nowDateResult.getTime()-gmtCreateResult.getTime())/1000L/60/60/24 <3){
              continue;
        }
        Long provinceId = user.getProvinceId();
        if(list.indexOf(provinceId)>=0){
          userList.add(user);
        }
        if(list1.indexOf(provinceId)>=0){
          userList1.add(user);
        }
        if(list2.indexOf(provinceId)>=0){
          userList2.add(user);
        }
      }
    }
    //分配
    if(!CollectionUtils.isEmpty(userList)){
      for(int i =0;i<userList.size();i++){
        ClientUserDO clientUserDO = userList.get(i);
        if(i%2==0){
          clientUserDO.setOrgId(xayyzx);
        }else{
          clientUserDO.setOrgId(zcglzx);
        }
        this.baseMapper.updateById(clientUserDO);
      }
    }
    //继续分配
    if(!CollectionUtils.isEmpty(userList1)){
      for(int i =0;i<userList1.size();i++){
        ClientUserDO clientUserDO = userList1.get(i);
        if(i%2==0){
          clientUserDO.setOrgId(shyyzx);
        }else{
          clientUserDO.setOrgId(zcglzx);
        }
        this.baseMapper.updateById(clientUserDO);
      }
    }
    //继续分配
    if(!CollectionUtils.isEmpty(userList2)){
      for(int i =0;i<userList1.size();i++){
        ClientUserDO clientUserDO = userList1.get(i);
        clientUserDO.setOrgId(szyyzx);
        this.baseMapper.updateById(clientUserDO);
      }
    }
  }
}
