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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.common.RegionBean;
import com.gree.mall.manager.bean.listvo.param.WorkOrderZfireParam;
import com.gree.mall.manager.bean.listvo.workorder.OrderBase2VO;
import com.gree.mall.manager.bean.listvo.workorder.OrderBaseAppraiseVO;
import com.gree.mall.manager.bean.listvo.workorder.OrderBaseVO;
import com.gree.mall.manager.bean.workorder.OrderAddBean2DTO;
import com.gree.mall.manager.bean.workorder.OrderAddBeanDTO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.commonmapper.workorder.OrderBaseCMapper;
import com.gree.mall.manager.constant.SysDictConstant;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.enums.base.BaseEnum;
import com.gree.mall.manager.enums.workorder.OrderBaseStatusEnum;
import com.gree.mall.manager.enums.workorder.OrderFlagEnum;
import com.gree.mall.manager.enums.workorder.OrderTypeEnum;
import com.gree.mall.manager.enums.workorder.SaleTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.LbsAmapLogic;
import com.gree.mall.manager.logic.common.SysDictCompanyLogic;
import com.gree.mall.manager.logic.common.WxPubNoticeLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderBaseLogic {

    private final CommonLogic commonLogic;
    private final OrderFlagLogic orderFlagLogic;
    private final SysDictCompanyLogic sysDictCompanyLogic;
    private final OrderLogLogic orderLogLogic;
    private final LbsAmapLogic lbsAmapLogic;
    private final WxPubNoticeLogic wxPubNoticeLogic;
    private final WebsitUserService websitUserService;
    private final CommonMapper commonMapper;
    private final OrderBaseCMapper orderBaseCMapper;
    private final PgOrderBaseService pgOrderBaseService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final AdminWebsitService adminWebsitService;
    private final OrderSmallTypeService orderSmallTypeService;
    private final PgOrderProductService pgOrderProductService;
    private final UserAddressService userAddressService;
    private final GoodsCategoryService goodsCategoryService;
    private final UserService userService;
    private final PgOrderProductDetailService pgOrderProductDetailService;
    private final OrderInfoService orderInfoService;
    private final PgIncreOrderService pgIncreOrderService;
    private final RpProjectRepairService rpProjectRepairService;
    private final RpProjectRepairProductService projectRepairProductService;
    private final SettleOrderLogic settleOrderLogic;
    private final PgOrderSettleNormService pgOrderSettleNormService;
    private final AdminUserWebsitRelaService adminUserWebsitRelaService;
    private final AdminUserService adminUserService;
    private final WorkerOrderService workerOrderService;
    private final RegionService regionService;
    private final NoticeRecordService noticeRecordService;
    private final LeaseOrderService leaseOrderService;

    /**
     * 工单列表
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<OrderBaseVO> orderBaseList(WorkOrderZfireParam zfireParamBean) {

        //特殊处理 "异常单","待预约","配件申请中","配件已到货","配件已取消" 的查询条件
        if (zfireParamBean.getParamValue("a.order_status") instanceof String) {
            String paramValue = (String) zfireParamBean.getParamValue("a.order_status");
            if (StringUtils.equals(paramValue, OrderBaseStatusEnum.YCD.getKey()) || StringUtils.equals(paramValue, OrderBaseStatusEnum.DYY.getKey())
                    || StringUtils.equals(paramValue, "PJSQZ") || StringUtils.equals(paramValue, "PJYDH") || StringUtils.equals(paramValue, "PJYQX")) {
                zfireParamBean.removeParam("a.order_status");

                if (StringUtils.equals(paramValue, "PJSQZ") || StringUtils.equals(paramValue, "PJYDH") || StringUtils.equals(paramValue, "PJYQX")) {
                    zfireParamBean.setPartsApplyStatus(paramValue);
                }
            }

        }

        AdminUserCom adminUser = commonLogic.getAdminUser();

        FieldUtils.supplyParam(zfireParamBean, OrderBaseVO.class, commonLogic.getAdminUser());
        zfireParamBean.setAdminWebsitIds(zfireParamBean.getAdminWebsitIds());

        IPage<OrderBaseVO> page = commonMapper.orderBaseList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getType());

        //服务单标识
        if (zfireParamBean.getPageSize() != -1 && page.getTotal() > 0) {
            List<String> orderBaseIds = page.getRecords()
                    .stream()
                    .map(OrderBaseVO::getId)
                    .collect(Collectors.toList());
            Map<String, List<PgOrderFlag>> mapList = orderFlagLogic.list(orderBaseIds);

            List<WorkerOrder> workerOrderList = workerOrderService.lambdaQuery().in(WorkerOrder::getWorkerOrderId, orderBaseIds)
                    .eq(WorkerOrder::getPayStatus, MaterialExamineStatusEnum.PAID.getKey())
                    .select(WorkerOrder::getWorkerOrderId, WorkerOrder::getTotalAmount).list();

            for (OrderBaseVO orderBaseVO : page.getRecords()) {
                orderBaseVO.setOrderFlags(mapList.get(orderBaseVO.getId()));

                List<WorkerOrder> workerOrders = workerOrderList.stream()
                        .filter(item -> item.getWorkerOrderId().equals(orderBaseVO.getId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(workerOrderList)) {
                    BigDecimal bigDecimal = workerOrders.stream().map(WorkerOrder::getTotalAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                    orderBaseVO.setWorkerPrice(bigDecimal);
                }

            }
        }
        return page;
    }


    /**
     * 工单列表2
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<PgOrderBase> list2(String userId, Integer pageNum, Integer pageSize) {
        User user = userService.getById(userId);
        Page<PgOrderBase> page = pgOrderBaseService.lambdaQuery()
                .and(v -> v.eq(PgOrderBase::getUserId, user.getUserId())
                        .or().eq(PgOrderBase::getUserMobile, user.getMobile())
                        .or().eq(PgOrderBase::getUserMobile2, user.getMobile()))
                .ne(PgOrderBase::getUserMobile, "")
                .ne(PgOrderBase::getUserMobile2, "")
                .orderByDesc(PgOrderBase::getCreateTime).page(new Page<>(pageNum, pageSize));
        return page;
    }


    /**
     * 工单评价列表
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<OrderBaseAppraiseVO> orderBaseAppraiseList(ZfireParamBean zfireParamBean) {
        FieldUtils.supplyParam(zfireParamBean, OrderBaseAppraiseVO.class, commonLogic.getAdminUser());
        zfireParamBean.setAdminWebsitIds(zfireParamBean.getAdminWebsitIds());
        IPage<OrderBaseAppraiseVO> page = commonMapper.orderBaseAppraiseList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }

    /**
     * 工单状态统计
     *
     * @return
     */
    public List<Map<String, Object>> countStatus(String startTime,String endTime,String orderSmallType, String orderSmallTypeText) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<Map<String, Object>> maps = orderBaseCMapper.countOrderStatus(adminUser.getCompanyWechatId(), adminUser.getAdminWebsitIds(),
                adminUser.getType(), orderSmallType, orderSmallTypeText,startTime,endTime);
        return maps;
    }


    /**
     * 保存工单
     *
     * @param orderAddBeanDTO
     */
    @Transactional
    public String saveOrder(OrderAddBeanDTO orderAddBeanDTO) {
        String orderBaseId = orderAddBeanDTO.getId();
        Boolean addFlag = false;
        PgOrderBase old = pgOrderBaseService.getById(orderBaseId);
        Boolean oldIsQd = false;
        if (old == null) {
            orderBaseId = "A" + IdWorker.getIdStr();
            addFlag = true;
        } else {
            oldIsQd = old.getIsQd();
        }
        orderAddBeanDTO.setId(orderBaseId);

        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号不可建单");
        }
        //如果选择的师傅存在非当前工单的网点，则清空师傅信息
        if (CollectionUtils.isNotEmpty(orderAddBeanDTO.getOrderWorkers())) {
            long count = orderAddBeanDTO.getOrderWorkers().stream().filter(v -> !StringUtils.equals(v.getWebsitId(), orderAddBeanDTO.getWebsitId())).count();
            if (count > 0) {
                orderAddBeanDTO.getOrderWorkers().clear();
            }
        }

        PgOrderBase orderBase = this.conver(old, orderAddBeanDTO, addFlag);
        orderBase.setCompanyWechatId(adminUser.getCompanyWechatId());
        orderBase.setCompanyWechatName(adminUser.getCompanyName());
        orderBase.setCreateWebsitId(orderAddBeanDTO.getCreateWebsitId());
        orderBase.setCreateWebsitName(orderAddBeanDTO.getCreateWebsitName());
        orderBase.setCreateMobile(adminUser.getLinkPhone());
        orderBase.setIsQd(orderAddBeanDTO.getIsQd());
        orderBase.setIsQdNotice(true);
        orderBase.setId(orderBaseId);

        //是否变更了师傅
        Boolean changeWorker = false;
        //修改记录
        if (!addFlag) {
            changeWorker = updateOrderLog(old, orderBase, orderAddBeanDTO);
        }

        //产品信息(编辑是单独维护的，这里只需要处理新增)
        if (addFlag) {
            for (PgOrderProduct v : orderAddBeanDTO.getOrderProducts()) {
                v.setOrderBaseId(orderBase.getId());

                if (StringUtils.isNotBlank(orderAddBeanDTO.getRpProjectRepairId())) {
                    //维保单判断是否数量超了
                    RpProjectRepairProduct one = projectRepairProductService.lambdaQuery()
                            .eq(RpProjectRepairProduct::getProjectRepairId, orderAddBeanDTO.getRpProjectRepairId())
                            .eq(RpProjectRepairProduct::getBrandId, v.getBrandId())
                            .eq(RpProjectRepairProduct::getMainId, v.getMainId())
                            .eq(RpProjectRepairProduct::getSmallId, v.getSmallId())
                            .last("limit 1")
                            .one();
                    if (one != null && one.getNum() < v.getNum()) {
                        throw new RemoteServiceException("机型【" + v.getProductName() + "】设备数量不可大于维保项目的机型设备数量");
                    }
                }
            }
            pgOrderProductService.saveBatch(orderAddBeanDTO.getOrderProducts());
            this.upOrderProduct(orderBase.getId());
        }

        //师傅信息
        pgOrderWorkerService.lambdaUpdate().eq(PgOrderWorker::getOrderBaseId, orderBaseId).remove();
        if (CollectionUtils.isNotEmpty(orderAddBeanDTO.getOrderWorkers())) {
            for (PgOrderWorker v : orderAddBeanDTO.getOrderWorkers()) {
                v.setOrderBaseId(orderBase.getId());
            }
            pgOrderWorkerService.saveBatch(orderAddBeanDTO.getOrderWorkers());
        }

        //如果变更了师傅，则需要将“抢单”标识剔除
        if (changeWorker || (addFlag && CollectionUtils.isNotEmpty(orderAddBeanDTO.getOrderWorkers()))) {
            orderBase.setIsQd(false);
        }

        String orderTitle = getOrderTitle(orderAddBeanDTO.getOrderProducts());
        orderBase.setOrderTitle(orderTitle);
        orderBase.insertOrUpdate();

        //生成已完工标签
        orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBase.getId()),OrderFlagEnum.ORDER);

        //日志记录
        if (addFlag) {
            addLog(orderBase, "");
        }

        //重算机型数量
        reNum(orderBaseId);

        //增值服务工单
        increWorkerOrderInsideCode(orderBaseId);

        //维保工单
        if (StringUtils.isNotBlank(orderAddBeanDTO.getRpProjectRepairId()))
            repairProjectWorkerOrder(orderBase);
        if (orderAddBeanDTO.getSaleType() != null && orderAddBeanDTO.getSaleType() == SaleTypeEnum.B.getIntKey()) {
            if (StringUtils.isAnyBlank(orderAddBeanDTO.getProjectNo(), orderAddBeanDTO.getProjectName())) {
                throw new RemoteServiceException("工程单的工程编号和工程名称不能为空");
            }
            orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBaseId), OrderFlagEnum.PROJECT);
        }
        //租赁单业务处理
        orderBase = handleZl(orderBase);
        //变更师傅的通知
        if (changeWorker) {
            orderLogLogic.insertNotice(orderBaseId);
        }

        //创建工单添加消息
        if (addFlag) {
            this.sendMaterialExamine(orderBase.getId());
        }
        //新建单，或者从旧单的不抢单改成抢单
//        if(addFlag || (!oldIsQd && orderAddBeanDTO.getIsQd())){
//            //抢单的通知，通知给当前网点的所有师傅
//            this.addQdNotice(orderBase);
//        }
        if (orderAddBeanDTO.getIsQd() && orderBase.getOrderStatus().equals(OrderBaseStatusEnum.DQD.getKey())) {
            this.addQdNotice(orderBase);
        }
        return orderBaseId;
    }


    /**
     * 添加抢单通知
     */
    public void addQdNotice(PgOrderBase orderBase) {
        //抢单的通知，通知给当前网点的所有师傅
        if (orderBase.getIsQd() != null && orderBase.getIsQd() && StringUtils.equals(orderBase.getOrderStatus(), OrderBaseStatusEnum.DQD.getKey())) {
            //查询当前网点的所有师傅
            List<WebsitUser> list = websitUserService.lambdaQuery().eq(WebsitUser::getWebsitId, orderBase.getWebsitId()).list();
            List<String> userIds = list.stream().map(WebsitUser::getUserId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIds)) {
                return;
            }
            List<User> workers = userService.lambdaQuery()
                    .eq(User::getStatus, true)
                    .eq(User::getType, UserTypeEnum.WORKER.getKey())
                    .in(User::getUserId, userIds).list();
            //公众号通知
            wxPubNoticeLogic.addDispatchBatch(workers, Lists.newArrayList(orderBase));
        }
    }


    public void sendMaterialExamine(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return;
        }
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderId);


        AdminUser one = adminUserService.lambdaQuery().eq(AdminUser::getCompanyWechatId, pgOrderBase.getCompanyWechatId())
                .eq(AdminUser::getType, 1).last("limit 1").one();

        NoticeRecord noticeRecordCom = new NoticeRecord();
        noticeRecordCom.setNoticeId(pgOrderBase.getId());
        String format = DateUtil.format(pgOrderBase.getCreateTime(), "yyyy-MM-dd");
        noticeRecordCom.setTitle(pgOrderBase.getOrderTypeText() + pgOrderBase.getId() + ",创建时间：" + format + "请及时跟进");
        noticeRecordCom.setContent(pgOrderBase.getOrderTypeText() + pgOrderBase.getId() + ",创建时间：" + format + "请及时跟进");
        noticeRecordCom.setType(NoticeEnum.B.getKey());
        noticeRecordCom.setNoticeType(NoticeTypeEnum.SYSTEM.getKey());
        noticeRecordCom.setIsNotice(IsYesNoEnum.YES.getKey());
        noticeRecordCom.setReadFlag(IsYesNoEnum.NO.getKey());
        noticeRecordCom.setAdminUserId(one.getAdminUserId());
        noticeRecordCom.setAdminNickName(one.getNickName());
        noticeRecordCom.setIssueTime(new Date());
        noticeRecordCom.setAdminCompanyId(pgOrderBase.getCompanyWechatId());
        noticeRecordCom.setAdminCompanyName(pgOrderBase.getCompanyWechatName());
        noticeRecordCom.setAdminNoticeType(AdminNoticTypeEnum.CRE_ORDER.getKey());
        noticeRecordCom.setOrderId(pgOrderBase.getId());
        noticeRecordCom.insert();


        String websitId = pgOrderBase.getWebsitId();
        if (StringUtils.isBlank(pgOrderBase.getWebsitId())) {
            return;
        }
        List<AdminUserWebsitRela> adminUserWebsitRelas = adminUserWebsitRelaService.lambdaQuery().in(AdminUserWebsitRela::getAdminWebsitId, websitId).list();
        if (CollectionUtils.isEmpty(adminUserWebsitRelas)) {
            return;
        }
        List<String> adminUserIds = adminUserWebsitRelas.stream().map(AdminUserWebsitRela::getAdminUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(adminUserIds)) {
            return;
        }
        List<AdminUser> adminUsers = adminUserService.lambdaQuery().in(AdminUser::getAdminUserId, adminUserIds).list();
        List<NoticeRecord> noticeRecords = new ArrayList<>();
        for (AdminUser adminUser : adminUsers) {
            NoticeRecord noticeRecord = new NoticeRecord();
            noticeRecord.setNoticeId(pgOrderBase.getId());
            String formatzi = DateUtil.format(pgOrderBase.getCreateTime(), "yyyy-MM-dd");
            noticeRecord.setTitle(pgOrderBase.getOrderTypeText() + pgOrderBase.getId() + ",创建时间：" + formatzi + "请及时跟进");
            noticeRecord.setContent(pgOrderBase.getOrderTypeText() + pgOrderBase.getId() + ",创建时间：" + formatzi + "请及时跟进");
            noticeRecord.setType(NoticeEnum.B.getKey());
            noticeRecord.setNoticeType(NoticeTypeEnum.SYSTEM.getKey());
            noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
            noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
            noticeRecord.setAdminUserId(adminUser.getAdminUserId());
            noticeRecord.setAdminNickName(adminUser.getNickName());
            noticeRecord.setIssueTime(new Date());
            noticeRecord.setAdminCompanyId(pgOrderBase.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(pgOrderBase.getCompanyWechatName());
            noticeRecord.setAdminNoticeType(AdminNoticTypeEnum.CRE_ORDER.getKey());
            noticeRecord.setOrderId(pgOrderBase.getId());
            noticeRecords.add(noticeRecord);
        }

        noticeRecordService.saveBatch(noticeRecords);

    }


    /**
     * 创建工单(小程序端用)
     *
     * @param orderAddBeanDTO
     */
    @Transactional
    public String add(OrderAddBean2DTO orderAddBeanDTO) {
        //商户id
        String companyWechatId = orderAddBeanDTO.getCompanyWechatId();
        //延保订单id
        String pgIncreOrderId = orderAddBeanDTO.getPgIncreOrderId();
        //检查此商户下面的所有网点，如果只有1个，则直接派单到这个网点。如果有多个网点则派到这个商户
        if (StringUtils.isBlank(orderAddBeanDTO.getWebsitId())) {
            List<AdminWebsit> adminWebsits = adminWebsitService.lambdaQuery()
                    .eq(AdminWebsit::getCompanyWechatId, companyWechatId)
                    .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey()).list();
            if (adminWebsits.size() == 1) {
                orderAddBeanDTO.setWebsitId(adminWebsits.get(0).getWebsitId());
            } else {
                AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                        .eq(AdminWebsit::getCompanyWechatId, companyWechatId)
                        .eq(AdminWebsit::getType, AdminWebsitTypeEnum.B.getKey())
                        .last("limit 1")
                        .one();

                orderAddBeanDTO.setWebsitId(adminWebsit.getWebsitId());
            }
        }
        //如果是租赁单，根据销售单号判断是否还有未完成的单
        if (orderAddBeanDTO.getIsZl() && StringUtils.isNotBlank(orderAddBeanDTO.getSaleOrderId())) {
            Integer count = pgOrderBaseService.lambdaQuery().eq(PgOrderBase::getIsZl, true)
                    .eq(PgOrderBase::getSaleOrderId, orderAddBeanDTO.getSaleOrderId())
                    .notIn(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.isOver())
                    .ne(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.YQX.getKey())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException("存在进行中的报修单，请耐心等候");
            }
        }

        String lng = "", lat = "";
        UserAddress userAddress = new UserAddress();
        if (StringUtils.isBlank(orderAddBeanDTO.getRpProjectRepairId())) {
            //用户收货地址
            if (StringUtils.isNotBlank(orderAddBeanDTO.getUserAddressId())) {
                userAddress = userAddressService.getById(orderAddBeanDTO.getUserAddressId());

                String gpsAddress = userAddress.getProvince() + userAddress.getCity() + userAddress.getArea() + userAddress.getStreet() + userAddress.getAddress();
                //反查经纬度
                String location = lbsAmapLogic.getLocationByAddress(gpsAddress);
                lng = location.split(",")[0];
                lat = location.split(",")[1];

                //填充参数
                orderAddBeanDTO.setUserId(userAddress.getUserId());
                orderAddBeanDTO.setUserName(userAddress.getName());
                orderAddBeanDTO.setPhone(userAddress.getPhone());
                orderAddBeanDTO.setProvinceId(userAddress.getProvinceId());
                orderAddBeanDTO.setProvince(userAddress.getProvince());
                orderAddBeanDTO.setCityId(userAddress.getCityId());
                orderAddBeanDTO.setCity(userAddress.getCity());
                orderAddBeanDTO.setAreaId(userAddress.getAreaId());
                orderAddBeanDTO.setArea(userAddress.getArea());
                orderAddBeanDTO.setStreetId(userAddress.getStreetId());
                orderAddBeanDTO.setStreet(userAddress.getStreet());
                orderAddBeanDTO.setAddress(gpsAddress);
            } else {
                if (StringUtils.isBlank(orderAddBeanDTO.getProvince())) {
                    //反查经纬度
                    String location = lbsAmapLogic.getLocationByAddress(orderAddBeanDTO.getAddress());
                    lng = location.split(",")[0];
                    lat = location.split(",")[1];

                    RegionBean regionBean = lbsAmapLogic.getRegionByLngLat(location);
                    Region region = getRegion(regionBean.getProvinceName(), regionBean.getCityName(), regionBean.getAreaName(), regionBean.getName());

                    orderAddBeanDTO.setProvinceId(region.getProvinceCode());
                    orderAddBeanDTO.setProvince(region.getProvinceName());
                    orderAddBeanDTO.setCityId(region.getCityCode());
                    orderAddBeanDTO.setCity(region.getCityName());
                    orderAddBeanDTO.setAreaId(region.getAreaCode());
                    orderAddBeanDTO.setArea(region.getAreaName());
                    orderAddBeanDTO.setStreetId(region.getId());
                    orderAddBeanDTO.setStreet(region.getName());
                    orderAddBeanDTO.setAddress(orderAddBeanDTO.getAddress());
                } else {
                    //反查经纬度
                    String location = lbsAmapLogic.getLocationByAddress(orderAddBeanDTO.getProvince() + orderAddBeanDTO.getCity()
                            + orderAddBeanDTO.getArea() + orderAddBeanDTO.getStreet() + orderAddBeanDTO.getAddress());
                    lng = location.split(",")[0];
                    lat = location.split(",")[1];
                }
            }
        }

        //产品大类
        List<GoodsCategory> list = goodsCategoryService.lambdaQuery().eq(GoodsCategory::getType, 2).list();
        Map<String, GoodsCategory> goodsCategoryMap = list.stream().collect(Collectors.toMap(v -> v.getCategoryId(), Function.identity()));
        //工单类型
        OrderSmallType orderSmallType = null;
        if (!orderAddBeanDTO.getIsCj()) {
            orderSmallType = orderSmallTypeService.getById(orderAddBeanDTO.getOrderSmallType());
            if (orderSmallType == null) {
                throw new RemoteServiceException("工单类型【" + orderAddBeanDTO.getOrderSmallType() + "】不存在，请联系相关人员");
            }
        } else {
            //拆机工单类型
            orderSmallType = orderSmallTypeService.lambdaQuery()
                    .eq(OrderSmallType::getOrderSmallTypeText, "拆机")
                    .eq(OrderSmallType::getCompanyWechatId, orderAddBeanDTO.getCompanyWechatId())
                    .last("limit 1").one();
            if (orderSmallType == null) {
                throw new RemoteServiceException("请先配置工单类型【拆机】");
            }
        }
        //业务类型，工单大类
        OrderTypeEnum orderTypeEnum = BaseEnum.keyToEnum(OrderTypeEnum.class, orderSmallType.getOrderType());
        if (orderTypeEnum == null) {
            throw new RemoteServiceException("工单类型错误");
        }
        //工单状态默认为待商户派工
        OrderBaseStatusEnum orderBaseStatusEnum = OrderBaseStatusEnum.DSHPG;

        PgOrderBase pgOrderBase = new PgOrderBase();
        //渠道
        SysDictCompany orderChannelDict = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, "商城", companyWechatId);
//        if(orderChannelDict == null){
//            SysDictCompany sysDictCompany = new SysDictCompany();
//            sysDictCompany.setDictType(SysDictConstant.ORDER_CHANNEL);
//            sysDictCompany.setDictValue("商城");
//            sysDictCompany.setCompanyWechatId(companyWechatId);
//            sysDictCompany.setCompanyName(orderAddBeanDTO.getCompanyWechatName());
//            sysDictCompanyLogic.saveOpenDict(sysDictCompany);
//
//            orderChannelDict = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, "商城",companyWechatId);
//        }

        pgOrderBase
                .setId("A" + IdWorker.getIdStr())
                .setUserName(orderAddBeanDTO.getUserName())
                .setLinkName(orderAddBeanDTO.getUserName())
                .setUserId(orderAddBeanDTO.getUserId())
                .setUserMobile(orderAddBeanDTO.getPhone())
                .setProvinceId(orderAddBeanDTO.getProvinceId())
                .setProvince(orderAddBeanDTO.getProvince())
                .setCityId(orderAddBeanDTO.getCityId())
                .setCity(orderAddBeanDTO.getCity())
                .setAreaId(orderAddBeanDTO.getAreaId())
                .setArea(orderAddBeanDTO.getArea())
                .setStreetId(orderAddBeanDTO.getStreetId())
                .setStreet(orderAddBeanDTO.getStreet())
                .setAddress(orderAddBeanDTO.getAddress())
                .setGpsAddress(orderAddBeanDTO.getAddress())
                .setLng(lng)
                .setLat(lat)
                .setOrderSmallType(orderSmallType.getId())
                .setOrderSmallTypeText(orderSmallType.getOrderSmallTypeText())
                .setOrderType(orderSmallType.getOrderType())
                .setOrderTypeText(orderTypeEnum.getRemark())
                .setOrderChannelId(orderChannelDict.getDictCode())
                .setOrderChannelText(orderChannelDict.getDictValue())
                .setAppointmentTime(orderAddBeanDTO.getAppointmentTime())
                .setAppointmentEndTime(DateUtil.offsetHour(orderAddBeanDTO.getAppointmentTime(), 1))
                .setRemark(orderAddBeanDTO.getRemark())
                .setLastOperatorAppointmentTime(new Date())
                .setCompanyWechatId(orderAddBeanDTO.getCompanyWechatId())
                .setCompanyWechatName(orderAddBeanDTO.getCompanyWechatName())
                .setCreateDate(DateUtil.beginOfDay(new Date()))
                .setSaleOrderId(orderAddBeanDTO.getSaleOrderId())
                .setRpProjectRepairId(orderAddBeanDTO.getRpProjectRepairId())
                .setIsCj(orderAddBeanDTO.getIsCj())
                .setIsZl(orderAddBeanDTO.getIsZl())
                .setIsQd(false)
        //.setSource("小程序建单")
        ;

        //根据上面不派网点，默认派商户，代表此时绝对有adminWebsit
        AdminWebsit adminWebsit = adminWebsitService.getById(orderAddBeanDTO.getWebsitId());
        if (adminWebsit == null) {
            throw new RemoteServiceException("网点不存在");
        }

        //师傅建单必须要选择网点，且此单必须派给当前师傅
        Boolean isWorker = false;
        User user = null;
        if (StringUtils.isNotBlank(orderAddBeanDTO.getUserId())) {
            user = userService.getById(orderAddBeanDTO.getUserId());
            if (user.getType().equals(UserTypeEnum.WORKER.getKey())) {
//                if(!adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())){
//                    throw new RemoteServiceException("请选择网点");
//                }
                if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
                    isWorker = true;
                }
            }
        }
        //派网点
        if (StringUtils.isNotBlank(orderAddBeanDTO.getWebsitId())) {
            //商户
            if (adminWebsit.getType().equals(AdminWebsitTypeEnum.B.getKey())) {
                orderBaseStatusEnum = OrderBaseStatusEnum.DSHPG;
            }
            //网点
            if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
                orderBaseStatusEnum = OrderBaseStatusEnum.DWDPG;
                if (pgOrderBase.getIsQd()) {
                    orderBaseStatusEnum = OrderBaseStatusEnum.DQD;
                }

                pgOrderBase.setWebsitId(adminWebsit.getWebsitId());
                pgOrderBase.setWebsitName(adminWebsit.getName());
                pgOrderBase.setWebsitPhone(adminWebsit.getWebsitPhone());
                pgOrderBase.setDispatchWebsitTime(new Date());
            }
            //创建网点
            pgOrderBase.setCreateWebsitId(adminWebsit.getWebsitId());
            pgOrderBase.setCreateWebsitName(adminWebsit.getName());
        }

        //派到师傅
        if (isWorker) {

            orderBaseStatusEnum = OrderBaseStatusEnum.DJD;

            pgOrderBase.setWorkerId(user.getUserId());
            pgOrderBase.setWorkerName(user.getNickName());
            pgOrderBase.setWorkerMobile(user.getMobile());
            pgOrderBase.setWorkerIdList(user.getUserId());
            pgOrderBase.setWorkerIdcard(user.getIdCard());
            pgOrderBase.setWorkerReceTime(new Date());
            pgOrderBase.setDispatchTime(new Date());

            PgOrderWorker pgOrderWorker = new PgOrderWorker();
            pgOrderWorker.setOrderBaseId(pgOrderBase.getId());
            pgOrderWorker.setWebsitId(pgOrderBase.getWebsitId());
            pgOrderWorker.setWebsitName(pgOrderBase.getWebsitName());
            pgOrderWorker.setWorkerId(pgOrderBase.getWorkerId());
            pgOrderWorker.setWorkerName(pgOrderBase.getWorkerName());
            pgOrderWorker.setWorkerMobile(pgOrderBase.getWorkerMobile());
            pgOrderWorker.setWorkerIdcard(pgOrderBase.getWorkerIdcard());
            pgOrderWorker.setIsMaster(true);
            pgOrderWorker.insert();
        }
        //商城订单信息补充
        if (StringUtils.isNotBlank(orderAddBeanDTO.getSaleOrderId())) {
            if (!orderAddBeanDTO.getIsZl()) {
                //商城订单
                OrderInfo orderInfo = orderInfoService.getById(orderAddBeanDTO.getSaleOrderId());
                if (orderInfo != null) {
                    pgOrderBase.setSaleTotalAmount(orderInfo.getPayAmount());
                    pgOrderBase.setSaleCreateTime(orderInfo.getCreateTime());
                    pgOrderBase.setSaleRemark(orderInfo.getBuyerMsg());
                    pgOrderBase.setSource(orderInfo.getSource());
                }
            } else {
                //租赁单业务处理
                pgOrderBase = handleZl(pgOrderBase);
            }
        }
        //状态维护
        pgOrderBase.setOrderStatus(orderBaseStatusEnum.getKey());
        pgOrderBase.setOrderStatusText(orderBaseStatusEnum.getRemark());

        //保存机型
        for (PgOrderProduct orderProduct : orderAddBeanDTO.getOrderProducts()) {
            orderProduct.setOrderBaseId(pgOrderBase.getId());
            GoodsCategory goodsCategory = goodsCategoryMap.get(orderProduct.getMainId());
            if (goodsCategory == null) {
                throw new RemoteServiceException("产品大类不存在");
            }
            orderProduct.setMainName(goodsCategory.getName());

        }
        pgOrderProductService.saveBatch(orderAddBeanDTO.getOrderProducts());

        String orderTitle = this.upOrderProduct(pgOrderBase.getId());
        //保存工单
        pgOrderBase.setOrderTitle(orderTitle);
        pgOrderBase.insert();

        //重算数量
        this.reNum(pgOrderBase.getId());

        //增置服务工单
        increWorkerOrder(pgIncreOrderService.getById(pgIncreOrderId), pgOrderBase.getId());
        //维保工单
        if (StringUtils.isNotBlank(orderAddBeanDTO.getRpProjectRepairId()))
            repairProjectWorkerOrder(pgOrderBase);
        //是否租赁单
        if (orderAddBeanDTO.getIsZl() != null && orderAddBeanDTO.getIsZl()) {
            orderFlagLogic.saveOrderFlag(Lists.newArrayList(pgOrderBase.getId()), OrderFlagEnum.ZL);
        }
        //记录日志
        this.addLog(pgOrderBase, pgOrderBase.getWebsitName());

        //创建工单添加消息
        this.sendMaterialExamine(pgOrderBase.getId());

        return pgOrderBase.getId();
    }


    public String getOrderTitle(List<PgOrderProduct> pgOrderProducts) {
        if (CollectionUtils.isEmpty(pgOrderProducts)) {
            return "";
        }
        String orderTitle = "";
        //产品信息(编辑是单独维护的，只需要处理新增)
        for (PgOrderProduct orderProduct : pgOrderProducts) {
            orderTitle += orderProduct.getMainName() + "x" + orderProduct.getNum() + ",";
        }
        if (StringUtils.isNotBlank(orderTitle)) {
            orderTitle = orderTitle.substring(0, orderTitle.length() - 1);
        }
        return orderTitle;
    }

    /**
     * 增值服务工单
     *
     * @param orderBaseId
     */
    public void increWorkerOrderInsideCode(String orderBaseId) {
        List<String> insideCodes = pgOrderProductService.lambdaQuery()
                .eq(PgOrderProduct::getOrderBaseId, orderBaseId)
                .list().stream().filter(v -> StringUtils.isNotBlank(v.getInsideCode()))
                .map(PgOrderProduct::getInsideCode).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(insideCodes)) {
            return;
        }
        List<PgIncreOrder> list = pgIncreOrderService.lambdaQuery().in(PgIncreOrder::getInsideCode, insideCodes).list();
        for (PgIncreOrder pgIncreOrder : list) {
            this.increWorkerOrder(pgIncreOrder, orderBaseId);
        }
    }


    /**
     * 维保工单
     *
     * @param orderBase
     */
    public void repairProjectWorkerOrder(PgOrderBase orderBase) {
        RpProjectRepair rpProjectRepair = rpProjectRepairService.getById(orderBase.getRpProjectRepairId());
        if (rpProjectRepair == null) {
            throw new RemoteServiceException("维保配置不存在");
        }
        if (rpProjectRepair.getStartTime().getTime() > new Date().getTime()
                || rpProjectRepair.getEndTime().getTime() < new Date().getTime()) {
            throw new RemoteServiceException("维保时间已失效");
        }

        String lng = "", lat = "";
        //反查经纬度
        String location = lbsAmapLogic.getLocationByAddress(rpProjectRepair.getProvince() + rpProjectRepair.getCity() + rpProjectRepair.getArea() + rpProjectRepair.getStreet() + rpProjectRepair.getAddress());
        lng = location.split(",")[0];
        lat = location.split(",")[1];

        orderBase.setUserName(rpProjectRepair.getManger())
                .setLinkName(rpProjectRepair.getManger())
                .setUserMobile(rpProjectRepair.getMobile())
                .setProvinceId(rpProjectRepair.getProvinceId())
                .setProvince(rpProjectRepair.getProvince())
                .setCityId(rpProjectRepair.getCityId())
                .setCity(rpProjectRepair.getCity())
                .setAreaId(rpProjectRepair.getAreaId())
                .setArea(rpProjectRepair.getArea())
                .setStreetId(rpProjectRepair.getStreetId())
                .setStreet(rpProjectRepair.getStreet())
                .setAddress(rpProjectRepair.getAddress())
                .setGpsAddress(rpProjectRepair.getAddress())
                .setLng(lng)
                .setLat(lat);
        orderBase.setFeePayMethod(rpProjectRepair.getFeePayMethod());
        orderBase.setIsAllFee(rpProjectRepair.getIsAllFee());
        orderBase.setRpProjectRepairName(rpProjectRepair.getProjectName());
        orderBase.updateById();

        orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBase.getId()), OrderFlagEnum.WB);
    }


    /**
     * 增值服务工单
     *
     * @param pgIncreOrder
     */
    public void increWorkerOrder(PgIncreOrder pgIncreOrder, String orderBaseId) {
        if (pgIncreOrder == null) {
            //throw new RemoteServiceException("增值服务订单不存在");
            return;
        }
        if (!StringUtils.equals(pgIncreOrder.getPayStatus(), PayStatusEnum.PAID.getKey())) {
            //throw new RemoteServiceException("当前订单未支付");
            log.error("【当前增置服务单未支付】");
            return;
        }
        if (pgIncreOrder.getServiceEndTime().getTime() < new Date().getTime()) {
            log.error("【增值服务已过期】");
            //throw new RemoteServiceException("增值服务已过期");
            return;
        }

        pgOrderBaseService.lambdaUpdate()
                .set(PgOrderBase::getPgIncreOrderId, pgIncreOrder.getId())
                .set(PgOrderBase::getSaleOrderId, pgIncreOrder.getId())
                .set(PgOrderBase::getPgIncreId, pgIncreOrder.getPgIncreId())
                .set(PgOrderBase::getPgIncreItemId, pgIncreOrder.getPgIncreItemId())
                .set(PgOrderBase::getPgIncreWebsitId, pgIncreOrder.getWebsitId())
                .set(PgOrderBase::getPgIncreWebsitName, pgIncreOrder.getWebsitName())
                .eq(PgOrderBase::getId, orderBaseId)
                .update();

        orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBaseId), OrderFlagEnum.YB);
    }

    /**
     * 取消工单
     *
     * @param orderBaseId
     */
    @Transactional
    public void cancel(String orderBaseId) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if (pgOrderBase == null) {
            throw new RemoteServiceException("工单不存在");
        }
        if (OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())) {
            throw new RemoteServiceException("已完工不可取消");
        }
        pgOrderBase.setOrderStatus(OrderBaseStatusEnum.YQX.getKey());
        pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.YQX.getRemark());
        pgOrderBase.updateById();

        orderLogLogic.addLog(orderBaseId, "取消工单", "取消工单", "");
    }

    /**
     * 激活工单
     *
     * @param orderBaseId
     */
    public void active(String orderBaseId) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if (pgOrderBase == null) {
            throw new RemoteServiceException("工单不存在");
        }
        if (!(OrderBaseStatusEnum.YQX.getKey().equals(pgOrderBase.getOrderStatus())
                || OrderBaseStatusEnum.FWZT.getKey().equals(pgOrderBase.getOrderStatus())
                || OrderBaseStatusEnum.FWQX.getKey().equals(pgOrderBase.getOrderStatus())
                || OrderBaseStatusEnum.YCGB.getKey().equals(pgOrderBase.getOrderStatus()))) {
            throw new RemoteServiceException("非已取消工单不可激活");
        }
        OrderBaseStatusEnum orderBaseStatus = OrderBaseStatusEnum.DSHPG;
        if (StringUtils.isNotBlank(pgOrderBase.getWebsitId())) {
            orderBaseStatus = OrderBaseStatusEnum.DWDPG;
            if (pgOrderBase != null && pgOrderBase.getIsQd()) {
                orderBaseStatus = OrderBaseStatusEnum.DQD;
            }
        }
        if (StringUtils.isNotBlank(pgOrderBase.getWorkerId())) {
            orderBaseStatus = OrderBaseStatusEnum.FWZ;
        }
        pgOrderBase.setOrderStatus(orderBaseStatus.getKey());
        pgOrderBase.setOrderStatusText(orderBaseStatus.getRemark());
        pgOrderBase.updateById();
        orderLogLogic.addLog(orderBaseId, "激活工单", "激活工单", "");
    }

    /**
     * 驳回工单到服务中状态
     *
     * @param orderBaseId
     */
    @Transactional
    public void reject(String orderBaseId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if (pgOrderBase == null) {
            throw new RemoteServiceException("工单不存在");
        }
        if (!StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.YWG.getKey())
                && !StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.GCSZX.getKey())
                && !StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.WDWG.getKey())
                && !StringUtils.equals(pgOrderBase.getOrderStatus(), OrderBaseStatusEnum.YWGO.getKey())
        ) {
            throw new RemoteServiceException("非已完工待结算状态不可驳回");
        }
        pgOrderBase.setOrderStatus(OrderBaseStatusEnum.FWZ.getKey());
        pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.FWZ.getRemark());
        pgOrderBase.updateById();

        String optWebsitName = "";
        if (CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds())) {
            final AdminWebsit websit = adminWebsitService.getById(adminUser.getAdminWebsitIds().get(0));
            optWebsitName = websit.getName();
        }

        orderLogLogic.addLog(orderBaseId, "未完工驳回", adminUser.getNickName() + "于" + DateUtil.formatDateTime(new Date()) + "驳回工单到服务中", optWebsitName);
        //删除标记
        orderFlagLogic.deleteOrderFlag(orderBaseId, OrderFlagEnum.YWG);
        //删除产生的结算数据
        settleOrderLogic.clearSettleOrderFee(orderBaseId);
    }


    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    public OrderAddBeanDTO detail(String id) {
        PgOrderBase orderBase = pgOrderBaseService.getById(id);
        if (Objects.isNull(orderBase)) {
            throw new RemoteServiceException("工单编号不存在");
        }
        OrderAddBeanDTO orderAddBeanDTO = BeanUtil.copyProperties(orderBase, OrderAddBeanDTO.class);
        //产品信息
        List<PgOrderProduct> list = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, id).list();
        orderAddBeanDTO.setOrderProducts(list);
        //师傅信息
        orderAddBeanDTO.setOrderWorkers(this.orderWorkerList(id));
        //标记
        orderAddBeanDTO.setOrderFlags(orderFlagLogic.list(id));
        return orderAddBeanDTO;
    }

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

            orderLogLogic.addLog(orderBaseId, orderFlagEnum.getRemark(), "" + orderFlagEnum.getRemark(), "");
        } else {
            orderFlagLogic.deleteOrderFlag(orderBaseId, orderFlagEnum);

            orderLogLogic.addLog(orderBaseId, orderFlagEnum.getRemark(), "取消" + orderFlagEnum.getRemark(), "");
        }

    }


    /**
     * 工单的师傅列表
     *
     * @param orderBaseId
     * @return
     */
    public List<PgOrderWorker> orderWorkerList(String orderBaseId) {
        //师傅信息
        List<PgOrderWorker> orderWorkers = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, orderBaseId).list();
        return orderWorkers;
    }


    /**
     * 工单创建组装
     *
     * @param orderAddBeanDTO
     * @param isAdd
     * @return
     */
    private PgOrderBase conver(PgOrderBase old, OrderAddBeanDTO orderAddBeanDTO, Boolean isAdd) {

        //工单渠道 （维保的工单渠道是写死的，不能检查）
//        SysDictCompany orderChannelDict = sysDictCompanyLogic.dictByTypeOfCode(SysDictConstant.ORDER_CHANNEL, orderAddBeanDTO.getOrderChannelId(),companyWechatId);
//        if(orderChannelDict == null){
//            throw new RemoteServiceException("工单渠道不存在");
//        }
        //工单类型
        OrderSmallType orderSmallType = orderSmallTypeService.getById(orderAddBeanDTO.getOrderSmallType());
        if (orderSmallType == null) {
            throw new RemoteServiceException("工单类型不存在【orderSmallType】");
        }
        //业务类型，工单大类
        OrderTypeEnum orderTypeEnum = BaseEnum.keyToEnum(OrderTypeEnum.class, orderSmallType.getOrderType());
        if (orderTypeEnum == null) {
            throw new RemoteServiceException("工单类型业务线错误【orderType】");
        }

        if (StringUtils.isBlank(orderAddBeanDTO.getWebsitId()) && StringUtils.isBlank(orderAddBeanDTO.getCompanyWechatId())) {
            throw new RemoteServiceException("请选择网点");
        }

        //PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderAddBeanDTO.getId());
//        if(pgOrderBase == null){
//            pgOrderBase = new PgOrderBase();
//        }
        PgOrderBase pgOrderBase = null;
        if (old != null) {
            //深拷贝
            pgOrderBase = ObjectUtil.clone(old);
        } else {
            pgOrderBase = new PgOrderBase();
        }

        if (!isAdd && OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())) {
            throw new RemoteServiceException("当前状态不可编辑工单");
        }
        if (StringUtils.isBlank(orderAddBeanDTO.getSource())) {
            orderAddBeanDTO.setSource("自建工单");
        }
        if (StringUtils.isBlank(orderAddBeanDTO.getLng()) || StringUtils.isBlank(orderAddBeanDTO.getLat())) {
            String gpsAddress = orderAddBeanDTO.getProvince() + orderAddBeanDTO.getCity() + orderAddBeanDTO.getArea() + orderAddBeanDTO.getStreet() + orderAddBeanDTO.getAddress();
            //反查经纬度
            String location = lbsAmapLogic.getLocationByAddress(gpsAddress);
            orderAddBeanDTO.setLng(location.split(",")[0]);
            orderAddBeanDTO.setLat(location.split(",")[1]);
        }
        pgOrderBase.setUserName(orderAddBeanDTO.getUserName())
                .setLinkName(orderAddBeanDTO.getLinkName())
                .setUserMobile(orderAddBeanDTO.getUserMobile())
                .setUserMobile2(orderAddBeanDTO.getUserMobile2())
                .setProvinceId(orderAddBeanDTO.getProvinceId())
                .setProvince(orderAddBeanDTO.getProvince())
                .setCityId(orderAddBeanDTO.getCityId())
                .setCity(orderAddBeanDTO.getCity())
                .setAreaId(orderAddBeanDTO.getAreaId())
                .setArea(orderAddBeanDTO.getArea())
                .setStreetId(orderAddBeanDTO.getStreetId())
                .setStreet(orderAddBeanDTO.getStreet())
                .setAddress(orderAddBeanDTO.getAddress())
                .setGpsAddress(orderAddBeanDTO.getGpsAddress())
                .setOrderChannelId(orderAddBeanDTO.getOrderChannelId())
                .setOrderChannelText(orderAddBeanDTO.getOrderChannelText())
//                .setOrderChannelId(orderChannelDict.getDictCode())
//                .setOrderChannelText(orderChannelDict.getDictValue())
                .setAppointmentTime(orderAddBeanDTO.getAppointmentTime())
                .setAppointmentEndTime(orderAddBeanDTO.getAppointmentEndTime())
                .setSaleCompany(orderAddBeanDTO.getSaleCompany())
                .setRemark(orderAddBeanDTO.getRemark())
                .setLastOperatorAppointmentTime(new Date())
                .setRpProjectRepairId(orderAddBeanDTO.getRpProjectRepairId())
                .setLng(orderAddBeanDTO.getLng())
                .setLat(orderAddBeanDTO.getLat())
                .setSaleType(orderAddBeanDTO.getSaleType())
                .setSaleOrderId(orderAddBeanDTO.getSaleOrderId())
                .setProjectNo(orderAddBeanDTO.getProjectNo())
                .setProjectName(orderAddBeanDTO.getProjectName())
                .setIsZl(orderAddBeanDTO.getIsZl())
                .setIsQd(orderAddBeanDTO.getIsQd())
                .setSource(orderAddBeanDTO.getSource())
                .setServiceStatus(orderAddBeanDTO.getServiceStatus())
                .setComplaint(orderAddBeanDTO.getComplaint())
                .setUrgent(orderAddBeanDTO.getUrgent())
                .setEvaluate(orderAddBeanDTO.getEvaluate())
                .setSalesPlatform(orderAddBeanDTO.getSalesPlatform())
                .setBuyName(orderAddBeanDTO.getBuyName())
                .setSalesTypeName(orderAddBeanDTO.getSalesTypeName())
                .setReqStatus(orderAddBeanDTO.getReqStatus())
                .setReqText(orderAddBeanDTO.getReqText())
                .setReqType(orderAddBeanDTO.getReqType())
                .setServiceOrderId(orderAddBeanDTO.getServiceOrderId())
                .setSalesOrderId(orderAddBeanDTO.getSalesOrderId())
                .setManagerName(orderAddBeanDTO.getManagerName())
                .setOperateEntity(orderAddBeanDTO.getOperateEntity())
                .setMainName(orderAddBeanDTO.getMainName())
        ;

        OrderBaseStatusEnum orderBaseStatusEnum = OrderBaseStatusEnum.DSHPG;
        AdminWebsit adminWebsit = null;
        //网点
        if (StringUtils.isNotBlank(orderAddBeanDTO.getWebsitId())) {
            adminWebsit = adminWebsitService.getById(orderAddBeanDTO.getWebsitId());
            if (adminWebsit == null) {
                throw new RemoteServiceException("网点不存在");
            }
            if (adminWebsit.getType().equals(AdminWebsitTypeEnum.B.getKey())) {
                orderBaseStatusEnum = OrderBaseStatusEnum.DSHPG;
            }
            if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())
                    && (orderBaseStatusEnum == OrderBaseStatusEnum.DSHPG || orderBaseStatusEnum == OrderBaseStatusEnum.DWDPG || orderBaseStatusEnum == OrderBaseStatusEnum.DQD)) {
                orderBaseStatusEnum = OrderBaseStatusEnum.DWDPG;
                if (pgOrderBase.getIsQd() != null && pgOrderBase.getIsQd()) {
                    orderBaseStatusEnum = OrderBaseStatusEnum.DQD;
                }
            }
            pgOrderBase.setWebsitId(adminWebsit.getWebsitId());
            pgOrderBase.setWebsitName(adminWebsit.getName());
            pgOrderBase.setWebsitPhone(adminWebsit.getWebsitPhone());
            //只记录第一次
            if (pgOrderBase.getDispatchWebsitTime() == null) {
                pgOrderBase.setDispatchWebsitTime(new Date());
            }
        }
        //师傅
        String workerIdsStr = "";
        if (CollectionUtils.isNotEmpty(orderAddBeanDTO.getOrderWorkers())) {
            //如果是待网点派工的工单，此时变更状态为待接单
            if (orderBaseStatusEnum == OrderBaseStatusEnum.DWDPG || orderBaseStatusEnum == OrderBaseStatusEnum.DQD ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.FL ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.CJ ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.YPD ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DXSPD ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DZBPG ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DWDSPGP ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DXSSPGP ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DTJXSSPGP ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DFZXPD ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DFZXSPGP ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.XSBH ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.TJXSBH ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.ZBBH ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.FZXBH ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.WDBH ||
                    orderBaseStatusEnum == OrderBaseStatusEnum.DFZXPD


            )
                orderBaseStatusEnum = OrderBaseStatusEnum.DJD;

            List<String> workerIds = orderAddBeanDTO.getOrderWorkers().stream().map(PgOrderWorker::getWorkerId).collect(Collectors.toList());
            workerIdsStr = StringUtils.join(workerIds, ",");

            PgOrderWorker masterWorker = orderAddBeanDTO.getOrderWorkers().get(0);
            pgOrderBase.setWorkerId(masterWorker.getWorkerId());
            pgOrderBase.setWorkerName(masterWorker.getWorkerName());
            pgOrderBase.setWorkerMobile(masterWorker.getWorkerMobile());
            pgOrderBase.setWorkerIdcard(masterWorker.getWorkerIdcard());
            pgOrderBase.setWebsitId(masterWorker.getWebsitId());
            pgOrderBase.setWebsitName(masterWorker.getWebsitName());
            pgOrderBase.setWorkerIdList(workerIdsStr);
            //只记录第一次
            if (pgOrderBase.getDispatchTime() == null) {
                pgOrderBase.setDispatchTime(new Date());
            }
            //旧单状态，如果是派师傅之后的状态则根据旧单的状态来
            if (StringUtils.isNotBlank(pgOrderBase.getOrderStatus())) {
                OrderBaseStatusEnum oldOrderBaseStatusEnum = BaseEnum.keyToEnum(OrderBaseStatusEnum.class, pgOrderBase.getOrderStatus());
                if (!OrderBaseStatusEnum.notDispatchWorker().contains(oldOrderBaseStatusEnum.getKey())) {
                    orderBaseStatusEnum = oldOrderBaseStatusEnum;
                }
            }

        } else {
            pgOrderBase.setWorkerId("");
            pgOrderBase.setWorkerName("");
            pgOrderBase.setWorkerMobile("");
            pgOrderBase.setWorkerIdcard("");
            pgOrderBase.setWorkerIdList("");
        }

        pgOrderBase.setOrderSmallType(orderAddBeanDTO.getOrderSmallType())
                .setOrderSmallTypeText(orderSmallType.getOrderSmallTypeText())
                .setOrderType(orderSmallType.getOrderType())
                .setOrderTypeText(orderTypeEnum.getRemark());

        if (isAdd) {
            pgOrderBase.setCreateDate(DateUtil.beginOfDay(new Date()));
        }
        pgOrderBase.setOrderStatus(orderBaseStatusEnum.getKey());
        pgOrderBase.setOrderStatusText(orderBaseStatusEnum.getRemark());

        //租赁
        pgOrderBase = this.handleZl(pgOrderBase);
        return pgOrderBase;
    }

    /**
     * 租赁业务处理
     *
     * @param pgOrderBase
     */
    public PgOrderBase handleZl(PgOrderBase pgOrderBase) {
        //如果是租赁单，根据销售单号判断是否还有未完成的单
        if (Objects.nonNull(pgOrderBase.getIsZl()) && pgOrderBase.getIsZl() && StringUtils.isNotBlank(pgOrderBase.getSaleOrderId())) {
            Integer count = pgOrderBaseService.lambdaQuery()
                    .ne(StringUtils.isNotBlank(pgOrderBase.getId()), PgOrderBase::getId, pgOrderBase.getId())
                    .eq(PgOrderBase::getIsZl, true)
                    .eq(PgOrderBase::getSaleOrderId, pgOrderBase.getSaleOrderId())
                    .notIn(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.isOver())
                    .ne(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.YQX.getKey())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException("存在进行中的报修单，请耐心等候");
            }
        }
        if (pgOrderBase.getIsZl() != null && pgOrderBase.getIsZl() && StringUtils.isNotBlank(pgOrderBase.getSaleOrderId())) {
            LeaseOrder leaseOrder = leaseOrderService.getById(pgOrderBase.getSaleOrderId());
            if (leaseOrder != null) {
                //渠道
                SysDictCompany orderChannelDict = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, "商城", leaseOrder.getCompanyWechatId());
                pgOrderBase.setUserName(leaseOrder.getUserName());
                pgOrderBase.setUserMobile(leaseOrder.getUserMobile());
                pgOrderBase.setLinkName(leaseOrder.getUserName());
                if (orderChannelDict != null) {
                    pgOrderBase.setOrderChannelId(orderChannelDict.getDictCode());
                    pgOrderBase.setOrderChannelText(orderChannelDict.getDictValue());
                }
                pgOrderBase.setUserId(leaseOrder.getUserId());
                pgOrderBase.setSaleTotalAmount(leaseOrder.getTotalAmount());
                pgOrderBase.setSaleCreateTime(leaseOrder.getCreateTime());
                pgOrderBase.setSaleRemark(leaseOrder.getRemark());
                pgOrderBase.setSource(leaseOrder.getSource());
            }
        }
        return pgOrderBase;
    }

    /**
     * 生成过程反馈
     *
     * @param pgOrderBase
     * @param websitName
     */
    public void addLog(PgOrderBase pgOrderBase, String websitName) {
        //自建工单
        orderLogLogic.addLog(pgOrderBase.getId(), "创建工单", "创建工单-自建工单", websitName);
        //派工网点
        if (StringUtils.isNotBlank(pgOrderBase.getWebsitId())) {
            orderLogLogic.addLog(pgOrderBase.getId(), "指派网点", "派工给网点【" + pgOrderBase.getWebsitName() + "】", websitName);
        }
        //派工给师傅
        if (StringUtils.isNotBlank(pgOrderBase.getWorkerId())) {
            orderLogLogic.addLog(pgOrderBase.getId(), "指派师傅", "派工给师傅【" + pgOrderBase.getWorkerName() + "】", websitName);
        }
        //预约
        if (pgOrderBase.getAppointmentTime() != null && pgOrderBase.getAppointmentEndTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("HH");
            SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm");
            int hour = Integer.parseInt(sdf2.format(pgOrderBase.getAppointmentTime()));
            String s = hour >= 12 ? "下午" : "上午";

            String format = sdf3.format(pgOrderBase.getAppointmentTime());
            String format1 = sdf3.format(pgOrderBase.getAppointmentEndTime());

            String s2 = StringUtils.isNotBlank(pgOrderBase.getAppointmentRemark()) ? "备注:" + pgOrderBase.getAppointmentRemark() : "";
            orderLogLogic.addLog(pgOrderBase.getId(), "用户预约", "预约时间:" + sdf.format(pgOrderBase.getAppointmentTime())+" "+format+"-"+format1 + " "  + "," + s2, websitName);
        }
    }

    public Region getRegion(String province, String city, String area, String street) {
        Region one = regionService.lambdaQuery()
                .like(Region::getProvinceName,province).eq(Region::getCityName,city).eq(Region::getAreaName,area).eq(Region::getName,street).last("limit 1").one();
        return one;
    }

    /**
     * 机型列表
     */
    public List<PgOrderProduct> listOrderProduct(String orderBaseId) {
        return pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, orderBaseId).list();
    }

    /**
     * 新增机型
     *
     * @param orderProduct
     */
    @Transactional
    public List<PgOrderProduct> addOrderProduct(PgOrderProduct orderProduct) {
        if (orderProduct.getNum() <= 0) {
            throw new RemoteServiceException("数量不可小于0");
        }
        orderProduct.insert();

        String orderTitle = this.upOrderProduct(orderProduct.getOrderBaseId());

        //日志
        PgOrderBase orderBase = pgOrderBaseService.getById(orderProduct.getOrderBaseId());
        orderBase.setOrderTitle(orderTitle);
        orderBase.updateById();

        orderLogLogic.addLog(orderProduct.getOrderBaseId(), "新增机型", "机型名称【" + orderProduct.getProductName() + "】,数量【" + orderProduct.getNum() + "】", orderBase.getWebsitName());
        //重算数量
        this.reNum(orderProduct.getOrderBaseId());

        return listOrderProduct(orderProduct.getOrderBaseId());
    }

    /**
     * 生成采集并返回服务内容
     *
     * @param id
     * @return
     */
    public String upOrderProduct(String id) {

        List<PgOrderProduct> list = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, id)
                .list();

        for (PgOrderProduct pgOrderProduct : list) {

            pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getOrderBaseId, id)
                    .eq(PgOrderProductDetail::getOrderProductId, pgOrderProduct.getId())
                    .set(PgOrderProductDetail::getBrandId, pgOrderProduct.getBrandId())
                    .set(PgOrderProductDetail::getBrandName, pgOrderProduct.getBrandName())
                    .set(PgOrderProductDetail::getMainId, pgOrderProduct.getMainId())
                    .set(PgOrderProductDetail::getMainName, pgOrderProduct.getMainName())
                    .set(PgOrderProductDetail::getSmallId, pgOrderProduct.getSmallId())
                    .set(PgOrderProductDetail::getSmallName, pgOrderProduct.getSmallName())
                    .set(PgOrderProductDetail::getProductId, pgOrderProduct.getProductId())
                    .set(PgOrderProductDetail::getProductName, pgOrderProduct.getProductName())
                    .set(PgOrderProductDetail::getImgUrl, pgOrderProduct.getImgUrl())
                    .set(PgOrderProductDetail::getInsideCode, pgOrderProduct.getInsideCode())
                    .update();


            Integer count = pgOrderProductDetailService.lambdaQuery()
                    .eq(PgOrderProductDetail::getOrderBaseId, id)
                    .eq(PgOrderProductDetail::getOrderProductId, pgOrderProduct.getId()).count();

            if (!count.equals(pgOrderProduct.getNum())) {

                if (count > pgOrderProduct.getNum()) {
                    pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getOrderBaseId, id)
                            .eq(PgOrderProductDetail::getOrderProductId, pgOrderProduct.getId())
                            .in(PgOrderProductDetail::getStatus, "WAIT", "WAIT_SAVE").remove();

                    Integer countTwo = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                            .eq(PgOrderProductDetail::getOrderProductId, pgOrderProduct.getId()).count();

                    if (countTwo > pgOrderProduct.getNum())
                        throw new RemoteServiceException(pgOrderProduct.getProductName() + "该机型已经采集" + countTwo + "台，不允许改小台数");

                }

                for (int i = 0; i < pgOrderProduct.getNum(); i++) {
                    Integer num = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                            .eq(PgOrderProductDetail::getOrderProductId, pgOrderProduct.getId()).count();
                    if (num.equals(pgOrderProduct.getNum()))
                        break;

                    Integer sort = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                            .count();
                    PgOrderProductDetail pgOrderProductDetail = BeanUtil.toBean(pgOrderProduct, PgOrderProductDetail.class);
                    pgOrderProductDetail.setId(null);
                    pgOrderProductDetail.setNum(1);
                    pgOrderProductDetail.setSort(sort + 1);
                    pgOrderProductDetail.setOrderProductId(pgOrderProduct.getId());
                    pgOrderProductDetail.insert();
                }

            }
        }

        return getOrderTitle(list);
    }

    /**
     * 编辑机型
     *
     * @param pgOrderProduct
     */
    @Transactional
    public List<PgOrderProduct> updateOrderProduct(PgOrderProduct pgOrderProduct) {
        if (pgOrderProduct.getNum() <= 0) {
            throw new RemoteServiceException("数量不可小于0");
        }
        //旧机型
        PgOrderProduct oldProduct = pgOrderProductService.getById(pgOrderProduct.getId());
        pgOrderProduct.updateById();
        String orderTitle = this.upOrderProduct(pgOrderProduct.getOrderBaseId());
        //日志
        List<String> logs = new ArrayList<>();
        String s1 = CommonUtils.supplyLog("机型名称", oldProduct.getProductName(), pgOrderProduct.getProductName());
        String s2 = CommonUtils.supplyLog("数量", oldProduct.getNum(), pgOrderProduct.getNum());
        if (StringUtils.isNotBlank(s1)) {
            logs.add(s1);
        }
        if (StringUtils.isNotBlank(s2)) {
            logs.add(s2);
        }
        PgOrderBase orderBase = pgOrderBaseService.getById(pgOrderProduct.getOrderBaseId());
        orderBase.setOrderTitle(orderTitle);
        orderBase.updateById();
        if (CollectionUtils.isNotEmpty(logs)) {
            orderLogLogic.addLog(pgOrderProduct.getOrderBaseId(), "编辑机型", StringUtils.join(logs, ";"), orderBase.getWebsitName());
        }

        //重算数量
        this.reNum(pgOrderProduct.getOrderBaseId());

        this.doProductDetailGonDan(pgOrderProduct);

        return listOrderProduct(pgOrderProduct.getOrderBaseId());
    }


    private void doProductDetailGonDan(PgOrderProduct pgOrderProducts) {


        //判断有无导入过
        List<PgOrderProductDetail> pgOrderProductDetails = pgOrderProductDetailService.lambdaQuery()
                .in(PgOrderProductDetail::getOrderProductId, pgOrderProducts.getId()).list();

        pgOrderProductDetailService.lambdaUpdate()
                .in(PgOrderProductDetail::getOrderProductId, pgOrderProducts.getId()).remove();

        if (!CollectionUtils.isEmpty(pgOrderProductDetails)) {

            int sort = 0;
            List<PgOrderProductDetail> pgOrderProductDetailList = pgOrderProductDetails.stream()
                    .filter(item -> !item.getStatus().equals("WAIT")).collect(Collectors.toList());

            for (PgOrderProductDetail pgOrderProductDetail : pgOrderProductDetailList) {
                if (sort >= pgOrderProducts.getNum())
                    break;
                pgOrderProductDetail.setSort(sort + 1);
                pgOrderProductDetail.setOrderProductId(pgOrderProducts.getId());

                pgOrderProductDetail.insert();
                sort++;
            }

            List<PgOrderProductDetail> pgOrderProductDetailListWait = pgOrderProductDetails.stream()
                    .filter(item -> item.getStatus().equals("WAIT")).collect(Collectors.toList());

            for (PgOrderProductDetail pgOrderProductDetail : pgOrderProductDetailListWait) {
                if (sort >= pgOrderProducts.getNum())
                    break;
                pgOrderProductDetail.setSort(sort + 1);
                pgOrderProductDetail.setOrderProductId(pgOrderProducts.getId());

                pgOrderProductDetail.insert();
                sort++;
            }
            if (sort < pgOrderProducts.getNum()) {
                List<PgOrderProductDetail> newProductDetail = new ArrayList<>();
                while (true) {
                    if (sort >= pgOrderProducts.getNum())
                        break;
                    PgOrderProductDetail pgOrderProductDetail = BeanUtil.toBean(pgOrderProducts, PgOrderProductDetail.class);
                    pgOrderProductDetail.setId(null);
                    pgOrderProductDetail.setNum(1);
                    pgOrderProductDetail.setSort(sort + 1);
                    pgOrderProductDetail.setOrderProductId(pgOrderProducts.getId());
                    newProductDetail.add(pgOrderProductDetail);
                    sort++;
                }
                pgOrderProductDetailService.saveBatch(newProductDetail);
            }

        } else {

            //生成新的待采集数据
            int sort = 0;
            List<PgOrderProductDetail> newProductDetail = new ArrayList<>();
            while (true) {
                if (sort >= pgOrderProducts.getNum())
                    break;
                PgOrderProductDetail pgOrderProductDetail = BeanUtil.toBean(pgOrderProducts, PgOrderProductDetail.class);
                pgOrderProductDetail.setId(null);
                pgOrderProductDetail.setNum(1);
                pgOrderProductDetail.setSort(sort + 1);
                pgOrderProductDetail.setOrderProductId(pgOrderProducts.getId());
                newProductDetail.add(pgOrderProductDetail);
                sort++;
            }
            pgOrderProductDetailService.saveBatch(newProductDetail);
        }


    }

    /**
     * 删除机型
     *
     * @param orderProductId
     */
    @Transactional
    public List<PgOrderProduct> deleteOrderProduct(String orderProductId) {
        //旧机型
        PgOrderProduct oldProduct = pgOrderProductService.getById(orderProductId);

        //不可删除最后一个机型
        Integer count = pgOrderProductService.lambdaQuery()
                .eq(PgOrderProduct::getOrderBaseId, oldProduct.getOrderBaseId())
                .ne(PgOrderProduct::getId, orderProductId)
                .count();
        if (count == 0) {
            throw new RemoteServiceException("不可删除所有机型");
        }

        pgOrderProductService.removeById(orderProductId);
        this.removeDetail(orderProductId);

        List<PgOrderProduct> list = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, oldProduct.getOrderBaseId()).list();

        //日志
        PgOrderBase orderBase = pgOrderBaseService.getById(oldProduct.getOrderBaseId());
        orderBase.setOrderTitle(getOrderTitle(list))
                .updateById();

        orderLogLogic.addLog(oldProduct.getOrderBaseId(), "删除机型", "机型名称【" + oldProduct.getProductName() + "】,数量【" + oldProduct.getNum() + "】", orderBase.getWebsitName());

        //重算数量
        this.reNum(oldProduct.getOrderBaseId());

        return listOrderProduct(orderProductId);
    }

    private void removeDetail(String orderProductId) {
        if (pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderProductId, orderProductId)
                .in(PgOrderProductDetail::getStatus, "OK", "WAIT_OK").count() > 0)
            throw new RemoteServiceException("已完工采集，不可删除机型");
        pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getOrderProductId, orderProductId).remove();
    }


    /**
     * 重算工单主表的完成数量
     *
     * @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 newOrderBase
     * @param orderAddBeanDTO
     * @return 是否变更了师傅
     */
    public Boolean updateOrderLog(PgOrderBase oldOrderBase, PgOrderBase newOrderBase, OrderAddBeanDTO orderAddBeanDTO) {
        //PgOrderBase oldOrderBase = pgOrderBaseService.getById(newOrderBase.getId());
        StringBuffer logs = new StringBuffer();

        String oldWorkerNames = "";
        String newWorkerNames = "";
        //旧的师傅组合
        List<String> collect = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, newOrderBase.getId())
                .list().stream().map(PgOrderWorker::getWorkerName).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            oldWorkerNames = StringUtils.join(collect);
        }
        //新的师傅组合名称
        List<String> collect1 = orderAddBeanDTO.getOrderWorkers().stream().map(PgOrderWorker::getWorkerName).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect1)) {
            newWorkerNames = StringUtils.join(collect1);
        }

        String changeWorker = CommonUtils.supplyLog("工程师", oldWorkerNames, newWorkerNames);

        log.info("旧网点：{}，新网点：{}", oldOrderBase.getWebsitName(), newOrderBase.getWebsitName());

        logs.append(CommonUtils.supplyLog("客户名称", oldOrderBase.getUserName(), newOrderBase.getUserName()))
                .append(CommonUtils.supplyLog("联系人", oldOrderBase.getLinkName(), newOrderBase.getLinkName()))
                .append(CommonUtils.supplyLog("客户电话", oldOrderBase.getUserMobile(), newOrderBase.getUserMobile()))
                .append(CommonUtils.supplyLog("客户电话2", oldOrderBase.getUserMobile2(), newOrderBase.getUserMobile2()))
                //.append(supplyLog("用户属性", oldOrderBase.getUserAttr(), newOrderBase.getUserAttr()))
                .append(CommonUtils.supplyLog("客户地址", oldOrderBase.getProvince() + oldOrderBase.getCity()
                                + oldOrderBase.getArea() + oldOrderBase.getStreet(),
                        newOrderBase.getProvince() + newOrderBase.getCity() + newOrderBase.getArea()
                                + newOrderBase.getStreet()))
                .append(CommonUtils.supplyLog("GPS地址", oldOrderBase.getGpsAddress(), newOrderBase.getGpsAddress()))
                .append(CommonUtils.supplyLog("详细地址", oldOrderBase.getAddress(), newOrderBase.getAddress()))
//                .append(supplyLog("派工方式",DispatchFlagEnum.valueOf(oldOrderBase.getDispatchFlag()).getValue(),DispatchFlagEnum.valueOf(newOrderBase.getDispatchFlag()).getValue()))
                //.append(CommonUtils.supplyLog("服务商网点", oldOrderBase.getWebsitName(), newOrderBase.getWebsitName()))
                .append(CommonUtils.supplyLog("工单渠道", oldOrderBase.getOrderChannelText(), newOrderBase.getOrderChannelText()))
                .append(CommonUtils.supplyLog("预约上门日期", DateUtil.formatDate(oldOrderBase.getAppointmentTime()), DateUtil.formatDate(newOrderBase.getAppointmentTime())))
                .append(CommonUtils.supplyLog("销售单位", oldOrderBase.getSaleCompany(), newOrderBase.getSaleCompany()))
                .append(CommonUtils.supplyLog("网点名称", oldOrderBase.getWebsitName(), newOrderBase.getWebsitName()))
                .append(changeWorker)
                .append(CommonUtils.supplyLog("备注", oldOrderBase.getRemark(), newOrderBase.getRemark()))
                .append(CommonUtils.supplyLog("是否抢单", oldOrderBase.getIsQd(), newOrderBase.getIsQd()))
        ;

        if (StringUtils.isBlank(logs.toString()))
            return false;

        orderLogLogic.addLog(oldOrderBase.getId(), "编辑服务单", logs.toString(), oldOrderBase.getWebsitName());

        return StringUtils.isNotBlank(changeWorker);
    }


    public IPage<OrderBase2VO> orderBaseList2(WorkOrderZfireParam zfireParamBean) {
        //特殊处理 "异常单","待预约" 的查询条件
        if (zfireParamBean.getParamValue("a.order_status") instanceof String) {
            String paramValue = (String) zfireParamBean.getParamValue("a.order_status");
            if (StringUtils.equals(paramValue, OrderBaseStatusEnum.YCD.getKey()) || StringUtils.equals(paramValue, OrderBaseStatusEnum.DYY.getKey())) {
                zfireParamBean.removeParam("a.order_status");
            }
        }

        AdminUserCom adminUser = commonLogic.getAdminUser();

        FieldUtils.supplyParam(zfireParamBean, OrderBase2VO.class, commonLogic.getAdminUser());

        IPage<OrderBase2VO> page = commonMapper.orderBaseList2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getType());

        //服务单标识
        if (zfireParamBean.getPageSize() != -1 && page.getTotal() > 0) {
            List<String> orderBaseIds = page.getRecords()
                    .stream()
                    .map(OrderBase2VO::getId)
                    .collect(Collectors.toList());
            Map<String, List<PgOrderFlag>> mapList = orderFlagLogic.list(orderBaseIds);
            for (OrderBase2VO orderBaseVO : page.getRecords()) {
                orderBaseVO.setOrderFlags(mapList.get(orderBaseVO.getId()));
            }
        }

        // 合计结算总金额
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<OrderBase2VO> records = page.getRecords();
            List<String> productList = records.stream().map(OrderBase2VO::getPgOrderProductId).collect(Collectors.toList());
            List<PgOrderSettleNorm> settleNorms = pgOrderSettleNormService.lambdaQuery()
                    .in(PgOrderSettleNorm::getPgOrderProductId, productList)
                    .list();
            Map<String, List<PgOrderSettleNorm>> groupMap = settleNorms.stream().collect(Collectors.groupingBy(PgOrderSettleNorm::getPgOrderProductId));

            for (OrderBase2VO record : records) {
                List<PgOrderSettleNorm> normList = groupMap.get(record.getPgOrderProductId());
                if (CollectionUtils.isNotEmpty(normList)) {
                    BigDecimal total = BigDecimal.ZERO;
                    for (PgOrderSettleNorm norm : normList) {
                        total = total.add(norm.getSettleAmount());
                    }
                    record.setSettleAmount(total);
                } else {
                    record.setSettleAmount(BigDecimal.ZERO);
                }
            }
        }

        return page;
    }

    public List<Map<String, Object>> countStatus2(String orderSmallTypeText) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<Map<String, Object>> maps = orderBaseCMapper.countOrderStatus2(adminUser.getCompanyWechatId(), adminUser.getAdminWebsitIds(), adminUser.getType(), orderSmallTypeText);
        return maps;
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(PgOrderBase pgOrderBase) {
        pgOrderBase.updateById();
    }
}
