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.google.common.collect.Lists;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.entity.CommonVO;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.acceptance.AcceptanceBasicInfo;
import com.sunxung.factoring.entity.biddingManagement.BiddingBasicInfoHis;
import com.sunxung.factoring.entity.biddingManagement.CBiddingBasicInfo;
import com.sunxung.factoring.entity.businessmanagement.BusinessBasicInfo;
import com.sunxung.factoring.entity.businessmanagement.BusinessBasicInfoHistory;
import com.sunxung.factoring.entity.creditresolution.CreditResolution;
import com.sunxung.factoring.entity.invoicemanage.InvoiceBasicInfo;
import com.sunxung.factoring.entity.project.BusinessAssignee;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.ProjectCoreEnterprise;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractManagement;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContract;
import com.sunxung.factoring.entity.settlement.SettlementBasicInfo;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.*;
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.entity.underlying.UnderlyingBasicInfo;
import com.sunxung.factoring.mapper.project.BusinessProcessingLogMapper;
import com.sunxung.factoring.mapper.sys.ClientUserMapper;
import com.sunxung.factoring.service.acceptancesheet.AcceptanceBasicInfoService;
import com.sunxung.factoring.service.biddingManagement.ICBiddingBasicInfoService;
import com.sunxung.factoring.service.creditresolution.ICreditResolutionService;
import com.sunxung.factoring.service.invoicemanage.InvoiceBasicInfoService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.project.IProjectCoreEnterpriseService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.project.impl.ProjectInformationServiceImpl;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.settlement.SettlementBasicInfoService;
import com.sunxung.factoring.service.supplier.ICreditInvestigationInfoService;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
import com.sunxung.factoring.service.supplier.impl.SupplierInfoServiceImpl;
import com.sunxung.factoring.service.sys.ClientUserService;
import com.sunxung.factoring.service.sys.OrgService;
import com.sunxung.factoring.service.sys.PermissionService;
import com.sunxung.factoring.service.sys.UserService;
import org.apache.log4j.Logger;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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 {

  private Logger log = Logger.getLogger(ClientUserServiceImpl.class);

  @Autowired
  private UserService userService;
  @Autowired
  private OrgService orgService;
  @Autowired
  private PermissionService permissionService;
  @Autowired
  private BusinessProcessingLogService businessProcessingLogService;
  @Autowired
  private SalesContractService salesContractService;
  @Autowired
  private TaskService taskService;
  @Autowired
  private BusinessAssigneeService assigneeService;
  @Autowired
  private BusinessProcessingLogMapper processingLogMapper;
  @Autowired
  private PurchContractService purchContractService;
  @Autowired
  private AcceptanceBasicInfoService acceptanceBasicInfoService;
  @Autowired
  private SettlementBasicInfoService settlementBasicInfoService;
  @Autowired
  private InvoiceBasicInfoService invoiceBasicInfoService;
  @Autowired
  private ISupplierInfoService supplierInfoService;
  @Autowired
  private IProjectInformationService projectInformationService;
  @Autowired
  private IProjectCoreEnterpriseService projectCoreEnterpriseService;
  @Autowired
  private ICreditResolutionService creditResolutionService;
  @Autowired
  private ICBiddingBasicInfoService biddingBasicInfoService;


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

    List<Role> roles = ThreadLocalUtil.getUser().getRoles();
    Long userId = ThreadLocalUtil.getUserId();
    clientUserQueryRequest.setCurrentUserId(userId);
    String roleType = null;
    List<Long> orgIds = Lists.newArrayList();
    List<Long> userIds = Lists.newArrayList();
    orgIds.add(-1L);
    userIds.add(-1L);

    Permission per = permissionService.getByEname(ConstantConversionUtil.VIEW_ALL_CLIENT_USER);
    List<Long> pers = permissionService.getPermissionIdByUserId(ThreadLocalUtil.getUserId());
    if (CollectionUtil.isEmpty(pers)) {
      pers = Lists.newArrayList();
      pers.add(-1L);
    }
    boolean showAllData = false;
    if (pers.contains(per.getId())
        || ThreadLocalUtil.getUser().getLoginName().equals(ConstantConversionUtil.ADMINISTORIES)) {
      showAllData = true;
    }
    if (!showAllData) {
      //如果不是查看全员 则需要判断用户的角色
      List<UserOrgRel> userOrgRelList = userService.findOrgRelByUserId(userId);
      for (UserOrgRel userOrgRel : userOrgRelList) {
        if (userOrgRel.isUserIdentity()) {
          roleType = "projectCapital";
          orgIds.add(userOrgRel.getOrgId());
          // 如果是部门负责人，获取部门下所有人员Id
          List<Long> userIdList = userService.findUserIdByOrgId(userOrgRel.getOrgId());
          userIds.addAll(userIdList);
        }
      }
      if (StringUtil.isEmpty(roleType)) {
        for (Role role : roles) {
          if (role.getName().equals("业务经理")) {
            roleType = "projectManager";
            break;
          }
          if (role.getName().equals("风控经理")) {
            roleType = "riskManager";
            break;
          }
        }
      }
      clientUserQueryRequest.setRoleType(roleType);
      clientUserQueryRequest.setUserIds(userIds);
      clientUserQueryRequest.setOrgIds(orgIds);
    }
    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 BusinessException("400", "数据不存在请刷新页面");
    }
    clientUserDO.setProjectManager(id);
    this.baseMapper.updateById(clientUserDO);
  }


  @Transactional
  @Override
  public void distributeProjectManager(Long clientUserId, Long projectManagerId, boolean flag) {
    ClientUserDO clientUserDO = this.baseMapper.selectById(clientUserId);
    //Long projectManager = clientUserDO.getProjectManager();

    if (clientUserDO == null) {
      throw new BusinessException("400", "数据不存在请刷新页面");
    }
    clientUserDO.setProjectManager(projectManagerId);
    this.baseMapper.updateById(clientUserDO);
    if (flag) {
      changeProjectManagerAndBusiness(Lists.newArrayList(clientUserId),projectManagerId);
    }

  }


  public void changeProjectManagerAndBusiness(List<Long> clientUserIds, Long projectManagerId) {
    for (Long clientUserId : clientUserIds) {
      List<SupplierInfo> list = supplierInfoService.getByClientUserId(clientUserId);
      if (CollectionUtil.isNotEmpty(list)) {
        for (SupplierInfo s : list) {
           //移交供应商
          //supplierInfoTransfer(s.getId(), projectManagerId);
          List<ProjectInformation> projectInformationList = projectInformationService.lambdaQuery()
              .eq(ProjectInformation::getcSupplierInfoId, s.getId()).list();
          if (CollectionUtil.isNotEmpty(projectInformationList)) {
            for (ProjectInformation p : projectInformationList) {
             //移交项目
              // projectTransfer(p.getId(), projectManagerId);
              ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.getByProjectInfoId(
                  p.getId());
              //移交核心企业
              //ProjectCoreEnterpriseTransfer(projectCoreEnterprise.getId(), projectManagerId);
              //移交授信决议
              CreditResolution byProjectInformationId = creditResolutionService.getByProjectInformationId(
                  p.getId());
              if (byProjectInformationId != null) {
                shouxinTransferManager(byProjectInformationId.getId(), projectManagerId);
              }
              //招投标移交
              biddingBasicInfoTransfer(p.getBusinessNumber(),projectManagerId);
              //移交发票
              invoiceTransfer(p.getBusinessNumber(), projectManagerId);
            }
          }
        }
      }
    }
  }


  public void changeRiskManagerAndBusiness(List<Long> clientUserIds, Long riskManagerId) {
    for (Long clientUserId : clientUserIds) {
      List<SupplierInfo> list = supplierInfoService.getByClientUserId(clientUserId);
      if (CollectionUtil.isNotEmpty(list)) {
        for (SupplierInfo s : list) {
          //供应商移交
          supplierInfoTransfer(s.getId(), riskManagerId);
          List<ProjectInformation> projectInformationList = projectInformationService.lambdaQuery()
              .eq(ProjectInformation::getcSupplierInfoId, s.getId()).list();
          if (CollectionUtil.isNotEmpty(projectInformationList)) {
            for (ProjectInformation p : projectInformationList) {
              projectTransfer(p.getId(), riskManagerId);
              ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.getByProjectInfoId(
                  p.getId());
             // 移交核心企业
              projectCoreEnterpriseTransfer(projectCoreEnterprise.getId(), riskManagerId);
              //移交授信决议
              CreditResolution creditResolution = creditResolutionService.getByProjectInformationId(
                  p.getId());
              if (creditResolution != null) {
                shouxinTransferRisk(creditResolution.getId(), riskManagerId);
               }
//              //移交发票
//              invoiceTransfer(p.getBusinessNumber(), projectManagerId);
            }
          }
        }
      }
    }
  }

  /**
   * 招投标   移交---业务需要
   */
  private void  biddingBasicInfoTransfer(String businessNumber,Long userId){
    CBiddingBasicInfo one = biddingBasicInfoService.lambdaQuery()
        .eq(CBiddingBasicInfo::getBusinessNumber, businessNumber).one();
    if(one!=null){
      List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
          one.getId(), ConstantUtil.BIDDING_MANAGEMENT);
      if(CollectionUtil.isNotEmpty(businessProcessingLogs)){
        for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
          Task task = taskService.createTaskQuery()
              .taskId(businessProcessingLog.getHistoricTaskId())
              .singleResult();
          if (task == null) {
            log.error("--------------移交出现任务id查看不到确切任务，跳过循环执行下一次循环------------taskId="
                + businessProcessingLog.getHistoricTaskId());
            continue;
          }
          taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
              ConstantUtil.GUARANTEE_METHOD_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""), String.valueOf(userId));
          taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
              ConstantUtil.AWARD_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""), String.valueOf(userId));


          if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.GUARANTEE_METHOD_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))||
              businessProcessingLog.getTaskDefKey().equals(ConstantUtil.AWARD_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                String.valueOf(userId));
            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
            businessProcessingLog.setAssignee(userService.get(userId));
            processingLogMapper.updateAssigneeId(businessProcessingLog);
          }
        }
      }
    }
  }

  /**
   * 核心企业移交 移交 - 风险移交
   *
   * @param projectCoreEnterpriseId
   * @param userId
   */
  private void projectCoreEnterpriseTransfer(Long projectCoreEnterpriseId, Long userId) {

    List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
        projectCoreEnterpriseId, ConstantUtil.PROJECT_CORE_ENTERPRISE);
    if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
      for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
        Task task = taskService.createTaskQuery().taskId(businessProcessingLog.getHistoricTaskId())
            .singleResult();
        if(task==null){
          log.error("--------------移交出现任务id查看不到确切任务，跳过循环执行下一次循环------------taskId="+businessProcessingLog.getHistoricTaskId());
          continue;
        }
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.PROJECT_CORE_ENTERPRISE_APPROVAL_ADD_ASSIGNEE, String.valueOf(userId));

        //修改business_assignee
        // BusinessAssignee businessAssignee = assigneeService.getByBusiness(projectId, ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
        // businessAssignee.setAssigneeId(userId);
        //assigneeService.update(businessAssignee);
        if (businessProcessingLog.getTaskDefKey().equals(
            "project_core_approval_add")) {
          taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
              String.valueOf(userId));
          taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
          businessProcessingLog.setAssignee(userService.get(userId));
          processingLogMapper.updateAssigneeId(businessProcessingLog);
        }
      }
    }
  }

  /**
   * 供应商移交  --- 风险移交调用
   *
   * @param supplierInfoId
   * @param userId
   */
  private void supplierInfoTransfer(Long supplierInfoId, Long userId) {

    List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
        supplierInfoId, ConstantUtil.SUPPLIER_INFO);
    if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
      for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.DUE_DILIGENCE_ALLOCATION_ASSIGNEE, String.valueOf(userId));
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.FIRST_REVIEW_ASSIGNEE, String.valueOf(userId));
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.SECOND_REVIEW_ASSIGNEE, String.valueOf(userId));
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.DUE_DILIGENCE_CONFIRM_ASSIGNEE, String.valueOf(userId));
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.VIDEO_DUE_DILIGENCE_ASSIGNEE, String.valueOf(userId));

        //修改business_assignee
        // BusinessAssignee businessAssignee = assigneeService.getByBusiness(projectId, ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
        // businessAssignee.setAssigneeId(userId);
        //assigneeService.update(businessAssignee);
        if (businessProcessingLog.getTaskDefKey().equals(
            ConstantUtil.DUE_DILIGENCE_ALLOCATION_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, "")) ||
            businessProcessingLog.getTaskDefKey()
                .equals(ConstantUtil.FIRST_REVIEW_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, "")) ||
            businessProcessingLog.getTaskDefKey()
                .equals(ConstantUtil.SECOND_REVIEW_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, "")) ||
            businessProcessingLog.getTaskDefKey().equals(
                ConstantUtil.DUE_DILIGENCE_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, "")) ||
            businessProcessingLog.getTaskDefKey().equals(
                ConstantUtil.VIDEO_DUE_DILIGENCE_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
          taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
              String.valueOf(userId));
          taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
          businessProcessingLog.setAssignee(userService.get(userId));
          processingLogMapper.updateAssigneeId(businessProcessingLog);
        }
      }
    }
  }

  /**
   * 项目移交--风险移交调用
   *
   * @param projectId
   * @param userId
   */
  private void projectTransfer(Long projectId, Long userId) {

    List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
        projectId, ConstantUtil.PROJECT_INFORMATION);
    if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
      for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
        Task task = taskService.createTaskQuery().taskId(businessProcessingLog.getHistoricTaskId())
            .singleResult();
        if(task==null){
          log.error("--------------移交出现任务id查看不到确切任务，跳过循环执行下一次循环------------taskId="+businessProcessingLog.getHistoricTaskId());
          continue;
        }
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.PROJECT_APPROVAL_ADD_ASSIGNEE, String.valueOf(userId));

        //修改business_assignee
        // BusinessAssignee businessAssignee = assigneeService.getByBusiness(projectId, ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
        // businessAssignee.setAssigneeId(userId);
        //assigneeService.update(businessAssignee);
        if (businessProcessingLog.getTaskDefKey().equals(
            ConstantUtil.PROJECT_APPROVAL_ADD)) {
          taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
              String.valueOf(userId));
          taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
          businessProcessingLog.setAssignee(userService.get(userId));
          processingLogMapper.updateAssigneeId(businessProcessingLog);
        }
      }
    }
  }

  /**
   * 授信-------移交项目经理
   *
   * @param shouxinId
   * @param userId
   */
  private void shouxinTransferManager(Long shouxinId, Long userId) {
    List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
        shouxinId, ConstantUtil.CREDIT_RESOLUTION);
    if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
      for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
        Task task = taskService.createTaskQuery().taskId(businessProcessingLog.getHistoricTaskId())
            .singleResult();
        if(task==null){
          log.error("--------------移交出现任务id查看不到确切任务，跳过循环执行下一次循环------------taskId="+businessProcessingLog.getHistoricTaskId());
          continue;
        }
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.CREDIT_RESOLUTION_ADD_ASSIGNEE, String.valueOf(userId));
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.RECONSIDER_ADJUST_ADD_ASSIGNEE, String.valueOf(userId));

        //修改business_assignee
        // BusinessAssignee businessAssignee = assigneeService.getByBusiness(projectId, ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
        // businessAssignee.setAssigneeId(userId);
        //assigneeService.update(businessAssignee);
        if (businessProcessingLog.getTaskDefKey()
            .equals(ConstantUtil.CREDIT_RESOLUTION_ADD_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))
            ||
            businessProcessingLog.getTaskDefKey().equals(
                ConstantUtil.RECONSIDER_ADJUST_ADD_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
          taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
              String.valueOf(userId));
          taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
          businessProcessingLog.setAssignee(userService.get(userId));
          processingLogMapper.updateAssigneeId(businessProcessingLog);
        }
      }
    }
  }


  /**
   * 授信-------移交风险
   *
   * @param shouxinId
   * @param userId
   */
  private void shouxinTransferRisk(Long shouxinId, Long userId) {
    List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
        shouxinId, ConstantUtil.CREDIT_RESOLUTION);
    if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
      for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
        Task task = taskService.createTaskQuery().taskId(businessProcessingLog.getHistoricTaskId())
            .singleResult();
        if(task==null){
          log.error("--------------移交出现任务id查看不到确切任务，跳过循环执行下一次循环------------taskId="+businessProcessingLog.getHistoricTaskId());
          continue;
        }
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.CREDIT_RESOLUTION_APPROVAL_ASSIGNEE, String.valueOf(userId));
        taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
            ConstantUtil.RECONSIDER_ADJUST_APPROVAL_ASSIGNEE, String.valueOf(userId));

        //修改business_assignee
        // BusinessAssignee businessAssignee = assigneeService.getByBusiness(projectId, ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
        // businessAssignee.setAssigneeId(userId);
        //assigneeService.update(businessAssignee);
        if (businessProcessingLog.getTaskDefKey().equals(
            ConstantUtil.CREDIT_RESOLUTION_APPROVAL_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, "")) ||
            businessProcessingLog.getTaskDefKey().equals(
                ConstantUtil.RECONSIDER_ADJUST_APPROVAL_ASSIGNEE.replace(ConstantUtil.ASSIGNEE,
                    ""))) {
          taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
              String.valueOf(userId));
          taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
          businessProcessingLog.setAssignee(userService.get(userId));
          processingLogMapper.updateAssigneeId(businessProcessingLog);
        }
      }
    }
  }


  /**
   * 法务审核 --  这个应该不需要移交
   *
   * @param businessNumber
   * @param userId
   */
  private void salesContractTransfer(String businessNumber, Long userId) {
    CSalesContract salesContract = salesContractService.getByBusinessNumber(businessNumber);
    if (salesContract != null) {
      List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
          salesContract.getId(), ConstantUtil.SALES_CONTRACT);
      List<BusinessProcessingLog> changeLogs = businessProcessingLogService.listForNullValueOfEndTime(
          salesContract.getId(), ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS);
      if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
        for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
          taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
              ConstantUtil.SALES_CONTRACT_CREATE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
          //修改business_assignee
          BusinessAssignee businessAssignee = assigneeService.getByBusiness(salesContract.getId(),
              ConstantUtil.SALES_CONTRACT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
          businessAssignee.setAssigneeId(userId);
          assigneeService.update(businessAssignee);
          if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.SALES_CONTRACT_CREATE)) {
            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                String.valueOf(userId));
            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
            businessProcessingLog.setAssignee(userService.get(userId));
            processingLogMapper.updateAssigneeId(businessProcessingLog);
          }
        }
      }
      if (CollectionUtil.isNotEmpty(changeLogs)) {
        for (BusinessProcessingLog businessProcessingLog : changeLogs) {
          taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
              ConstantUtil.SALES_CONTRACT_CHANGE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
          //修改business_assignee
          BusinessAssignee businessAssignee = assigneeService.getByBusiness(salesContract.getId(),
              ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
          businessAssignee.setAssigneeId(userId);
          assigneeService.update(businessAssignee);
          if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.SALES_CONTRACT_CHANGE)) {
            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                String.valueOf(userId));
            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
            businessProcessingLog.setAssignee(userService.get(userId));
            processingLogMapper.updateAssigneeId(businessProcessingLog);
          }
        }
      }
    }
  }


  /**
   * 法务审核 --  这个应该不需要移交
   *
   * @param businessNumber
   * @param userId
   */
  private void purchContractTransfer(String businessNumber, Long userId) {
    List<PurchContractManagement> purchContractManagements = purchContractService.lambdaQuery()
        .eq(PurchContractManagement::getBusinessNumber, businessNumber).list();
    if (CollectionUtil.isNotEmpty(purchContractManagements)) {
      for (PurchContractManagement purchContractManagement : purchContractManagements) {
        List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
            purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT);
        List<BusinessProcessingLog> changeLogs = businessProcessingLogService.listForNullValueOfEndTime(
            purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS);
        if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
          for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.PURCH_CONTRACT_CREATE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.PURCH_CONTRACT_UNDERLINE_CONFIRM + ConstantUtil.ASSIGNEE,
                String.valueOf(userId));
            //修改business_assignee
            BusinessAssignee businessAssignee = assigneeService.getByBusiness(
                purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT,
                ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
            businessAssignee.setAssigneeId(userId);
            assigneeService.update(businessAssignee);
            if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.PURCH_CONTRACT_CREATE)
                || businessProcessingLog.getTaskDefKey()
                .equals(ConstantUtil.PURCH_CONTRACT_UNDERLINE_CONFIRM)) {
              taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              taskService.setOwner(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              businessProcessingLog.setAssignee(userService.get(userId));
              processingLogMapper.updateAssigneeId(businessProcessingLog);
            }
          }
        }
        if (CollectionUtil.isNotEmpty(changeLogs)) {
          for (BusinessProcessingLog businessProcessingLog : changeLogs) {
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.PURCH_CONTRACT_CHANGE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.PURCH_CONTRACT_CHANGE_SIGN_CONFIRM_UNDERLINE + ConstantUtil.ASSIGNEE,
                String.valueOf(userId));
            //修改business_assignee
            BusinessAssignee businessAssignee = assigneeService.getByBusiness(
                purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS,
                ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
            businessAssignee.setAssigneeId(userId);
            assigneeService.update(businessAssignee);
            if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.PURCH_CONTRACT_CHANGE)
                || businessProcessingLog.getTaskDefKey()
                .equals(ConstantUtil.PURCH_CONTRACT_CHANGE_SIGN_CONFIRM_UNDERLINE)) {
              taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              taskService.setOwner(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              businessProcessingLog.setAssignee(userService.get(userId));
              processingLogMapper.updateAssigneeId(businessProcessingLog);
            }
          }
        }
      }
    }
  }


  /**
   * 法务审核 --  这个应该不需要移交
   *
   * @param businessNumber
   * @param userId
   */
  private void acceptanceTransfer(String businessNumber, Long userId) {
    List<AcceptanceBasicInfo> acceptanceBasicInfos = acceptanceBasicInfoService.lambdaQuery()
        .eq(AcceptanceBasicInfo::getBusinessNumber, businessNumber).list();
    if (CollectionUtil.isNotEmpty(acceptanceBasicInfos)) {
      for (AcceptanceBasicInfo acceptanceBasicInfo : acceptanceBasicInfos) {
        List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
            acceptanceBasicInfo.getId(), ConstantUtil.ACCEPTANCE_SHEET);
        if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
          for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.ACCEPTANCE_SHEET_ASSIGNEE, String.valueOf(userId));
            //修改business_assignee
            BusinessAssignee businessAssignee = assigneeService.getByBusiness(
                acceptanceBasicInfo.getId(), ConstantUtil.ACCEPTANCE_SHEET,
                ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
            businessAssignee.setAssigneeId(userId);
            assigneeService.update(businessAssignee);
            if (businessProcessingLog.getTaskDefKey().equals(
                ConstantUtil.ACCEPTANCE_SHEET_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
              taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              taskService.setOwner(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              businessProcessingLog.setAssignee(userService.get(userId));
              processingLogMapper.updateAssigneeId(businessProcessingLog);
            }
          }
        }
      }
    }
  }

  /**
   * 法务审核 --  这个应该不需要移交
   *
   * @param businessNumber
   * @param userId
   */
  private void settlementTransfer(String businessNumber, Long userId) {
    List<SettlementBasicInfo> settlementBasicInfos = settlementBasicInfoService.lambdaQuery()
        .eq(SettlementBasicInfo::getBusinessNumber, businessNumber).list();
    if (CollectionUtil.isNotEmpty(settlementBasicInfos)) {
      for (SettlementBasicInfo settlementBasicInfo : settlementBasicInfos) {
        List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
            settlementBasicInfo.getId(), ConstantUtil.BILL_BASIC_INFORMATION);
        if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
          for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.BILL_ASSIGNEE, String.valueOf(userId));
            //修改business_assignee
            BusinessAssignee businessAssignee = assigneeService.getByBusiness(
                settlementBasicInfo.getId(), ConstantUtil.BILL_BASIC_INFORMATION,
                ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
            businessAssignee.setAssigneeId(userId);
            assigneeService.update(businessAssignee);
            if (businessProcessingLog.getTaskDefKey().equals("bill_create")) {
              taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              taskService.setOwner(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              businessProcessingLog.setAssignee(userService.get(userId));
              processingLogMapper.updateAssigneeId(businessProcessingLog);
            }
          }
        }
      }
    }
  }

  /**
   * 发票管理 -- 移交 业务经理
   *
   * @param businessNumber
   * @param userId
   */
  private void invoiceTransfer(String businessNumber, Long userId) {
    List<InvoiceBasicInfo> invoiceAudiList = invoiceBasicInfoService.lambdaQuery()
        .eq(InvoiceBasicInfo::getBusinessNumber, businessNumber).list();
    if (CollectionUtil.isNotEmpty(invoiceAudiList)) {
      for (InvoiceBasicInfo invoiceBasicInfo : invoiceAudiList) {
        List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(
            invoiceBasicInfo.getId(), "invoiceManager");
        if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
          for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
            Task task = taskService.createTaskQuery().taskId(businessProcessingLog.getHistoricTaskId())
                .singleResult();
            if(task==null){
              log.error("--------------移交出现任务id查看不到确切任务，跳过循环执行下一次循环------------taskId="+businessProcessingLog.getHistoricTaskId());
              continue;
            }
            taskService.setVariable(businessProcessingLog.getHistoricTaskId(),
                ConstantUtil.SALE_INVOICE_CREATE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
            BusinessAssignee businessAssignee = assigneeService.getByBusiness(
                invoiceBasicInfo.getId(), ConstantUtil.INVOICE,
                ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
            if (businessAssignee != null) {
              businessAssignee.setAssigneeId(userId);
              assigneeService.update(businessAssignee);
            }
            if (businessProcessingLog.getTaskDefKey()
                .equals(ConstantUtil.SALE_INVOICE_APPROVAL_CANDIDATE)) {
              taskService.setAssignee(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              taskService.setOwner(businessProcessingLog.getHistoricTaskId(),
                  String.valueOf(userId));
              businessProcessingLog.setAssignee(userService.get(userId));
              processingLogMapper.updateAssigneeId(businessProcessingLog);
            }
          }
        }
      }
    }
  }


  /**
   * 分配风险经理-- 同时移交这个客户产生的在途数据
   *
   * @param clientUserId
   * @param riskManagerId
   */
  @Transactional
  @Override
  public void distributeRiskManager(Long clientUserId, Long riskManagerId) {
    ClientUserDO clientUserDO = this.baseMapper.selectById(clientUserId);
    if (clientUserDO == null) {
      throw new BusinessException("400", "数据不存在请刷新页面");
    }
    clientUserDO.setRiskManager(riskManagerId);
    this.baseMapper.updateById(clientUserDO);
    changeRiskManagerAndBusiness(Lists.newArrayList(clientUserId),riskManagerId);
  }


  @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);
        }
      }
      //分配项目经理
      changeProjectManagerAndBusiness(userIds,distributePMRequest.getProjectManagerId());
    }
  }

  @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);
        }
      }
      //分配项目经理
      changeRiskManagerAndBusiness(userIds,distributeRMRequest.getRiskManagerId());
    }
  }

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

    List<Long> userIdByOrgId = Lists.newArrayList();
    if (orgId != null) {
      userIdByOrgId = userService.findUserIdByOrgId(orgId);
    }
    List<User> userByRoleId = userService.findUserByRoleName("业务经理");
    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 = orgService.findByName("西安运营中心").getId();    //西安运营中心
    Long zcglzx = orgService.findByName("资产管理中心").getId();    //资产管理中心
    Long shyyzx = orgService.findByName("上海运营中心").getId();    //上海运营中心
    Long szyyzx = orgService.findByName("深圳运营中心").getId();
    ;   //深圳运营中心

    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);
      }
    }
  }

  @Override
  public void resetPassword(Long clientUserId) {
    lambdaUpdate().eq(ClientUserDO::getId, clientUserId)
        .set(ClientUserDO::getPassword, "686650D2C058A32CA4990FF17362DE795051EF7CC60A8158BF986087")
        .update();
  }
}
