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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.gree.mall.manager.bean.SyncOrderDto;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.common.RegionBean;
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.ExamineStatusEnum;
import com.gree.mall.manager.enums.UserTypeEnum;
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.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.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.StringUtil;
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 org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author ：lijh
 * @description：TODO
 * @date ：2024/4/1 16:43
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderBaseExcelLogic {

    private final CommonLogic commonLogic;
    private final OrderBaseLogic orderBaseLogic;
    private final OrderFlagLogic orderFlagLogic;
    private final SysDictCompanyLogic sysDictCompanyLogic;
    private final LbsAmapLogic lbsAmapLogic;
    private final SettleOrderLogic settleOrderLogic;
    private final PgOrderBaseService pgOrderBaseService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final AdminWebsitService adminWebsitService;
    private final PgOrderProductService pgOrderProductService;
    private final GoodsCategoryService goodsCategoryService;
    private final UserService userService;
    private final RegionService regionService;
    private final WebsitUserService websitUserService;
    private final PgOrderProductDetailService pgOrderProductDetailService;
    private final UserWaitService userWaitService;
    private final PgOrderOperatorLogService pgOrderOperatorLogService;


    /**
     * 导入工单
     *
     * @param rows
     */
    @Transactional
    public void importOrder(List<Object> rows, String createWebsitId, String createWebsitName) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //品牌map
        Map<String, Brand> brandMap = sysDictCompanyLogic.brandMapOfName(adminUser.getCompanyWechatId());
        //工单类型map
        Map<String, OrderSmallType> orderSmallTypeMap = sysDictCompanyLogic.orderSmallTypeMap(adminUser.getCompanyWechatId());
        //产品大类，小类map
        List<GoodsCategory> goodsCategoryList = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(GoodsCategory::getType, 2).list();
        Map<String, GoodsCategory> categoryMap1 = goodsCategoryList.stream().filter(v -> v.getLevel() == 1)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        Map<String, GoodsCategory> categoryMap2 = goodsCategoryList.stream().filter(v -> v.getLevel() == 2)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        //工单渠道
        Map<String, SysDictCompany> orderChannelMap = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, adminUser.getCompanyWechatId());
        //网点名称
        Map<String, AdminWebsit> adminWebsitMap = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(adminUser.getType() == 0, AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .list().stream().collect(Collectors.toMap(AdminWebsit::getName, Function.identity()));
        //已完工标识
        List<String> overOrderIds = new ArrayList<>();
        //旧工单id集
        List<String> oldOrderBaseIds = new ArrayList<>();
        //本次导入的旧的工单集合 (并清空旧的师傅信息)
        Map<String, PgOrderBase> oldOrderBaseMap = getOldOrderBase(rows);
        //本商户的所有师傅
        Map<String, User> workerMap = getWorkers(adminUser.getCompanyWechatId());
        //本次新增的工单
        List<PgOrderBase> addPgOrderBase = new ArrayList<>();

        //需要保存的集合
        List<PgOrderProduct> pgOrderProducts = new ArrayList<>();
        List<PgOrderWorker> pgOrderWorkers = new ArrayList<>();
        int index = 0;
        for (Object o : rows) {
            ++index;
            String errPrefix = "第" + (index) + "行,工单号："+ rows.get(1)+":";
            OrderBaseStatusEnum orderBaseStatusEnum = OrderBaseStatusEnum.DSHPG;
            List<String> row = (List<String>) o;
            CommonUtils.initList(row, 100);
            String websitName = row.get(0);
            String orderBaseId = row.get(1);
            String source = row.get(2);
            String orderSmallType = row.get(3);
            String orderChannel = row.get(4);
            String userName = row.get(5);
            String linkName = row.get(6);
            String userMobile = row.get(7);
            String userMobile2 = row.get(8);
            String address = row.get(9);
            String saleCompany = row.get(10);
            String orderStatus = row.get(11);
            String workerName = row.get(12);
            String workerMobile = row.get(13);
            String createTime = row.get(14);
            String isQdText = row.get(15);
            String remark = row.get(16);

            Boolean isQd = StringUtils.equals(isQdText, "是");

            if (StringUtils.isAnyBlank(orderBaseId, source, orderSmallType, source, userName, linkName, userMobile, address, createTime)) {
                throw new RemoteServiceException(errPrefix + "黄色区域为必填项");
            }
            if (userMobile.length() > 11) {
                throw new RemoteServiceException(errPrefix + "请输入正确的客户手机号");
            }
            if (StringUtils.isNotBlank(userMobile2) && userMobile2.length() > 11) {
                throw new RemoteServiceException(errPrefix + "请输入正确的客户手机号2");
            }
            oldOrderBaseIds.add(orderBaseId);

            String location = lbsAmapLogic.getLocationByAddress(address);
            RegionBean regionBean = lbsAmapLogic.getRegionByLngLat(location);
            Region region = orderBaseLogic.getRegion(regionBean.getProvinceName(), regionBean.getCityName(), regionBean.getAreaName(), regionBean.getName());
            if (region == null) {
                //throw new RemoteServiceException(errPrefix+"地址【"+address+"】解析失败");
                region = regionService.lambdaQuery()
                        .eq(Region::getCityName, "广州市")
                        .eq(Region::getAreaName, "天河区")
                        .eq(Region::getName, "五山街道")
                        .last("limit 1").one();
                location = "0,0";
            }

            DateTime dateTime = null;
            try {
                dateTime = DateUtil.parseDateTime(createTime);
                if (dateTime == null) {
                    throw new RemoteServiceException(errPrefix + "创建时间请输入【2023-12-28 00:00:00】的格式");
                }
            } catch (Exception e) {
                throw new RemoteServiceException(errPrefix + "创建时间请输入【2023-12-28 00:00:00】的格式");
            }

            AdminWebsit adminWebsit = null;
            if (StringUtils.isNotBlank(websitName)) {
                adminWebsit = adminWebsitMap.get(websitName);
                if (adminWebsit == null) {
                    throw new RemoteServiceException(errPrefix + "网点名称不存在");
                }
            }

            Boolean addFlag = true;
            PgOrderBase old = oldOrderBaseMap.get(orderBaseId);
            if (old != null) {
                //throw new RemoteServiceException(errPrefix+"工单号已存在");
                addFlag = false;

                if (OrderBaseStatusEnum.isOver().contains(old.getOrderStatus())) {
                    throw new RemoteServiceException(errPrefix + "工单号【" + orderBaseId + "】当前工单状态不可编辑");
                }
            }
            OrderSmallType orderSmallType1 = orderSmallTypeMap.get(orderSmallType);
            if (orderSmallType1 == null) {
                throw new RemoteServiceException(errPrefix + "工单类型不存在");
            }
            SysDictCompany orderChannelDict = orderChannelMap.get(orderChannel);
            if (orderChannelDict == null) {
                throw new RemoteServiceException(errPrefix + "工单渠道不存在");
            }

            //工单状态
            OrderBaseStatusEnum importBaseStatusEnum = null;
            if (StringUtils.isNotBlank(orderStatus)) {
                importBaseStatusEnum = BaseEnum.valueToEnum(OrderBaseStatusEnum.class, orderStatus);
                if (importBaseStatusEnum == null) {
                    throw new RemoteServiceException(errPrefix + "工单状态不存在");
                }
                //如果已完工，师傅和网点不能为空
                if (OrderBaseStatusEnum.isOver().contains(importBaseStatusEnum.getKey())) {

                    if (StringUtils.isBlank(workerMobile) || StringUtils.isBlank(websitName)) {
                        throw new RemoteServiceException(errPrefix + "完工状态师傅和网点不能为空");
                    }
                    overOrderIds.add(orderBaseId);
                }
            }


            PgOrderBase pgOrderBase = new PgOrderBase();
            pgOrderBase.setId(orderBaseId);
            pgOrderBase.setIsImport(true);
            pgOrderBase.setOrderType(orderSmallType1.getOrderType());
            pgOrderBase.setOrderTypeText(BaseEnum.keyToEnum(OrderTypeEnum.class, orderSmallType1.getOrderType()).getRemark());
            pgOrderBase.setOrderSmallType(orderSmallType1.getId());
            pgOrderBase.setOrderSmallTypeText(orderSmallType1.getOrderSmallTypeText());
            pgOrderBase.setCompanyWechatId(adminUser.getCompanyWechatId());
            pgOrderBase.setCompanyWechatName(adminUser.getCompanyName());
            if (adminWebsit != null) {
                orderBaseStatusEnum = OrderBaseStatusEnum.DWDPG;
                if (isQd) {
                    orderBaseStatusEnum = OrderBaseStatusEnum.DQD;
                }

                pgOrderBase.setWebsitId(adminWebsit.getWebsitId());
                pgOrderBase.setWebsitName(adminWebsit.getName());
                pgOrderBase.setWebsitPhone(adminWebsit.getWebsitPhone());
                pgOrderBase.setDispatchWebsitTime(new Date());
                pgOrderBase.setIsQd(isQd);

                //是否派对了师傅
                User worker = null;
                if (StringUtils.isNotBlank(workerMobile)) {

                    int workerIndex = 0;
                    String[] workerMobiles = StringUtils.split(workerMobile, ",");
                    long count1 = Lists.newArrayList(workerMobiles).stream().distinct().count();
                    if (count1 != workerMobiles.length) {
                        throw new RemoteServiceException(errPrefix + "师傅手机号不可重复");
                    }
                    for (String mobile : workerMobiles) {
                        worker = workerMap.get(mobile);
                        if (worker == null) {
                            throw new RemoteServiceException(errPrefix + " 师傅手机号【" + mobile + "】不存在网点【" + adminWebsit.getName() + "】");
                        }
                        Integer count = websitUserService.lambdaQuery()
                                .eq(WebsitUser::getWebsitId, adminWebsit.getWebsitId())
                                .eq(WebsitUser::getUserId, worker.getUserId())
                                .eq(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.getKey()).count();
                        if (count == 0) {
                            throw new RemoteServiceException(errPrefix + " 师傅手机号【" + mobile + "】不存在网点【" + adminWebsit.getName() + "】");
                        }

                        orderBaseStatusEnum = OrderBaseStatusEnum.DJD;

                        if (workerIndex == 0) {
                            pgOrderBase.setWorkerId(worker.getUserId());
                            pgOrderBase.setWorkerIdcard(worker.getIdCard());
                            pgOrderBase.setWorkerIdList(worker.getUserId());
                            pgOrderBase.setWorkerMobile(worker.getMobile());
                            pgOrderBase.setWorkerName(worker.getNickName());
                            pgOrderBase.setWorkerReceTime(new Date());
                            pgOrderBase.setDispatchTime(new Date());
                        }

                        PgOrderWorker pgOrderWorker = new PgOrderWorker();
                        pgOrderWorker.setOrderBaseId(orderBaseId);
                        pgOrderWorker.setWebsitId(pgOrderBase.getWebsitId());
                        pgOrderWorker.setWebsitName(pgOrderBase.getWebsitName());
                        pgOrderWorker.setWorkerId(worker.getUserId());
                        pgOrderWorker.setWorkerName(worker.getNickName());
                        pgOrderWorker.setWorkerIdcard(worker.getIdCard());
                        pgOrderWorker.setWorkerMobile(worker.getMobile());
                        pgOrderWorker.setIsMaster(workerIndex == 0);
                        //pgOrderWorker.insert();
                        pgOrderWorkers.add(pgOrderWorker);

                        workerIndex++;
                    }
                }
            }

            pgOrderBase.setOrderStatus(orderBaseStatusEnum.getKey());
            pgOrderBase.setOrderStatusText(orderBaseStatusEnum.getRemark());
            if (OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())) {
                pgOrderBase.setOverTime(new Date());
                pgOrderBase.setOverDate(new Date());
                pgOrderBase.setWebsitOverTime(new Date());
            }
            pgOrderBase.setUserName(userName);
            pgOrderBase.setLinkName(linkName);
            pgOrderBase.setUserMobile(userMobile);
            pgOrderBase.setUserMobile2(userMobile2);
            pgOrderBase.setProvinceId(region.getProvinceCode());
            pgOrderBase.setProvince(region.getProvinceName());
            pgOrderBase.setCity(region.getCityName());
            pgOrderBase.setCityId(region.getCityCode());
            pgOrderBase.setArea(region.getAreaName());
            pgOrderBase.setAreaId(region.getAreaCode());
            pgOrderBase.setStreet(region.getName());
            pgOrderBase.setStreetId(region.getId());
            pgOrderBase.setAddress(address);
            pgOrderBase.setGpsAddress(pgOrderBase.getAddress());
            //根据中文地址反查经纬度
            try {
                pgOrderBase.setLng(location.split(",")[0]);
                pgOrderBase.setLat(location.split(",")[1]);
            } catch (Exception e) {
                pgOrderBase.setLng("0");
                pgOrderBase.setLat("0");
            }
            pgOrderBase.setCreateTime(dateTime);
            pgOrderBase.setCreateDate(DateUtil.parseDate(createTime));
            pgOrderBase.setSaleCompany(saleCompany);
            pgOrderBase.setSource(source);
            pgOrderBase.setOrderChannelId(orderChannelDict.getDictCode());
            pgOrderBase.setOrderChannelText(orderChannelDict.getDictValue());
            pgOrderBase.setCreateWebsitId(createWebsitId);
            pgOrderBase.setCreateWebsitName(createWebsitName);
            if (importBaseStatusEnum != null) {
                pgOrderBase.setOrderStatus(importBaseStatusEnum.getKey());
                pgOrderBase.setOrderStatusText(importBaseStatusEnum.getRemark());
            }
            //机型
            List<PgOrderProduct> pgOrderProducts1 = this.importOrderProduct(row, pgOrderBase.getId(), index, brandMap, categoryMap1, categoryMap2);
            pgOrderProducts.addAll(pgOrderProducts1);
            //pgOrderProductService.saveBatch(pgOrderProducts);

            //总数量,未完成数量
            int totalNum = pgOrderProducts.stream().mapToInt(PgOrderProduct::getNum).sum();
            pgOrderBase.setTotalNum(totalNum);
            pgOrderBase.setUndoneNum(totalNum);
            pgOrderBase.setOrderTitle(orderBaseLogic.getOrderTitle(pgOrderProducts1));
            pgOrderBase.setRemark(remark);
            pgOrderBase.insertOrUpdate();

            //生成待采集数据
            //orderBaseLogic.upOrderProduct(pgOrderBase.getId());

            //生成待结算数据
            if (OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())) {
                if (old == null || !OrderBaseStatusEnum.isOver().contains(old.getOrderStatus())) {
                    //生成待结算数据
                    settleOrderLogic.insertSettleOrderMethod(pgOrderBase, pgOrderProducts);
                }
            }

            //保存日志
            if (addFlag) {
                addPgOrderBase.add(pgOrderBase);
            }
        }

        //生成完工标识数据
        if (CollectionUtils.isNotEmpty(overOrderIds)) {
            orderFlagLogic.saveOrderFlag(overOrderIds, OrderFlagEnum.YWG);
        }
        //生成师傅信息
        if (CollectionUtils.isNotEmpty(pgOrderWorkers)) {
            pgOrderWorkerService.saveBatch(pgOrderWorkers);
        }
        //重新生成产品信息和待采集数据
        doProductDetail(pgOrderProducts, oldOrderBaseIds);
        //创建工单添加消息
        if (CollectionUtils.isNotEmpty(addPgOrderBase)) {
            for (PgOrderBase pgOrderBase : addPgOrderBase) {
                orderBaseLogic.sendMaterialExamine(pgOrderBase.getId());
                orderBaseLogic.addLog(pgOrderBase, pgOrderBase.getCreateWebsitName());
            }
        }
    }


    private List<PgOrderProduct> importOrderProduct(List<String> row, String orderBaseId, int index, Map<String, Brand> brandMap, Map<String, GoodsCategory> mainMap, Map<String, GoodsCategory> smallMap) {
//        pgOrderProductService.lambdaUpdate().eq(PgOrderProduct::getOrderBaseId,orderBaseId).remove();
//        //删除旧的待采集数据
//        pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getOrderBaseId,orderBaseId).remove();

        List<PgOrderProduct> pgOrderProducts = new ArrayList<>();
        //默认最多10个机型
        for (int i = 0; i < 10; i++) {
            String brandName = row.get(6 * i + 17);
            String mainName = row.get(6 * i + 18);
            String smallName = row.get(6 * i + 19);
            String productName = row.get(6 * i + 20);
            String productNum = row.get(6 * i + 21);
            String remark = row.get(6 * i + 22);
            if (StringUtils.isBlank(brandName)) {
                continue;
            }
            if (StringUtils.isAnyBlank(mainName, smallName, productNum)) {
                throw new RemoteServiceException("第" + (index) + "行 产品大类/产品小类/商品数量 不能为空");
            }

            GoodsCategory mainGoodsCategory = mainMap.get(mainName);
            GoodsCategory smallGoodsCategory = smallMap.get(smallName);
            Brand brand = brandMap.get(brandName);
            if (brand == null) {
                throw new RemoteServiceException("第" + (index) + "行 品牌不存在");
            }
            if (mainGoodsCategory == null) {
                throw new RemoteServiceException("第" + (index) + "行 产品大类不存在");
            }
            if (smallGoodsCategory == null) {
                throw new RemoteServiceException("第" + (index) + "行 产品小类不存在");
            }

            PgOrderProduct pgOrderProduct = new PgOrderProduct();
            pgOrderProduct.setOrderBaseId(orderBaseId);
            pgOrderProduct.setNum(Integer.parseInt(productNum));
            pgOrderProduct.setMainId(mainGoodsCategory.getCategoryId());
            pgOrderProduct.setMainName(mainName);
            pgOrderProduct.setSmallId(smallGoodsCategory.getCategoryId());
            pgOrderProduct.setSmallName(smallName);
            pgOrderProduct.setBrandId(brand.getId());
            pgOrderProduct.setBrandName(brandName);
            pgOrderProduct.setRemark(remark);
            pgOrderProduct.setProductName(productName);
            pgOrderProducts.add(pgOrderProduct);
        }
        return pgOrderProducts;
    }


    /**
     * 导入工单2
     *
     * @param rows
     */
    public void importOrder2(List<Object> rows, String createWebsitId, String createWebsitName) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //品牌map
        Map<String, Brand> brandMap = sysDictCompanyLogic.brandMapOfName(adminUser.getCompanyWechatId());
        //工单类型map
        Map<String, OrderSmallType> orderSmallTypeMap = sysDictCompanyLogic.orderSmallTypeMap(adminUser.getCompanyWechatId());
        //产品大类，小类map
        List<GoodsCategory> goodsCategoryList = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(GoodsCategory::getType, 2).list();
        Map<String, GoodsCategory> mainMap = goodsCategoryList.stream().filter(v -> v.getLevel() == 1)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        Map<String, GoodsCategory> smallMap = goodsCategoryList.stream().filter(v -> v.getLevel() == 2)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        //工单渠道
        Map<String, SysDictCompany> orderChannelMap = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, adminUser.getCompanyWechatId());
        //网点名称
        Map<String, AdminWebsit> adminWebsitMap = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(adminUser.getType() == 0, AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .list().stream().collect(Collectors.toMap(AdminWebsit::getName, Function.identity()));
        //完工的工单集合
        List<String> overOrderIds = new ArrayList<>();
        //旧的工单号集合
        List<String> oldOrderBaseIds = new ArrayList<>();
        //本次导入的旧的工单集合
        Map<String, PgOrderBase> oldOrderBaseMap = getOldOrderBase(rows);
        //本商户的所有师傅
        Map<String, User> workerMap = getWorkers(adminUser.getCompanyWechatId());
        //本次新增的工单
        List<PgOrderBase> addPgOrderBase = new ArrayList<>();
        //本次保存的集合
        List<PgOrderProduct> pgOrderProducts = new ArrayList<>();
        List<PgOrderWorker> pgOrderWorkers = new ArrayList<>();

        int index = 0;
        for (Object o : rows) {
            ++index;
            String errPrefix = "第" + (index) + "行,工单号："+ rows.get(1)+":";
            OrderBaseStatusEnum orderBaseStatusEnum = OrderBaseStatusEnum.DSHPG;
            List<String> row = (List<String>) o;
            CommonUtils.initList(row, 100);
            String websitName = row.get(0);
            String orderChannel = row.get(1);
            String orderBaseId = row.get(2);
            String userName = row.get(3);
            String userMobile = row.get(4);
            String userMobile2 = row.get(5);
            String address = row.get(6);
            String mainName = row.get(7);
            String smallName = row.get(8);
            String productName = row.get(9);
            String workerName = row.get(10);
            String workerMobile = row.get(11);
            String orderStatus = row.get(12);
            String orderSmallType = row.get(13);
            String brandName = row.get(14);
            Integer num = StringUtils.isBlank(row.get(15)) ? 1 : Integer.parseInt(row.get(15));
            BigDecimal amount = StringUtils.isBlank(row.get(16)) ? BigDecimal.ZERO : new BigDecimal(row.get(16));

            if (StringUtils.isAnyBlank(orderBaseId, orderChannel, userName, userMobile, address, mainName, smallName, productName, orderSmallType, brandName)) {
                throw new RemoteServiceException(errPrefix + "黄色区域为必填项");
            }

            if (userMobile.length() > 11) {
                throw new RemoteServiceException(errPrefix + "请输入正确的客户手机号");
            }
            if (StringUtils.isNotBlank(userMobile2) && userMobile2.length() > 11) {
                throw new RemoteServiceException(errPrefix + "请输入正确的客户手机号2");
            }

            oldOrderBaseIds.add(orderBaseId);

            String location = lbsAmapLogic.getLocationByAddress(address);
            RegionBean regionBean = lbsAmapLogic.getRegionByLngLat(location);
            Region region = orderBaseLogic.getRegion(regionBean.getProvinceName(), regionBean.getCityName(), regionBean.getAreaName(), regionBean.getName());
            if (region == null) {
                //throw new RemoteServiceException(errPrefix+"地址【"+address+"】解析失败");
                region = regionService.lambdaQuery()
                        .eq(Region::getCityName, "广州市")
                        .eq(Region::getAreaName, "天河区")
                        .eq(Region::getName, "五山街道")
                        .last("limit 1").one();
                location = "0,0";
            }

            AdminWebsit adminWebsit = null;
            if (StringUtils.isNotBlank(websitName)) {
                adminWebsit = adminWebsitMap.get(websitName);
                if (adminWebsit == null) {
                    throw new RemoteServiceException(errPrefix + "网点名称不存在");
                }
            }
            Boolean addFlag = true;
            PgOrderBase old = oldOrderBaseMap.get(orderBaseId);
            if (old != null) {
                addFlag = false;

                if (OrderBaseStatusEnum.isOver().contains(old.getOrderStatus())) {
                    throw new RemoteServiceException(errPrefix + "工单号【" + orderBaseId + "】当前工单状态不可编辑");
                }
            }
            OrderSmallType orderSmallType1 = orderSmallTypeMap.get(orderSmallType);
            if (orderSmallType1 == null) {
                throw new RemoteServiceException(errPrefix + "工单类型不存在");
            }
            SysDictCompany orderChannelDict = orderChannelMap.get(orderChannel);
            if (orderChannelDict == null) {
                throw new RemoteServiceException(errPrefix + "工单渠道不存在");
            }

            //工单状态
            OrderBaseStatusEnum importBaseStatusEnum = null;
            if (StringUtils.isNotBlank(orderStatus)) {
                importBaseStatusEnum = BaseEnum.valueToEnum(OrderBaseStatusEnum.class, orderStatus);
                if (importBaseStatusEnum == null) {
                    throw new RemoteServiceException(errPrefix + "工单状态不存在");
                }
                //如果已完工，师傅和网点不能为空
                if (OrderBaseStatusEnum.isOver().contains(importBaseStatusEnum.getKey())) {

                    if (StringUtils.isBlank(workerMobile) || StringUtils.isBlank(websitName)) {
                        throw new RemoteServiceException(errPrefix + "完工状态师傅和网点不能为空");
                    }

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


            PgOrderBase pgOrderBase = new PgOrderBase();
            pgOrderBase.setId(orderBaseId);
            pgOrderBase.setIsImport(true);
            pgOrderBase.setOrderType(orderSmallType1.getOrderType());
            pgOrderBase.setOrderTypeText(BaseEnum.keyToEnum(OrderTypeEnum.class, orderSmallType1.getOrderType()).getRemark());
            pgOrderBase.setOrderSmallType(orderSmallType1.getId());
            pgOrderBase.setOrderSmallTypeText(orderSmallType1.getOrderSmallTypeText());
            pgOrderBase.setCompanyWechatId(adminUser.getCompanyWechatId());
            pgOrderBase.setCompanyWechatName(adminUser.getCompanyName());
            if (adminWebsit != null) {
                orderBaseStatusEnum = OrderBaseStatusEnum.DWDPG;


                pgOrderBase.setWebsitId(adminWebsit.getWebsitId());
                pgOrderBase.setWebsitName(adminWebsit.getName());
                pgOrderBase.setWebsitPhone(adminWebsit.getWebsitPhone());
                pgOrderBase.setDispatchWebsitTime(new Date());

                //是否派对了师傅
                User worker = null;
                if (StringUtils.isNotBlank(workerMobile)) {

                    int workerIndex = 0;
                    String[] workerMobiles = StringUtils.split(workerMobile, ",");
                    long count1 = Lists.newArrayList(workerMobiles).stream().distinct().count();
                    if (count1 != workerMobiles.length) {
                        throw new RemoteServiceException(errPrefix + "师傅手机号不可重复");
                    }
                    for (String mobile : workerMobiles) {
                        worker = workerMap.get(mobile);
                        if (worker == null) {
                            throw new RemoteServiceException(errPrefix + " 师傅手机号【" + mobile + "】不存在网点【" + adminWebsit.getName() + "】");
                        }
                        Integer count = websitUserService.lambdaQuery()
                                .eq(WebsitUser::getWebsitId, adminWebsit.getWebsitId())
                                .eq(WebsitUser::getUserId, worker.getUserId())
                                .eq(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.getKey()).count();
                        if (count == 0) {
                            throw new RemoteServiceException(errPrefix + " 师傅手机号【" + mobile + "】不存在网点【" + adminWebsit.getName() + "】");
                        }

                        orderBaseStatusEnum = OrderBaseStatusEnum.DJD;

                        if (workerIndex == 0) {
                            pgOrderBase.setWorkerId(worker.getUserId());
                            pgOrderBase.setWorkerIdcard(worker.getIdCard());
                            pgOrderBase.setWorkerIdList(worker.getUserId());
                            pgOrderBase.setWorkerMobile(worker.getMobile());
                            pgOrderBase.setWorkerName(worker.getNickName());
                            pgOrderBase.setWorkerReceTime(new Date());
                            pgOrderBase.setDispatchTime(new Date());
                        }

                        PgOrderWorker pgOrderWorker = new PgOrderWorker();
                        pgOrderWorker.setOrderBaseId(orderBaseId);
                        pgOrderWorker.setWebsitId(pgOrderBase.getWebsitId());
                        pgOrderWorker.setWebsitName(pgOrderBase.getWebsitName());
                        pgOrderWorker.setWorkerId(worker.getUserId());
                        pgOrderWorker.setWorkerName(worker.getNickName());
                        pgOrderWorker.setWorkerIdcard(worker.getIdCard());
                        pgOrderWorker.setWorkerMobile(worker.getMobile());
                        pgOrderWorker.setIsMaster(workerIndex == 0);
                        //pgOrderWorker.insert();
                        pgOrderWorkers.add(pgOrderWorker);
                        workerIndex++;
                    }
                }
            }

            pgOrderBase.setOrderStatus(orderBaseStatusEnum.getKey());
            pgOrderBase.setOrderStatusText(orderBaseStatusEnum.getRemark());
            pgOrderBase.setUserName(userName);
            pgOrderBase.setLinkName(userName);
            pgOrderBase.setUserMobile(userMobile);
            pgOrderBase.setUserMobile2(userMobile2);
            pgOrderBase.setProvinceId(region.getProvinceCode());
            pgOrderBase.setProvince(region.getProvinceName());
            pgOrderBase.setCity(region.getCityName());
            pgOrderBase.setCityId(region.getCityCode());
            pgOrderBase.setArea(region.getAreaName());
            pgOrderBase.setAreaId(region.getAreaCode());
            pgOrderBase.setStreet(region.getName());
            pgOrderBase.setStreetId(region.getId());
            pgOrderBase.setAddress(address);
            pgOrderBase.setGpsAddress(pgOrderBase.getAddress());
            //根据中文地址反查经纬度
            try {
                pgOrderBase.setLng(location.split(",")[0]);
                pgOrderBase.setLat(location.split(",")[1]);
            } catch (Exception e) {
                pgOrderBase.setLng("0");
                pgOrderBase.setLat("0");
            }
            pgOrderBase.setCreateTime(new Date());
            pgOrderBase.setCreateDate(new Date());
            pgOrderBase.setSource("导入");
            pgOrderBase.setOrderChannelId(orderChannelDict.getDictCode());
            pgOrderBase.setOrderChannelText(orderChannelDict.getDictValue());
            pgOrderBase.setCreateWebsitId(createWebsitId);
            pgOrderBase.setCreateWebsitName(createWebsitName);
            if (importBaseStatusEnum != null) {
                pgOrderBase.setOrderStatus(importBaseStatusEnum.getKey());
                pgOrderBase.setOrderStatusText(importBaseStatusEnum.getRemark());
            }
            if (OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())) {
                pgOrderBase.setOverTime(new Date());
                pgOrderBase.setOverDate(new Date());
                pgOrderBase.setWebsitOverTime(new Date());

                overOrderIds.add(orderBaseId);
            }
            pgOrderBase.setSettleServiceAmount(amount);

            //商品信息
            GoodsCategory mainGoodsCategory = mainMap.get(mainName);
            GoodsCategory smallGoodsCategory = smallMap.get(smallName);
            Brand brand = brandMap.get(brandName);
            if (brand == null) {
                throw new RemoteServiceException("第" + (index) + "行 品牌不存在");
            }
            if (mainGoodsCategory == null) {
                throw new RemoteServiceException("第" + (index) + "行 产品大类不存在");
            }
            if (smallGoodsCategory == null) {
                throw new RemoteServiceException("第" + (index) + "行 产品小类不存在");
            }
            PgOrderProduct pgOrderProduct = new PgOrderProduct();
            pgOrderProduct.setOrderBaseId(orderBaseId);
            pgOrderProduct.setNum(num);
            pgOrderProduct.setMainId(mainGoodsCategory.getCategoryId());
            pgOrderProduct.setMainName(mainName);
            pgOrderProduct.setSmallId(smallGoodsCategory.getCategoryId());
            pgOrderProduct.setSmallName(smallName);
            pgOrderProduct.setBrandId(brand.getId());
            pgOrderProduct.setBrandName(brandName);
            pgOrderProduct.setProductName(productName);
            //pgOrderProduct.insert();
            pgOrderProducts.add(pgOrderProduct);
            //生成待采集数据
            //orderBaseLogic.upOrderProduct(pgOrderBase.getId());
            pgOrderBase.setTotalNum(num);
            pgOrderBase.setUndoneNum(num);
            pgOrderBase.setOrderTitle(orderBaseLogic.getOrderTitle(pgOrderProducts));
            pgOrderBase.insertOrUpdate();
            //保存日志
            if (addFlag) {
                //创建工单添加消息
//                orderBaseLogic.sendMaterialExamine(pgOrderBase.getId());
//                orderBaseLogic.addLog(pgOrderBase, pgOrderBase.getCreateWebsitName());
                addPgOrderBase.add(pgOrderBase);
            }
        }
        //生成完工标识数据
        if (CollectionUtils.isNotEmpty(overOrderIds)) {
            orderFlagLogic.saveOrderFlag(overOrderIds, OrderFlagEnum.YWG);
        }
        //生成师傅信息
        if (CollectionUtils.isNotEmpty(pgOrderWorkers)) {
            pgOrderWorkerService.saveBatch(pgOrderWorkers);
        }
        //重新生成产品信息和待采集数据
        doProductDetail(pgOrderProducts, oldOrderBaseIds);
        //创建工单添加消息
        if (CollectionUtils.isNotEmpty(addPgOrderBase)) {
            for (PgOrderBase pgOrderBase : addPgOrderBase) {
                orderBaseLogic.sendMaterialExamine(pgOrderBase.getId());
                orderBaseLogic.addLog(pgOrderBase, pgOrderBase.getCreateWebsitName());
            }
        }
    }


    /**
     * 获取旧的工单集
     *
     * @param rows
     * @return
     */
    public Map<String, PgOrderBase> getOldOrderBase(List<Object> rows) {
        List<String> orderBaseIds = new ArrayList<>();
        //本次导入的所有工单号
        for (Object o : rows) {
            List<String> row = (List<String>) o;
            String orderBaseId = row.get(1);
            orderBaseIds.add(orderBaseId);
        }

        //先清空师傅
        pgOrderWorkerService.lambdaUpdate().in(PgOrderWorker::getOrderBaseId, orderBaseIds).remove();

        List<PgOrderBase> list = pgOrderBaseService.lambdaQuery().in(PgOrderBase::getId, orderBaseIds).list();
        Map<String, PgOrderBase> oldOrderBaseMap = list.stream().collect(Collectors.toMap(v -> v.getId(), Function.identity()));
        return oldOrderBaseMap;
    }

    /**
     * 获取旧的师傅集
     *
     * @param companyWechatId
     * @return
     */
    public Map<String, User> getWorkers(String companyWechatId) {
        List<User> workers = userService.lambdaQuery().eq(User::getCompanyWechatId, companyWechatId).ne(User::getMobile, "")
                .eq(User::getType, UserTypeEnum.WORKER.getKey()).list();
        Map<String, User> workerMap = workers.stream().collect(Collectors.toMap(v -> v.getMobile(), Function.identity()));
        return workerMap;
    }


    private void doProductDetail(List<PgOrderProduct> pgOrderProducts, List<String> oldOrderBaseIds) {
        if (CollectionUtils.isNotEmpty(pgOrderProducts)) {
            //删除旧的产品数据
            pgOrderProductService.lambdaUpdate().in(PgOrderProduct::getOrderBaseId, oldOrderBaseIds).remove();
            //删除旧的待采集数据
            pgOrderProductDetailService.lambdaUpdate().in(PgOrderProductDetail::getOrderBaseId, oldOrderBaseIds).remove();
            //生成新的产品数据
            pgOrderProductService.saveBatch(pgOrderProducts);
            //生成新的待采集数据
            int sort = 0;
            List<PgOrderProductDetail> newProductDetail = new ArrayList<>();
            for (PgOrderProduct pgOrderProduct : pgOrderProducts) {
                PgOrderProductDetail pgOrderProductDetail = BeanUtil.toBean(pgOrderProduct, PgOrderProductDetail.class);
                pgOrderProductDetail.setId(null);
                pgOrderProductDetail.setNum(1);
                pgOrderProductDetail.setSort(sort + 1);
                pgOrderProductDetail.setOrderProductId(pgOrderProduct.getId());
                newProductDetail.add(pgOrderProductDetail);
                sort++;
            }
            pgOrderProductDetailService.saveBatch(newProductDetail);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void import3(List<Object> rows) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        //品牌map
        Map<String, Brand> brandMap = sysDictCompanyLogic.brandMapOfName(adminUser.getCompanyWechatId());
        //工单类型map
        Map<String, OrderSmallType> orderSmallTypeMap = sysDictCompanyLogic.orderSmallTypeMap(adminUser.getCompanyWechatId());
        //产品大类，小类map
        List<GoodsCategory> goodsCategoryList = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(GoodsCategory::getType, 2).list();
        Map<String, GoodsCategory> categoryMap1 = goodsCategoryList.stream().filter(v -> v.getLevel() == 1)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        Map<String, GoodsCategory> categoryMap2 = goodsCategoryList.stream().filter(v -> v.getLevel() == 2)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().groupBy(WebsitUser::getWorkerNumber).list();
        Map<String, WebsitUser> websitUserMap = websitUsers.stream()
                .collect(Collectors.toMap(WebsitUser::getWorkerNumber, v -> v));

        List<User> users = userService.lambdaQuery().eq(User::getType, "WORKER").list();
        Map<String, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, v -> v));

        //工单渠道
        // Map<String, SysDictCompany> orderChannelMap = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, adminUser.getCompanyWechatId());
        //网点名称
        Map<String, AdminWebsit> adminWebsitMap = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(adminUser.getType() == 0, AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .list().stream().collect(Collectors.toMap(AdminWebsit::getWebsitId, Function.identity()));
        //已完工标识
        List<String> overOrderIds = new ArrayList<>();

        //本次导入的旧的工单集合 (并清空旧的师傅信息)
        // Map<String, PgOrderBase> oldOrderBaseMap = getOldOrderBase(rows);
        //本商户的所有师傅
        Map<String, User> workerMap = getWorkers(adminUser.getCompanyWechatId());
        //本次新增的工单
        List<PgOrderBase> addPgOrderBase = new ArrayList<>();

        //需要保存的集合
        List<PgOrderProduct> pgOrderProducts = new ArrayList<>();
        List<PgOrderWorker> pgOrderWorkers = new ArrayList<>();

        int index = 1;
        for (Object o : rows) {
            ++index;

            List<String> row = (List<String>) o;

            String errPrefix = "第" + (index) + "行,工单号："+ row.get(1)+":";

            String pgOrderId = row.get(0);
            String status = row.get(1);
            String serviceStatus = row.get(2);
            String orderType = row.get(3);
            String categoryType = row.get(4);
            String complaint = row.get(5);
            String userName = row.get(6);
            String userMobile = row.get(7);
            String province = row.get(8);
            String city = row.get(9);
            String area = row.get(10);
            String street = row.get(11);
            String address = row.get(12);
            String urgent = row.get(13);
            String evaluate = row.get(14);
            String source = row.get(15);
            String salesSource = row.get(16);
            String buyName = row.get(17);
            String salesTypeName = row.get(18);
            String totalNum = row.get(19);
            String undoneNum = row.get(20);
            String requirement = row.get(21);
            String requirementType = row.get(22);
            String requirementNotes = row.get(23);
            String pSize = row.get(24);
            String createWebsitName = row.get(25);
            String createWebsitId = row.get(26);
            String belongCompany = row.get(27);
            String serviceOrderId = row.get(28);
            String createTime = row.get(29);
            String salesOrderId = row.get(30);
            String appointmentTime = row.get(31);
            String appointmentEndTime = row.get(32);
            String overDate = row.get(33);
            String websitId = row.get(34);
            String websitName = row.get(35);
            String workerId = row.get(36);
            String workerName = row.get(37);
            String managerGroup = row.get(38);

            DateTime dateTime = null;
            try {
                dateTime = DateUtil.parseDateTime(createTime);
                if (dateTime == null) {
                    throw new RemoteServiceException(errPrefix + "创建时间请输入【2023-12-28 00:00:00】的格式");
                }
            } catch (Exception e) {
                throw new RemoteServiceException(errPrefix + "创建时间请输入【2023-12-28 00:00:00】的格式");
            }

            AdminWebsit adminWebsit = null;
            if (StringUtils.isNotBlank(createWebsitId)) {
                adminWebsit = adminWebsitMap.get(createWebsitId);
                if (adminWebsit == null) {
                    //throw new RemoteServiceException(errPrefix + "网点不存在");
                }
            }


            AdminWebsit adminWebsitWorker = null;
            if (StringUtils.isNotBlank(websitId)) {
                adminWebsitWorker = adminWebsitMap.get(websitId);
                if (adminWebsitWorker == null) {
                    // throw new RemoteServiceException(errPrefix + "网点不存在");
                }
            }

            OrderSmallType orderSmallType1 = orderSmallTypeMap.get(orderType);
            if (orderSmallType1 == null) {
               // throw new RemoteServiceException(errPrefix + "工单类型不存在");
            }

            //工单状态
            OrderBaseStatusEnum importBaseStatusEnum = null;
            if (StringUtils.isNotBlank(status)) {
                importBaseStatusEnum = BaseEnum.valueToEnum(OrderBaseStatusEnum.class, status);
                if (importBaseStatusEnum == null) {
                   // throw new RemoteServiceException(errPrefix + "工单状态不存在");
                }
            }

            Region region = orderBaseLogic.getRegion(province, city, area, street);
            if (region == null) {
              //  throw new RemoteServiceException(errPrefix + "地址【" + province + city + area + street + "】解析失败");
            }


            PgOrderBase pgOrderBase = new PgOrderBase();
            pgOrderBase.setId(pgOrderId);
            pgOrderBase.setIsImport(true);
            pgOrderBase.setIsImportExcel(true);
            pgOrderBase.setOrderStatus(importBaseStatusEnum == null ? null : importBaseStatusEnum.getKey());
            pgOrderBase.setOrderStatusText(importBaseStatusEnum.getRemark());
            pgOrderBase.setServiceStatus(serviceStatus);

            pgOrderBase.setOrderType(orderSmallType1 == null?orderType:orderSmallType1.getOrderType());
            pgOrderBase.setOrderTypeText(
                    orderSmallType1 == null?orderType:BaseEnum.keyToEnum(OrderTypeEnum.class, orderSmallType1.getOrderType()).getRemark()
            );


            pgOrderBase.setOrderSmallType(orderSmallType1 == null?orderType:orderSmallType1.getId());
            pgOrderBase.setOrderSmallTypeText(orderSmallType1 == null?orderType:orderSmallType1.getOrderSmallTypeText());

            pgOrderBase.setCompanyWechatId(adminUser.getCompanyWechatId());
            pgOrderBase.setCompanyWechatName(adminUser.getCompanyName());

            pgOrderBase.setComplaint(complaint);
            pgOrderBase.setUserName(userName);
            pgOrderBase.setLinkName(userName);
            pgOrderBase.setUserMobile(userMobile);


            pgOrderBase.setProvinceId(region == null?province:region.getProvinceCode());
            pgOrderBase.setProvince(region == null?province:region.getProvinceName());
            pgOrderBase.setCity(region == null?city:region.getCityName());
            pgOrderBase.setCityId(region == null?city:region.getCityCode());
            pgOrderBase.setArea(region == null?area:region.getAreaName());
            pgOrderBase.setAreaId(region == null?area:region.getAreaCode());
            pgOrderBase.setStreet(region == null?street:region.getName());
            pgOrderBase.setStreetId(region == null?street:region.getId());
            pgOrderBase.setAddress(address);

            if (adminWebsit == null) {
                pgOrderBase.setCreateWebsitId(createWebsitId);
                pgOrderBase.setCreateWebsitName(createWebsitName);
            } else {
                pgOrderBase.setCreateWebsitId(adminWebsit.getWebsitId());
                pgOrderBase.setCreateWebsitName(adminWebsit.getName());
            }

            pgOrderBase.setSource(source);
            pgOrderBase.setUrgent(urgent);
            pgOrderBase.setEvaluate(evaluate);
            pgOrderBase.setSalesPlatform(salesSource);
            pgOrderBase.setSaleCompany(buyName);
            pgOrderBase.setSalesTypeName(salesTypeName);
            pgOrderBase.setTotalNum(Convert.toInt(totalNum));
            pgOrderBase.setUndoneNum(StringUtil.isEmpty(undoneNum) ? 0 : Convert.toInt(undoneNum));
            pgOrderBase.setReqStatus(requirement);
            pgOrderBase.setReqType(requirementType);
            pgOrderBase.setReqText(requirementNotes);
            pgOrderBase.setBuyName(belongCompany);
            pgOrderBase.setCreateTime(dateTime);
            pgOrderBase.setServiceOrderId(serviceOrderId);
            pgOrderBase.setMainName(categoryType);

            DateTime appointmentTimeN = null;
            DateTime appointmentEndTimeN = null;
            if (!StringUtil.isEmpty(appointmentTime)) {
                try {
                    appointmentTimeN = DateUtil.parseDateTime(appointmentTime);
                    if (dateTime == null) {
                        throw new RemoteServiceException(errPrefix + "预约开始时间请输入【2023-12-28 00:00:00】的格式");
                    }
                } catch (Exception e) {
                    throw new RemoteServiceException(errPrefix + "预约开始时间请输入【2023-12-28 00:00:00】的格式");
                }


                try {
                    appointmentEndTimeN = DateUtil.parseDateTime(appointmentEndTime);
                    if (dateTime == null) {
                        throw new RemoteServiceException(errPrefix + "预约结束时间请输入【2023-12-28 00:00:00】的格式");
                    }
                } catch (Exception e) {
                    throw new RemoteServiceException(errPrefix + "预约结束时间请输入【2023-12-28 00:00:00】的格式");
                }
            }
            pgOrderBase.setAppointmentTime(appointmentTimeN);
            pgOrderBase.setAppointmentEndTime(appointmentEndTimeN);
            pgOrderBase.setSalesOrderId(salesOrderId);

            DateTime overDateN = null;
            if (!StringUtil.isEmpty(overDate)) {
                try {
                    overDateN = DateUtil.parseDateTime(overDate);
                    if (dateTime == null) {
                        throw new RemoteServiceException(errPrefix + "完工时间请输入【2023-12-28 00:00:00】的格式");
                    }
                } catch (Exception e) {
                    throw new RemoteServiceException(errPrefix + "完工时间请输入【2023-12-28 00:00:00】的格式");
                }
            }

            pgOrderBase.setOverDate(overDateN);
            pgOrderBase.setManagerName(managerGroup);

            if (row.size() > 39) {
                String operateEntity = row.get(39);
                pgOrderBase.setOperateEntity(operateEntity);
            }


            if (adminWebsitWorker != null) {

                pgOrderBase.setWebsitId(adminWebsitWorker.getWebsitId());
                pgOrderBase.setWebsitName(adminWebsitWorker.getName());
                pgOrderBase.setWebsitPhone(adminWebsitWorker.getWebsitPhone());
            }else {
                pgOrderBase.setWebsitId(websitId);
                pgOrderBase.setWebsitName(websitName);

            }


            if (StringUtils.isNotBlank(workerId)) {

                WebsitUser websitUser = websitUserMap.get(workerId);


                pgOrderBase.setWorkerNumber(workerId);
                pgOrderBase.setWorkerName(workerName);

                pgOrderBase.setWorkerReceTime(new Date());
                pgOrderBase.setDispatchTime(new Date());


                PgOrderWorker pgOrderWorker = new PgOrderWorker();
                pgOrderWorker.setOrderBaseId(pgOrderId);
                pgOrderWorker.setWorkerNumber(workerId);
                pgOrderWorker.setWebsitId(pgOrderBase.getWebsitId());
                pgOrderWorker.setWebsitName(pgOrderBase.getWebsitName());
                pgOrderWorker.setWorkerName(workerName);

                if (websitUser != null) {
                    pgOrderWorker.setWorkerId(websitUser.getUserId());
                    pgOrderBase.setWorkerId(websitUser.getUserId());

                    User user = userMap.get(websitUser.getUserId());

                    if (!StringUtil.isEmpty(user.getMobile())) {
                        pgOrderBase.setWorkerNumber(user.getMobile());
                        pgOrderWorker.setWorkerMobile(user.getMobile());
                    }

                }


                pgOrderWorker.setIsMaster(true);
                pgOrderWorkers.add(pgOrderWorker);

            }


            if (Convert.toInt(totalNum) > 0) {

                GoodsCategory mainGoodsCategory = categoryMap1.get(categoryType);

           /*     if (mainGoodsCategory == null) {
                    throw new RemoteServiceException("第" + (index) + "行 产品大类不存在");
                }*/

                PgOrderProduct pgOrderProduct = new PgOrderProduct();
                pgOrderProduct.setOrderBaseId(pgOrderId);
                pgOrderProduct.setNum(Convert.toInt(totalNum));
                pgOrderProduct.setMainId(mainGoodsCategory==null?categoryType:mainGoodsCategory.getCategoryId());
                pgOrderProduct.setMainName(categoryType);

                Brand brand = brandMap.get("格力");

                if (brand == null) {
                    pgOrderProduct.setBrandName("格力");
                } else {
                    pgOrderProduct.setBrandName("格力");
                    pgOrderProduct.setBrandId(brand.getId());
                }

                pgOrderProduct.setProductName(pSize);
                pgOrderProducts.add(pgOrderProduct);
            }
            addPgOrderBase.add(pgOrderBase);
            pgOrderBase.insertOrUpdate();

        }

        //生成师傅信息
        if (CollectionUtils.isNotEmpty(pgOrderWorkers)) {
            List<String> collect = addPgOrderBase.stream().map(PgOrderBase::getId).collect(Collectors.toList());
            pgOrderWorkerService.lambdaUpdate().in(PgOrderWorker::getOrderBaseId, collect).remove();
            pgOrderWorkerService.saveBatch(pgOrderWorkers);
        }

        if (CollectionUtils.isNotEmpty(pgOrderProducts)) {
            //删除旧的产品数据

            List<String> collect = addPgOrderBase.stream().map(PgOrderBase::getId).collect(Collectors.toList());
            pgOrderProductService.lambdaUpdate().in(PgOrderProduct::getOrderBaseId, collect).remove();

            //生成新的产品数据
            pgOrderProductService.saveBatch(pgOrderProducts);

            //重新生成产品信息和待采集数据
            doProductDetailGonDan(pgOrderProducts, addPgOrderBase);

            //创建工单添加消息
            if (CollectionUtils.isNotEmpty(addPgOrderBase)) {
                for (PgOrderBase pgOrderBase : addPgOrderBase) {
                    orderBaseLogic.addLog(pgOrderBase, pgOrderBase.getCreateWebsitName());
                }
            }


        }
    }


    private void doProductDetailGonDan(List<PgOrderProduct> pgOrderProducts, List<PgOrderBase> addPgOrderBaseList) {

        for (PgOrderBase pgOrderBase : addPgOrderBaseList) {

            List<PgOrderProduct> pgOrderProductList = pgOrderProducts.stream()
                    .filter(item -> item.getOrderBaseId().equals(pgOrderBase.getId()))
                    .collect(Collectors.toList());


            if (CollectionUtils.isNotEmpty(pgOrderProductList)) {
                for (PgOrderProduct pgOrderProduct : pgOrderProductList) {

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

                    pgOrderProductDetailService.lambdaUpdate()
                            .in(PgOrderProductDetail::getOrderBaseId, pgOrderBase.getId()).remove();

                    if (!CollectionUtils.isEmpty(pgOrderProductDetails)) {

                        pgOrderProduct.setId(pgOrderProduct.getId());
                        pgOrderProduct.updateById();


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

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

                            pgOrderProductDetail.insert();
                            sort++;
                        }

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

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

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

                    } else {

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

            }

        }

    }



    public void saveThreeOrder(SyncOrderDto syncOrderDto) {



        AdminUserCom adminUser = commonLogic.getAdminUser();
        //品牌map
        Map<String, Brand> brandMap = sysDictCompanyLogic.brandMapOfName(adminUser.getCompanyWechatId());
        //工单类型map
        Map<String, OrderSmallType> orderSmallTypeMap = sysDictCompanyLogic.orderSmallTypeMap(adminUser.getCompanyWechatId());
        //产品大类，小类map
        List<GoodsCategory> goodsCategoryList = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(GoodsCategory::getType, 2).list();
        Map<String, GoodsCategory> categoryMap1 = goodsCategoryList.stream().filter(v -> v.getLevel() == 1)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        Map<String, GoodsCategory> categoryMap2 = goodsCategoryList.stream().filter(v -> v.getLevel() == 2)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().groupBy(WebsitUser::getWorkerNumber).list();
        Map<String, WebsitUser> websitUserMap = websitUsers.stream()
                .collect(Collectors.toMap(WebsitUser::getWorkerNumber, v -> v));

        List<User> users = userService.lambdaQuery().eq(User::getType, "WORKER").list();
        Map<String, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, v -> v));

        //工单渠道
        // Map<String, SysDictCompany> orderChannelMap = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.ORDER_CHANNEL, adminUser.getCompanyWechatId());
        //网点名称
        Map<String, AdminWebsit> adminWebsitMap = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(adminUser.getType() == 0, AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .list().stream().collect(Collectors.toMap(AdminWebsit::getWebsitId, Function.identity()));
        //已完工标识
        List<String> overOrderIds = new ArrayList<>();

        //本次导入的旧的工单集合 (并清空旧的师傅信息)
        // Map<String, PgOrderBase> oldOrderBaseMap = getOldOrderBase(rows);
        //本商户的所有师傅
        Map<String, User> workerMap = getWorkers(adminUser.getCompanyWechatId());

        for (PgOrderBase pgOrderBase : syncOrderDto.getPgOrderBases()) {

            Region region = orderBaseLogic.getRegion(pgOrderBase.getProvince(), pgOrderBase.getCity(), pgOrderBase.getArea(), pgOrderBase.getStreet());

            if (region != null){
                pgOrderBase.setProvinceId(region.getProvinceCode());
                pgOrderBase.setCityId(region.getCityCode());
                pgOrderBase.setAreaId(region.getAreaCode());
                pgOrderBase.setStreetId(region.getId());

            }else {
                Region province = regionService.lambdaQuery()
                        .like(Region::getProvinceName,pgOrderBase.getProvince()).last("limit 1").one();


                Region city = regionService.lambdaQuery()
                        .like(Region::getProvinceName,pgOrderBase.getProvince())
                        .eq(Region::getCityName,pgOrderBase.getCity())
                        .last("limit 1").one();


                Region area = regionService.lambdaQuery()
                        .like(Region::getProvinceName,pgOrderBase.getProvince())
                        .eq(Region::getCityName,pgOrderBase.getCity())
                        .eq(Region::getAreaName,pgOrderBase.getArea())
                        .last("limit 1").one();


                Region street = regionService.lambdaQuery()
                        .like(Region::getProvinceName,pgOrderBase.getProvince())
                        .eq(Region::getCityName,pgOrderBase.getCity())
                        .eq(Region::getAreaName,pgOrderBase.getArea())
                        .eq(Region::getName,pgOrderBase.getStreet())
                        .last("limit 1").one();




                if (province == null){
                    province = new Region();

                    province.setId(IdWorker.getIdStr());
                    province.setPid("0");
                    province.setName(pgOrderBase.getProvince());
                    province.setProvinceName(pgOrderBase.getProvince());
                    province.setProvinceCode(province.getId());
                    province.setLevel(1);
                    province.insert();
                }



                if (city == null){
                    city = new Region();

                    city.setId(IdWorker.getIdStr());
                    city.setPid(province.getId());
                    city.setName(pgOrderBase.getCity());
                    city.setProvinceName(pgOrderBase.getProvince());
                    city.setProvinceCode(province.getId());
                    city.setCityCode(city.getId());
                    city.setCityName(pgOrderBase.getCity());
                    city.setLevel(2);
                    city.insert();
                }


                if (area == null){
                    area = new Region();

                    area.setId(IdWorker.getIdStr());
                    area.setPid(city.getId());
                    area.setName(pgOrderBase.getArea());

                    area.setProvinceName(pgOrderBase.getProvince());
                    area.setProvinceCode(province.getId());

                    area.setCityCode(city.getId());
                    area.setCityName(city.getCityName());

                    area.setAreaCode(area.getId());
                    area.setAreaName(pgOrderBase.getArea());

                    area.setLevel(3);
                    area.insert();
                }


                if (street == null){
                    street = new Region();

                    street.setId(IdWorker.getIdStr());
                    street.setPid(area.getId());
                    street.setName(pgOrderBase.getStreet());

                    street.setProvinceName(pgOrderBase.getProvince());
                    street.setProvinceCode(province.getId());

                    street.setCityCode(city.getId());
                    street.setCityName(city.getCityName());

                    street.setAreaCode(area.getId());
                    street.setAreaName(pgOrderBase.getArea());

                    street.setLevel(4);
                    street.insert();
                }


                pgOrderBase.setProvinceId(province.getProvinceCode());
                pgOrderBase.setCityId(city.getCityCode());
                pgOrderBase.setAreaId(area.getAreaCode());
                pgOrderBase.setStreetId(street.getId());


            }
            pgOrderBase.setIsThreeOrder(true);
        }




        pgOrderBaseService.saveBatch(syncOrderDto.getPgOrderBases());

        pgOrderWorkerService.saveBatch(syncOrderDto.getOrderWorkers());

        pgOrderProductService.saveBatch(syncOrderDto.getOrderProducts());


        if (!CollectionUtils.isEmpty(syncOrderDto.getPgOrderOperatorLogs())) {
            for (PgOrderOperatorLog pgOrderOperatorLog : syncOrderDto.getPgOrderOperatorLogs()) {
                pgOrderOperatorLog.setIsThreeOrder(true);
            }

            pgOrderOperatorLogService.saveBatch(syncOrderDto.getPgOrderOperatorLogs());
        }

    }

}
