package com.gree.mall.miniapp.logic.workorder;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gree.mall.miniapp.bean.order.WorkerTeamBean;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.bean.workorder.*;
import com.gree.mall.miniapp.commonmapper.workorder.OrderBaseCMapper;
import com.gree.mall.miniapp.enums.ExamineStatusEnum;
import com.gree.mall.miniapp.enums.StateEnum;
import com.gree.mall.miniapp.enums.UserTypeEnum;
import com.gree.mall.miniapp.enums.WebsitAttrEnum;
import com.gree.mall.miniapp.enums.workorder.AppraiseStatusEnum;
import com.gree.mall.miniapp.enums.workorder.OrderBaseStatusEnum;
import com.gree.mall.miniapp.enums.workorder.OrderFlagEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.outside.WorkOrderApiLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class OrderBaseLogic {

    private final PgOrderBaseService pgOrderBaseService;
    private final PgOrderFlagService pgOrderFlagService;
    private final CommonLogic commonLogic;
    private final WorkOrderApiLogic workOrderApiLogic;
    private final OrderLogLogic orderLogLogic;
    private final OrderFlagLogic orderFlagLogic;
    private final OrderSmallTypeService orderSmallTypeService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final OrderBaseCMapper orderBaseCMapper;
    private final PgOrderProductService pgOrderProductService;
    private final UserService userService;
    private final AdminWebsitService adminWebsitService;
    private final WorkerTeamService workerTeamService;
    private final WebsitUserService websitUserService;

    /**
     * 工单状态统计
     * @return
     */
    public CountOrderStatusBean countOrderStatus(String pgIncreOrderId,Boolean isYb,Boolean isWb){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        CountOrderStatusBean countOrderStatusBean = orderBaseCMapper.countOrderStatus(currentCompanyWechat.getUserId(),pgIncreOrderId,isYb,isWb,currentCompanyWechat.getCompanyWechatId());
        CountOrderStatusBean countOrderStatusBean2 = orderBaseCMapper.countPartsApply(currentCompanyWechat.getUserId());
        if(countOrderStatusBean2 != null) {
            countOrderStatusBean.setPing(countOrderStatusBean2.getPing());
            countOrderStatusBean.setPend(countOrderStatusBean2.getPend());
        }
        return countOrderStatusBean;
    }

    /**
     * 未来7天的日程统计
     * @return
     */
    public MySchedule7Day mySchedule(){
        MySchedule7Day mySchedule7Day = new MySchedule7Day();

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        Date startTime = DateUtil.beginOfDay(new Date());
        Date endTime = DateUtil.endOfDay(DateUtil.offsetDay(startTime,6));

        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        DateUtils.getWeekDay();
        //星期未来7天
        List<String> weekList = Lists.newArrayList(
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 0)),
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 1)),
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 2)),
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 3)),
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 4)),
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 5)),
                DateUtils.dateToWeek(DateUtil.offsetDay(new Date(), 6))
        );
        mySchedule7Day.setWeekList(weekList);
        //日期未来7天
        List<String> dayList = Lists.newArrayList(
                sdf.format(DateUtil.offsetDay(new Date(), 0)),
                sdf.format(DateUtil.offsetDay(new Date(), 1)),
                sdf.format(DateUtil.offsetDay(new Date(), 2)),
                sdf.format(DateUtil.offsetDay(new Date(), 3)),
                sdf.format(DateUtil.offsetDay(new Date(), 4)),
                sdf.format(DateUtil.offsetDay(new Date(), 5)),
                sdf.format(DateUtil.offsetDay(new Date(), 6))
        );
        mySchedule7Day.setDayList(dayList);

        List<String> orderBaseIds = pgOrderWorkerService.lambdaQuery()
                .eq(PgOrderWorker::getWorkerId, currentCompanyWechat.getUserId())
                .list().stream().map(PgOrderWorker::getOrderBaseId).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(orderBaseIds)){
            return mySchedule7Day;
        }
        List<PgOrderBase> list = pgOrderBaseService
                .lambdaQuery().between(PgOrderBase::getAppointmentTime, startTime, endTime)
                .in(PgOrderBase::getId, orderBaseIds)
                .list();

        List<Long> djdList = Lists.newArrayList(
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.beginOfDay(new Date()),DateUtil.endOfDay(new Date())),
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),1),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),1)),
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),2),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),2)),
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),3),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),3)),
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),4),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),4)),
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),5),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),5)),
                scheduleSupply(list,OrderBaseStatusEnum.DJD,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),6),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),6))
                );

        List<Long> fwzList = Lists.newArrayList(
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.beginOfDay(new Date()),DateUtil.endOfDay(new Date())),
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),1),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),1)),
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),2),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),2)),
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),3),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),3)),
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),4),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),4)),
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),5),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),5)),
                scheduleSupply(list,OrderBaseStatusEnum.FWZ,DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),6),DateUtil.offsetDay(DateUtil.endOfDay(new Date()),6))
        );

        mySchedule7Day.setDjdList(djdList);
        mySchedule7Day.setFwzList(fwzList);
        return mySchedule7Day;
    }

    private long scheduleSupply(List<PgOrderBase> list,OrderBaseStatusEnum orderBaseStatusEnum,Date startTime,Date endTime){
        long count = list.stream()
                .filter(v -> StringUtils.equals(v.getOrderStatus(), orderBaseStatusEnum.getKey()))
                .filter(v -> v.getAppointmentTime() != null && v.getAppointmentTime().getTime() >= startTime.getTime() && v.getAppointmentTime().getTime() <= endTime.getTime())
                .count();
        return count;
    }

    /**
     * 工单小类
     * @return
     */
    public List<OrderSmallType> orderSmallTypeList(){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        List<OrderSmallType> list = orderSmallTypeService.lambdaQuery()
                .eq(OrderSmallType::getStatus,true)
                .eq(OrderSmallType::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                .orderByAsc(OrderSmallType::getSortNum).list();
        return list;
    }

    /**
     * 工单列表
     * @param byDay 1=今天 2=明天 3=其他
     * @param startTime
     * @param endTime
     * @return
     */
    public IPage<OrderBaseVO> list(String keyword,String pgIncreOrderId,Boolean isYb,Boolean isWb,OrderBaseStatusEnum orderBaseStatusEnum,
                                   Integer byDay,String startTime,String endTime,Integer pageNum,Integer pageSize){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        if(!StringUtils.equals(currentCompanyWechat.getUser().getType(),UserTypeEnum.WORKER.getKey())){
            return new Page<>(pageNum,pageSize);
        }
        List<String> orderBaseIds = pgOrderWorkerService.lambdaQuery()
                    .eq(PgOrderWorker::getWorkerId, currentCompanyWechat.getUserId())
                    .list().stream().map(PgOrderWorker::getOrderBaseId).distinct().collect(Collectors.toList());

        if(byDay != null){
            if(byDay == 1) {
                startTime = DateUtil.formatDateTime(DateUtil.beginOfDay(new Date()));
                endTime = DateUtil.formatDateTime(DateUtil.endOfDay(new Date()));
            }else if(byDay == 2){
                startTime = DateUtil.formatDateTime(DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),1));
                endTime = DateUtil.formatDateTime(DateUtil.offsetDay(DateUtil.endOfDay(new Date()),1));
            }else if(byDay == 3){
                startTime = DateUtil.formatDateTime(DateUtil.beginOfDay(new Date()));
                endTime = DateUtil.formatDateTime(DateUtil.offsetDay(DateUtil.endOfDay(new Date()),1));
            }
        }
        List<String> orderStatusList = new ArrayList<>();
        String orderStatus = orderBaseStatusEnum != null ? orderBaseStatusEnum.getKey() : null;
        if(StringUtils.equals(orderStatus, OrderBaseStatusEnum.YWG.getKey())){
            orderStatusList.add(orderStatus);
            orderStatusList.add(OrderBaseStatusEnum.YJS.getKey());
        }else if(StringUtils.equals(orderStatus,OrderBaseStatusEnum.YCD.getKey())){
            //异常单，不能通过工单状态字段去查，所以这里留空
            orderStatusList.clear();
        } else if(orderStatus != null){
            orderStatusList.add(orderStatus);
        }

        if(StringUtils.equals(orderStatus, OrderBaseStatusEnum.FWZ.getKey())){
            orderStatusList.add(OrderBaseStatusEnum.FWZ.getKey());
            orderStatusList.add(OrderBaseStatusEnum.GCSZT.getKey());
            orderStatusList.add(OrderBaseStatusEnum.BFWG.getKey());
        }

        Page page = pgOrderBaseService.lambdaQuery()
                .eq(PgOrderBase::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .ne(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.YQX.getKey())
                .ne(isYb != null && isYb,PgOrderBase::getPgIncreOrderId,"")
                .ne(isWb != null && isWb,PgOrderBase::getRpProjectRepairId,"")
                .eq(StringUtils.isNotBlank(pgIncreOrderId),PgOrderBase::getPgIncreOrderId,pgIncreOrderId)
                .and(v -> v.eq(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.DQD.getKey())
                        .or().in(CollectionUtils.isNotEmpty(orderBaseIds),PgOrderBase::getId,orderBaseIds))
                .and(StringUtils.isNotBlank(keyword),
                        v -> v.like(PgOrderBase::getId,keyword).or()
                                .like(PgOrderBase::getUserName,keyword).or()
                                .like(PgOrderBase::getOrderSmallTypeText,keyword).or()
                                .like(PgOrderBase::getUserMobile,keyword).or()
                                .like(PgOrderBase::getAddress,keyword))
                .in(CollectionUtils.isNotEmpty(orderStatusList), PgOrderBase::getOrderStatus, orderStatusList)
                .eq(StringUtils.equals(orderStatus, OrderBaseStatusEnum.YCD.getKey()),PgOrderBase::getIsException,true)
                .between(!StringUtils.equals(orderStatus, OrderBaseStatusEnum.YWG.getKey())
                        && StringUtils.isNoneBlank(startTime, endTime) && (byDay == null || byDay != 3), PgOrderBase::getDispatchTime, startTime, endTime)
                .notBetween(!StringUtils.equals(orderStatus, OrderBaseStatusEnum.YWG.getKey())
                        && StringUtils.isNoneBlank(startTime, endTime) && byDay != null && byDay == 3, PgOrderBase::getDispatchTime, startTime, endTime)

                .between(StringUtils.equals(orderStatus, OrderBaseStatusEnum.YWG.getKey())
                        && StringUtils.isNoneBlank(startTime, endTime) && (byDay == null || byDay != 3), PgOrderBase::getOverTime, startTime, endTime)
                .notBetween(StringUtils.equals(orderStatus, OrderBaseStatusEnum.YWG.getKey())
                        && StringUtils.isNoneBlank(startTime, endTime) && byDay != null && byDay == 3, PgOrderBase::getOverTime, startTime, endTime)

                .orderByDesc(!StringUtils.equals(orderStatus,OrderBaseStatusEnum.YWG.getKey()) && !StringUtils.equals(orderStatus,OrderBaseStatusEnum.DQD.getKey()),PgOrderBase::getDispatchTime)
                .orderByDesc(StringUtils.equals(orderStatus,OrderBaseStatusEnum.YWG.getKey()),PgOrderBase::getOverTime)
                .orderByDesc(StringUtils.equals(orderStatus,OrderBaseStatusEnum.DQD.getKey()),PgOrderBase::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<OrderBaseVO> orderBaseVOS = BeanUtil.copyToList(page.getRecords(), OrderBaseVO.class);

        //服务单标识
        List<String> orderIds = orderBaseVOS
                .stream()
                .map(OrderBaseVO::getId)
                .collect(Collectors.toList());
        List<AdminWebsit> adminWebsits = new ArrayList<>();
        Map<String, String> adminWebsitMap = new HashMap<>();

        if (CollectionUtil.isNotEmpty(orderBaseVOS)) {
            adminWebsits = adminWebsitService.lambdaQuery()
                    .eq(AdminWebsit::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                    .in(AdminWebsit::getWebsitId, orderBaseVOS.stream().map(OrderBaseVO::getWebsitId).collect(Collectors.toList()))
                    .list();
        }

        if (CollectionUtil.isNotEmpty(adminWebsits)) {
            adminWebsitMap = adminWebsits.stream().collect(Collectors.toMap(AdminWebsit::getWebsitId, AdminWebsit::getAttr));
        }

        Map<String, List<PgOrderFlag>> mapList = this.getOrderFlags(orderIds);
        for (OrderBaseVO orderBaseVO : orderBaseVOS) {
            orderBaseVO.setOrderFlags(mapList.get(orderBaseVO.getId()));
            //明细
            orderBaseVO.setPgOrderProducts(
                pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId,orderBaseVO.getId()).list()
            );
            //待抢单状态隐藏
            if(StringUtils.equals(orderBaseVO.getOrderStatus(),OrderBaseStatusEnum.DQD.getKey())){
                orderBaseVO.setUserMobile(orderBaseVO.getUserMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                orderBaseVO.setAddress(orderBaseVO.getProvince()+orderBaseVO.getCity()+orderBaseVO.getArea()+orderBaseVO.getStreet()+"****");
            }
            final String attr = adminWebsitMap.get(orderBaseVO.getWebsitId());
            if (StringUtils.isNotBlank(attr)
                    && attr.equals(WebsitAttrEnum.SELF.getKey())
                    && "安装, 拆移机".contains(orderBaseVO.getOrderSmallTypeText())) {
                orderBaseVO.setNeedSlave(true);
            }
        }
        page.setRecords(orderBaseVOS);
        return page;
    }


    /**
     * 客户的工单列表
     * @param flag 1=待预约 2=服务中 3=待评价 4=已完成
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<OrderBaseVO> list2(String pgIncreOrderId,Boolean isYb,Boolean isWb,Integer flag, Integer pageNum,Integer pageSize){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        LambdaQueryChainWrapper<PgOrderBase> qw = pgOrderBaseService.lambdaQuery();
        if(flag != null){
            if(flag == 1) {
                qw.eq(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.DYY.getKey());
            }else if(flag == 2){
                qw.eq(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.FWZ.getKey());
            }else if(flag == 3){
                qw.eq(PgOrderBase::getAppraiseStatus,AppraiseStatusEnum.N.getKey())
                        .in(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.YWG.getKey(),OrderBaseStatusEnum.YWG.getKey(),OrderBaseStatusEnum.YJS.getKey());
            }else if(flag == 4){
                qw.ne(PgOrderBase::getAppraiseStatus,AppraiseStatusEnum.N.getKey())
                        .in(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.YWG.getKey(),OrderBaseStatusEnum.YWG.getKey(),OrderBaseStatusEnum.YJS.getKey());
            }
        }
        if(StringUtils.isBlank(currentCompanyWechat.getUser().getMobile())){
            return new Page<>(pageNum,pageSize);
        }
        Page page = qw
                .and(v -> v.eq(PgOrderBase::getUserMobile, currentCompanyWechat.getUser().getMobile()).or()
                    .eq(PgOrderBase::getUserMobile2, currentCompanyWechat.getUser().getMobile()).or().eq(PgOrderBase::getUserId,currentCompanyWechat.getUserId()))
                .ne(isYb != null && isYb,PgOrderBase::getPgIncreOrderId,"")
                .ne(isWb != null && isWb,PgOrderBase::getRpProjectRepairId,"")
                .eq(StringUtils.isNotBlank(pgIncreOrderId),PgOrderBase::getPgIncreOrderId,pgIncreOrderId)
                .eq(PgOrderBase::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .orderByDesc(PgOrderBase::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<OrderBaseVO> orderBaseVOS = BeanUtil.copyToList(page.getRecords(), OrderBaseVO.class);
        for (OrderBaseVO orderBaseVO : orderBaseVOS) {
            //明细
            orderBaseVO.setPgOrderProducts(
                    pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId,orderBaseVO.getId()).list()
            );
        }
        page.setRecords(orderBaseVOS);
        return page;
    }

    /**
     * 服务单详情
     * @param orderBaseId
     * @return
     */
    public PgOrderBaseDetailVO detail(String orderBaseId){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        String userId = currentCompanyWechat.getUserId();

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        PgOrderBaseDetailVO pgOrderBaseDetailVO = BeanUtil.copyProperties(pgOrderBase, PgOrderBaseDetailVO.class);
        //师傅
        List<PgOrderWorker> list = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, orderBaseId).list();
//        if(list.stream().filter(v -> StringUtils.equals(v.getWorkerId(),userId)).count() == 0 && !pgOrderBase.getIsQd()){
//            throw new RemoteServiceException(ResponseHelper.NOT_PERMISSION,"暂无权限访问");
//        }
        //工单机型
        List<PgOrderProduct> list2 = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, orderBaseId).list();
        pgOrderBaseDetailVO.setPgOrderWorkers(list);
        pgOrderBaseDetailVO.setPgOrderProducts(list2);
        //服务流程
        if(StringUtils.isNotBlank(pgOrderBase.getWorkerId())){
            pgOrderBaseDetailVO.setServiceFlag(2);
        }
        if(StringUtils.equals(pgOrderBase.getOrderStatus(),OrderBaseStatusEnum.FWZ.getKey())){
            pgOrderBaseDetailVO.setServiceFlag(3);
        }
        if(OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())){
            pgOrderBaseDetailVO.setServiceFlag(4);
        }
        if(OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus()) && !StringUtils.equals(pgOrderBase.getAppraiseStatus(),AppraiseStatusEnum.N.getKey())){
            pgOrderBaseDetailVO.setServiceFlag(5);
        }
        //待抢单状态隐藏
        if(StringUtils.equals(pgOrderBaseDetailVO.getOrderStatus(),OrderBaseStatusEnum.DQD.getKey())){
            pgOrderBaseDetailVO.setUserMobile(pgOrderBaseDetailVO.getUserMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            pgOrderBaseDetailVO.setAddress(pgOrderBaseDetailVO.getProvince()+pgOrderBaseDetailVO.getCity()+pgOrderBaseDetailVO.getArea()+pgOrderBaseDetailVO.getStreet()+"****");
        }
        //服务单标记
        pgOrderBaseDetailVO.setPgOrderFlags(orderFlagLogic.list(orderBaseId));

        final AdminWebsit adminWebsit = adminWebsitService.getById(pgOrderBase.getWebsitId());
        if (Objects.nonNull(adminWebsit)) {
            if (adminWebsit.getAttr().equals(WebsitAttrEnum.SELF.getKey())
                    && "安装, 拆移机".contains(pgOrderBase.getOrderSmallTypeText())) {
                pgOrderBaseDetailVO.setNeedSlave(true);
            }
        }
        return pgOrderBaseDetailVO;
    }



    /**
     * 查询服务单标识-列表
     */
    public Map<String, List<PgOrderFlag>> getOrderFlags(List<String> orderBaseIds) {
        if (CollectionUtils.isEmpty(orderBaseIds)) {
            return Collections.emptyMap();
        }
        return pgOrderFlagService.lambdaQuery()
                .in(PgOrderFlag::getOrderBaseId, orderBaseIds)
                .orderByAsc(PgOrderFlag::getSortNum)
                .list()
                .stream()
                .collect(Collectors.groupingBy(PgOrderFlag::getOrderBaseId));
    }

    //public Map<String,Integer>

    /**
     * 创建工单
     * @param orderAddBeanDTO
     */
    public void add(OrderAddBeanDTO orderAddBeanDTO){
        workOrderApiLogic.createOrder(orderAddBeanDTO);
    }


    /**
     * 接单确认
     * @param orderBaseId
     * @param workerList
     */
    public void rece(String orderBaseId, List<String> workerList) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        PgOrderWorker one = pgOrderWorkerService.lambdaQuery()
                .eq(PgOrderWorker::getOrderBaseId, orderBaseId)
                .eq(PgOrderWorker::getWorkerId, currentCompanyWechat.getUserId())
                .one();
        if (one == null) {
            throw new RemoteServiceException("暂无权限接单");
        }
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if (!(StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.DJD.getKey())
                || StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.DSM.getKey())
                || StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.YZP.getKey())
        )) {
            throw new RemoteServiceException("当前状态不可接单");
        }

        final AdminWebsit adminWebsit = adminWebsitService.getById(pgOrderBase.getWebsitId());

        if (adminWebsit.getAttr().equals(WebsitAttrEnum.SELF.getKey())
                && "安装, 拆移机".contains(pgOrderBase.getOrderSmallTypeText())
                && CollectionUtil.isEmpty(workerList)) {
            throw new RemoteServiceException("工单的类型必须至少选一个小工");
        }

        StringBuilder joinSlaveStr = new StringBuilder();
        if (CollectionUtil.isNotEmpty(workerList)) {
            joinSlaveStr.append(", 辅助工程师");
            List<PgOrderWorker> orderWorkerList = new ArrayList<>();
            for (String workerId : workerList) {
                final User user = userService.getById(workerId);
                PgOrderWorker orderWorker = new PgOrderWorker();
                orderWorker.setOrderBaseId(pgOrderBase.getId())
                        .setWebsitId(pgOrderBase.getWebsitId())
                        .setWebsitName(pgOrderBase.getWebsitName())
                        .setWorkerId(workerId)
                        .setWorkerName(Objects.nonNull(user) ? user.getNickName() : "")
                        .setWorkerMobile(Objects.nonNull(user) ? user.getMobile() : "")
                        .setWorkerIdcard(Objects.nonNull(user) ? user.getIdCard() : "")
                        .setWorkerNumber(Objects.nonNull(user) ? user.getWorkerNumber() : "")
                        .setIsMaster(false);

                orderWorkerList.add(orderWorker);
                joinSlaveStr.append("【").append(orderWorker.getWorkerName()).append("】");
            }
            // 清空小工
            pgOrderWorkerService.lambdaUpdate()
                    .eq(PgOrderWorker::getOrderBaseId, pgOrderBase.getId())
                    .eq(PgOrderWorker::getIsMaster, false)
                    .remove();
            pgOrderWorkerService.saveBatch(orderWorkerList);
        }


        pgOrderBase.setOrderStatus(OrderBaseStatusEnum.FWZ.getKey());
        pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.FWZ.getRemark());
        pgOrderBase.setWorkerReceTime(new Date());
        pgOrderBase.updateById();

        orderLogLogic.addLog(orderBaseId, "接收工单", "主要工程师【" + one.getWorkerName() + "】确认接单" + joinSlaveStr, one.getWebsitName());
    }

    /**
     * 抢单
     * @param orderBaseId
     */
    @Transactional
    public void qd(String orderBaseId){
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if(!StringUtils.equals(pgOrderBase.getOrderStatus(),OrderBaseStatusEnum.DQD.getKey())){
            throw new RemoteServiceException("很遗憾，单已被人抢走");
        }
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        User user = currentCompanyWechat.getUser();
        if(!StringUtils.equals(user.getType(),UserTypeEnum.WORKER.getKey())){
            throw new RemoteServiceException("当前身份不可抢单");
        }

        pgOrderBase.setWorkerId(currentCompanyWechat.getUserId());
        pgOrderBase.setWorkerNumber(currentCompanyWechat.getUser().getWorkerNumber());
        pgOrderBase.setWorkerName(user.getNickName());
        pgOrderBase.setWorkerReceTime(new Date());
        pgOrderBase.setWorkerIdcard(user.getIdCard());
        pgOrderBase.setWorkerMobile(user.getMobile());
        pgOrderBase.setWorkerIdList(user.getUserId());
        pgOrderBase.setDispatchTime(new Date());
        pgOrderBase.setOrderStatus(OrderBaseStatusEnum.FWZ.getKey());
        pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.FWZ.getRemark());
        pgOrderBase.updateById();

        //记录师傅表
        pgOrderWorkerService.lambdaUpdate().eq(PgOrderWorker::getOrderBaseId,pgOrderBase.getId()).remove();
        PgOrderWorker pgOrderWorker = new PgOrderWorker();
        pgOrderWorker.setIsMaster(true);
        pgOrderWorker.setWorkerId(user.getUserId());
        pgOrderWorker.setWorkerNumber(currentCompanyWechat.getUser().getWorkerNumber());
        pgOrderWorker.setWorkerName(user.getNickName());
        pgOrderWorker.setWorkerIdcard(user.getIdCard());
        pgOrderWorker.setWorkerMobile(user.getMobile());
        pgOrderWorker.setWebsitId(pgOrderBase.getWebsitId());
        pgOrderWorker.setWebsitName(pgOrderBase.getWebsitName());
        pgOrderWorker.setOrderBaseId(pgOrderBase.getId());
        pgOrderWorker.insert();

        final AdminWebsit adminWebsit = adminWebsitService.getById(pgOrderBase.getWebsitId());
        StringBuilder joinSlaveStr = new StringBuilder();
        if (adminWebsit.getAttr().equals(WebsitAttrEnum.SELF.getKey())
                && "安装, 拆移机".contains(pgOrderBase.getOrderSmallTypeText())) {
            final List<WorkerTeamBean> teamBeanList = this.slaveWorkerTeam(orderBaseId, pgOrderBase);
            if (CollectionUtil.isEmpty(teamBeanList)) {
                throw new RemoteServiceException("工单类型必须有一组有效的组队，抢单失败");
            }
            joinSlaveStr.append(", 辅助工程师");
            final WorkerTeamBean bean = teamBeanList.get(0);
            PgOrderWorker pgOrderWorker2 = new PgOrderWorker();
            pgOrderWorker2.setIsMaster(false);
            pgOrderWorker2.setWorkerId(bean.getWorkerId());
            pgOrderWorker2.setWorkerNumber(bean.getWorkerNumber());
            pgOrderWorker2.setWorkerName(bean.getWorkerName());
            pgOrderWorker2.setWorkerIdcard(bean.getWorkerIdCard());
            pgOrderWorker2.setWorkerMobile(bean.getWorkerMobile());
            pgOrderWorker2.setWebsitId(pgOrderBase.getWebsitId());
            pgOrderWorker2.setWebsitName(pgOrderBase.getWebsitName());
            pgOrderWorker2.setOrderBaseId(pgOrderBase.getId());
            pgOrderWorker2.insert();
            joinSlaveStr.append("【").append(pgOrderWorker2.getWorkerName()).append("】");
        }

        orderLogLogic.addLog(orderBaseId,"师傅抢单","工程师【"+pgOrderWorker.getWorkerName()+"】" + joinSlaveStr + "抢单成功",pgOrderWorker.getWebsitName());
    }

    /**
     * 打标记/取消标记
     * @param orderBaseId
     * @param jiaji
     */
    public void jiaji(String orderBaseId, OrderFlagEnum orderFlagEnum, Boolean jiaji){
        if(jiaji) {
            orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBaseId), orderFlagEnum);
        }else{
            orderFlagLogic.deleteOrderFlag(orderBaseId,orderFlagEnum);
        }
    }

    /**
     * 工单评价
     * @param orderAppraiseBean
     */
    public void appraise(OrderAppraiseBean orderAppraiseBean){
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderAppraiseBean.getOrderBaseId());
        if(!pgOrderBase.getAppraiseStatus().equals(AppraiseStatusEnum.N.getKey())){
            throw new RemoteServiceException("当前服务单暂无法评价");
        }
        pgOrderBase.setAppraiseTime(new Date());
        pgOrderBase.setAppraiseStatus(converAppraiseStatus(orderAppraiseBean.getLevel()).getKey());
        pgOrderBase.setAppraiseContent(orderAppraiseBean.getAppraiseContent());
        pgOrderBase.setAppraiseImgUrl(orderAppraiseBean.getAppraiseImgUrl());
        pgOrderBase.setAppraiseSource(1);
        pgOrderBase.updateById();
    }


    public AppraiseStatusEnum converAppraiseStatus(Integer level){
        if(level <= 2){
            return AppraiseStatusEnum.C;
        }else if(level <= 4 ){
            return AppraiseStatusEnum.B;
        }else if(level >= 5){
            return AppraiseStatusEnum.A;
        }
        return AppraiseStatusEnum.N;
    }


    /**
     * 重算工单主表的完成数量
     * @param orderBaseId
     */
    public void reNum(String orderBaseId) {
        Integer totalNum = 0;
        Integer undoneNum = 0;
        //安装规则的
        List<PgOrderProduct> orderProducts = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, orderBaseId).list();
        if(CollectionUtils.isNotEmpty(orderProducts)) {
            totalNum = orderProducts.stream().mapToInt(v -> v.getNum()).sum();
            totalNum = totalNum < 1 ? 1 : totalNum;
            //undoneNum = totalNum;
            //未完成数量 todo 待采集表设计完成
            undoneNum = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId,orderBaseId).ne(PgOrderProduct::getStatus,"OK").count();

        }
        pgOrderBaseService.lambdaUpdate()
                .set(PgOrderBase::getTotalNum, totalNum)
                .set(PgOrderBase::getUndoneNum, undoneNum)
                .eq(PgOrderBase::getId, orderBaseId).update();
    }

    /**
     * 根据工单号获取大工有配队的小工师傅
     * @param orderBaseId
     * @return
     */
    public List<WorkerTeamBean> slaveWorkerTeam(String orderBaseId, PgOrderBase orderBase) {
        String workerNumber;
        if (Objects.isNull(orderBase)) {
            orderBase = pgOrderBaseService.getById(orderBaseId);
            if (StringUtils.equals(orderBase.getOrderStatus(), OrderBaseStatusEnum.YWG.getKey())) {
                throw new RemoteServiceException("工单状态”已完工“");
            }
            workerNumber = orderBase.getWorkerNumber();
        } else {
            CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
            workerNumber = currentCompanyWechat.getUser().getWorkerNumber();
        }
        Map<String, WorkerTeamBean> workerTeamMap = new HashMap<>();
        if (StringUtils.isNotBlank(orderBase.getWorkerId())) {
            final List<PgOrderWorker> orderWorkerList = pgOrderWorkerService.lambdaQuery()
                    .eq(PgOrderWorker::getOrderBaseId, orderBaseId)
                    .eq(PgOrderWorker::getIsMaster, false)
                    .ne(PgOrderWorker::getWorkerId, orderBase.getWorkerId())
                    .list();

            if (CollectionUtil.isNotEmpty(orderWorkerList)) {
                for (PgOrderWorker orderWorker : orderWorkerList) {
                    WorkerTeamBean bean = new WorkerTeamBean();
                    bean.setWorkerId(orderWorker.getWorkerId());
                    bean.setWorkerName(orderWorker.getWorkerName());
                    bean.setWorkerNumber(orderWorker.getWorkerNumber());
                    bean.setWorkerMobile(orderWorker.getWorkerMobile());
                    bean.setWorkerIdCard(orderWorker.getWorkerIdcard());
                    bean.setIsSelect(true);
                    workerTeamMap.put(orderWorker.getWorkerId(), bean);
                }
            }
        }

        final List<WorkerTeam> teamList = workerTeamService.lambdaQuery()
                .eq(WorkerTeam::getCompanyWechatId, orderBase.getCompanyWechatId())
                .eq(WorkerTeam::getMasterWorkerId, workerNumber)
                .eq(WorkerTeam::getStatus, StateEnum.ON.getKey())
                .orderByAsc(WorkerTeam::getCreateTime)
                .list();
        if (CollectionUtil.isNotEmpty(teamList)) {
            final List<User> userList = userService.lambdaQuery()
                    .in(User::getWorkerNumber, teamList.stream()
                            .map(WorkerTeam::getAssistantWorkerId)
                            .collect(Collectors.toList()))
                    .eq(User::getType, UserTypeEnum.WORKER.getKey())
                    .list();
            final Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getWorkerNumber, Function.identity()));
            int index = 0;
            for (WorkerTeam workerTeam : teamList) {
                final User user = userMap.get(workerTeam.getAssistantWorkerId());
                if (Objects.nonNull(user)) {
                    WorkerTeamBean bean = new WorkerTeamBean();
                    bean.setWorkerId(user.getUserId());
                    bean.setWorkerName(user.getNickName());
                    bean.setWorkerNumber(user.getWorkerNumber());
                    bean.setWorkerMobile(user.getMobile());
                    bean.setWorkerIdCard(user.getIdCard());
                    bean.setIsSelect(false);
                    if (index == 0 && CollectionUtil.isEmpty(workerTeamMap)) {
                        // 没有工单派工师傅并且下标为0时，默认选中
                        bean.setIsSelect(true);
                    }
                    workerTeamMap.put(user.getUserId(), bean);
                    index++;
                }
            }
        }

        if (CollectionUtil.isNotEmpty(workerTeamMap)) {
            // 清除非正常状态的小工师傅
            final List<WebsitUser> websitUserList = websitUserService.lambdaQuery()
                    .eq(WebsitUser::getCompanyWechatId, orderBase.getCompanyWechatId())
                    .ne(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.getKey())
                    .eq(WebsitUser::getWebsitId, orderBase.getWebsitId())
                    .in(WebsitUser::getUserId, workerTeamMap.keySet())
                    .list();

            for (WebsitUser websitUser : websitUserList) {
                workerTeamMap.remove(websitUser.getUserId());
            }
        }

        return new ArrayList<>(workerTeamMap.values());
    }

    public void changeSlaveWorkerTeam(String orderBaseId, List<String> workerList) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if (StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.YWG.getKey())) {
            throw new RemoteServiceException("工单状态”已完工“");
        }

        final AdminWebsit adminWebsit = adminWebsitService.getById(pgOrderBase.getWebsitId());

        if (adminWebsit.getAttr().equals(WebsitAttrEnum.SELF.getKey())
                && "安装, 拆移".contains(pgOrderBase.getOrderSmallType())
                && CollectionUtil.isEmpty(workerList)) {
            throw new RemoteServiceException("工单的类型必须至少选一个小工");
        }
        // 清空小工
        pgOrderWorkerService.lambdaUpdate()
                .eq(PgOrderWorker::getOrderBaseId, pgOrderBase.getId())
                .eq(PgOrderWorker::getIsMaster, false)
                .remove();

        StringBuilder joinSlaveStr = new StringBuilder();
        if (CollectionUtil.isNotEmpty(workerList)) {
            joinSlaveStr.append("辅助工程师");
            List<PgOrderWorker> orderWorkerList = new ArrayList<>();
            for (String workerId : workerList) {
                final User user = userService.getById(workerId);
                PgOrderWorker orderWorker = new PgOrderWorker();
                orderWorker.setOrderBaseId(pgOrderBase.getId())
                        .setWebsitId(pgOrderBase.getWebsitId())
                        .setWebsitName(pgOrderBase.getWebsitName())
                        .setWorkerId(workerId)
                        .setWorkerName(Objects.nonNull(user) ? user.getNickName() : "")
                        .setWorkerMobile(Objects.nonNull(user) ? user.getMobile() : "")
                        .setWorkerIdcard(Objects.nonNull(user) ? user.getIdCard() : "")
                        .setWorkerNumber(Objects.nonNull(user) ? user.getWorkerNumber() : "")
                        .setIsMaster(false);

                orderWorkerList.add(orderWorker);
                joinSlaveStr.append("【").append(orderWorker.getWorkerName()).append("】");
            }

            pgOrderWorkerService.saveBatch(orderWorkerList);
        }

        orderLogLogic.addLog(orderBaseId, "更换小工", joinSlaveStr.toString(), pgOrderBase.getWebsitName());
    }
}
