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

import cn.hutool.core.bean.BeanUtil;
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.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.bean.workorder.*;
import com.gree.mall.miniapp.commonmapper.workorder.OrderBaseCMapper;
import com.gree.mall.miniapp.enums.UserTypeEnum;
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.helper.ResponseHelper;
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.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;


    /**
     * 工单状态统计
     * @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());
        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()+"****");
            }
        }
        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));
        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
     */
    public void rece(String orderBaseId){
        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("当前状态不可接单");
        }
        pgOrderBase.setOrderStatus(OrderBaseStatusEnum.FWZ.getKey());
        pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.FWZ.getRemark());
        pgOrderBase.setWorkerReceTime(new Date());
        pgOrderBase.updateById();

        orderLogLogic.addLog(orderBaseId,"接收工单","工程师【"+one.getWorkerName()+"】确认接单",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.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.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();

        orderLogLogic.addLog(orderBaseId,"师傅抢单","工程师【"+pgOrderWorker.getWorkerName()+"】抢单成功",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();
    }


}
