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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.workorder.*;
import com.gree.mall.manager.commonmapper.workorder.IncreMapper;
import com.gree.mall.manager.constant.SysDictConstant;
import com.gree.mall.manager.enums.PayStatusEnum;
import com.gree.mall.manager.enums.WebsitAttrEnum;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.enums.workorder.OrderBaseStatusEnum;
import com.gree.mall.manager.enums.workorder.OrderOperatorLogTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
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.StringUtil;
import com.gree.mall.manager.utils.excel.ExcelUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
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;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChangeOrderLogic {

    @Autowired
    PgOrderBaseService pgOrderBaseService;

    @Autowired
    UserService userService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    PgOrderWorkerService pgOrderWorkerService;


    @Autowired
    PgOrderProductService pgOrderProductService;

    @Autowired
    PgOrderDetailService pgOrderDetailService;

    @Autowired
    WorkerOrderService workerOrderService;

    @Autowired
    WorkerOrderItemService workerOrderItemService;


    @Autowired
    OrderLogLogic orderLogLogic;

    @Autowired
    PgOrderProductDetailService pgOrderProductDetailService;

    @Autowired
    PgOrderOperatorLogService pgOrderOperatorLogService;

    @Autowired
    CommonLogic commonLogic;


    @Autowired
    IncreMapper increMapper;

    @Autowired
    RegionService regionService;


    @Autowired
    SysDictCompanyService sysDictCompanyService;

    @Autowired
    OrderSmallTypeService orderSmallTypeService;

    @Autowired
    GoodsCategoryService goodsCategoryService;

    @Autowired
    WebsitDispatchService websitDispatchService;

    @Autowired
    SysDictCompanyLogic sysDictCompanyLogic;

    @Autowired
    OrderBaseLogic orderBaseLogic;


    @Transactional(rollbackFor = Exception.class)
    public void changeAppointmentTime(String id, String appointmentTime, String appointmentEndTime, String remark, String imgSrc) {
        pgOrderBaseService.lambdaUpdate()
                .eq(PgOrderBase::getId, id)
                .set(!StringUtils.isEmpty(remark), PgOrderBase::getChangeRemark, remark)
                .set(!StringUtils.isEmpty(remark), PgOrderBase::getAppointmentRemark, remark)
                .set(PgOrderBase::getAppointmentTime, appointmentTime)
                .set(PgOrderBase::getAppointmentEndTime, appointmentEndTime)
                .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                .update();

//        pgOrderBaseService.lambdaUpdate()
//                .eq(PgOrderBase::getId,id)
//                .eq(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.DYY.getKey())
//                .set(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.DSHPG).update();

        this.addLog(id, imgSrc);
    }

    private void addLog(String id, String imgSrc) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setOrderBaseId(id);
        pgOrderOperatorLog.setType(OrderOperatorLogTypeEnum.GAIYUE.getRemark());
        pgOrderOperatorLog.setTypeText(OrderOperatorLogTypeEnum.GAIYUE.getRemark());
        pgOrderOperatorLog.setAppointmentTime(pgOrderBase.getAppointmentTime());
        pgOrderOperatorLog.setAppointmentEndTime(pgOrderBase.getAppointmentEndTime());
        pgOrderOperatorLog.setContent(pgOrderBase.getChangeRemark());
        pgOrderOperatorLog.setImgSrc(imgSrc);
        orderLogLogic.addLog(pgOrderOperatorLog);
    }

    @Transactional(rollbackFor = Exception.class)
    public void changeWorker(List<String> ids, List<String> workerIds, String websitId) {

        ids = ids.stream().distinct().collect(Collectors.toList());
        workerIds = workerIds.stream().distinct().collect(Collectors.toList());
        //循环师傅获得网点派工数据
        AdminWebsit adminWebsit = adminWebsitService.getById(websitId);

        List<PgOrderWorker> pgOrderWorkers = new ArrayList<>();


        boolean isDa = true;

        User userOne = userService.getById(workerIds.get(0));
        for (String workerId : workerIds) {
            User user = userService.getById(workerId);
            for (String id : ids) {

                PgOrderWorker pgOrderWorker = new PgOrderWorker();
                pgOrderWorker.setOrderBaseId(id);
                pgOrderWorker.setWebsitId(adminWebsit.getWebsitId());
                pgOrderWorker.setWebsitName(adminWebsit.getName());
                pgOrderWorker.setWorkerName(user.getNickName());
                pgOrderWorker.setWorkerId(workerId);
                pgOrderWorker.setWorkerNumber(user.getWorkerNumber());
                pgOrderWorker.setWorkerIdcard(user.getIdCard());
                pgOrderWorker.setWorkerMobile(user.getMobile());
                if (userOne.getIdCard().equals(user.getIdCard()))
                    pgOrderWorker.setIsMaster(isDa);
                else
                    pgOrderWorker.setIsMaster(false);
                pgOrderWorkers.add(pgOrderWorker);
            }

        }

/*
        List<String> orderIds = new ArrayList<>();

        for (String id : ids) {
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

            PgOrderProduct pgOrderProduct = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, id)
                    .one();

            if (websitDispatchService.lambdaQuery()
                    .eq( WebsitDispatch::getStreetCode, pgOrderBase.getStreetId())
                    .eq(WebsitDispatch::getSaleTypeId, pgOrderBase.getSaleType())
                    .eq( WebsitDispatch::getCategoryId,pgOrderProduct.getMainId())
                    .eq( WebsitDispatch::getOrderSmallId, pgOrderBase.getOrderSmallType())
                    .eq(!StringUtil.isEmpty(websitId), WebsitDispatch::getWebsitId, websitId).count() > 0) {
                orderIds.add(id);
            }
        }

        if (CollectionUtils.isEmpty(orderIds))
            return;
*/


        pgOrderBaseService.lambdaUpdate()
                .in(PgOrderBase::getId, ids)
                .set(PgOrderBase::getWorkerName, userOne.getNickName())
                .set(PgOrderBase::getWebsitId, websitId)
                .set(PgOrderBase::getWebsitName, adminWebsit.getName())
                .set(PgOrderBase::getWebsitPhone, adminWebsit.getWebsitPhone())
                .set(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.DJD.getKey())
                .set(PgOrderBase::getOrderStatusText, OrderBaseStatusEnum.DJD.getRemark())
                .set(PgOrderBase::getWorkerIdcard, userOne.getIdCard())
                .set(PgOrderBase::getWorkerId, userOne.getUserId())
                .set(PgOrderBase::getWorkerNumber, userOne.getWorkerNumber())
                .set(PgOrderBase::getWorkerMobile, userOne.getMobile())
                .set(PgOrderBase::getDispatchTime, new Date())
                .set(PgOrderBase::getIsQd, false)
                .update();

        List<PgOrderBase> list = pgOrderBaseService.lambdaQuery()
                .in(PgOrderBase::getId, ids).list();

        for (PgOrderBase pgOrderBase : list) {
            if (pgOrderBase.getIsImportExcel()) {
                PgOrderBase pgOrderBase1 = new PgOrderBase();
                pgOrderBase1.setId(pgOrderBase.getId());
                pgOrderBase1.setIsMeet(false);
                pgOrderBase1.updateById();
            }
            if (adminWebsit.getAttr().equals(WebsitAttrEnum.SELF.getKey())
                    && "安装, 拆移机".contains(pgOrderBase.getOrderSmallTypeText())
                    && StringUtils.isBlank(pgOrderBase.getWorkerNumber())) {

                throw new RemoteServiceException("自建网点的工单 ”安装, 拆移机“ 没有S编号师傅, 无法派单");
            }
        }


        pgOrderWorkerService.lambdaUpdate().in(PgOrderWorker::getOrderBaseId, ids).remove();

        pgOrderWorkerService.saveBatch(pgOrderWorkers);

        for (String id : ids) {
            this.addWorkerLog(id);
        }
    }

    private void addWorkerLog(String id) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setOrderBaseId(id);
        pgOrderOperatorLog.setType(OrderOperatorLogTypeEnum.GP.getKey());
        pgOrderOperatorLog.setTypeText(OrderOperatorLogTypeEnum.GP.getRemark());
        pgOrderOperatorLog.setContent("派工主要工程师：" + pgOrderBase.getWorkerName());
        orderLogLogic.addLog(pgOrderOperatorLog);
    }


    public List<PgOrderProductDetail> getOrderProduct(String id, List<String> status) {

        return pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                .in(!CollectionUtils.isEmpty(status), PgOrderProductDetail::getStatus, status).list();
    }

    public PgOrderProductDetailVO productDetail(String id) {
        PgOrderProductDetail pgOrderProduct = pgOrderProductDetailService.getById(id);

        PgOrderProductDetailVO pgOrderProductDetail = BeanUtil.toBean(pgOrderProduct, PgOrderProductDetailVO.class);

        List<PgOrderDetail> list = pgOrderDetailService.lambdaQuery().eq(PgOrderDetail::getProductDetailId, id).list();

        pgOrderProductDetail.setPgOrderProductDetails(list);
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(pgOrderProduct.getOrderBaseId());

        pgOrderProductDetail.setPgOrderBase(pgOrderBase);

        List<PgOrderWorker> list1 = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, pgOrderProductDetail.getOrderBaseId()).list();
        pgOrderProductDetail.setPgOrderWorkers(list1);

        return pgOrderProductDetail;

    }


    public List<WorkerOrderDetail> getOrderList(String workerOrderId) {

        List<WorkerOrder> list = workerOrderService.lambdaQuery().eq(WorkerOrder::getWorkerOrderId, workerOrderId)
                .in(WorkerOrder::getPayStatus, PayStatusEnum.WAIT.getKey(), PayStatusEnum.PAID.getKey()).list();
        if (CollectionUtils.isEmpty(list))
            return new ArrayList<>();

        List<WorkerOrderDetail> workerOrderDetails1 = BeanUtil.copyToList(list, WorkerOrderDetail.class);
        for (WorkerOrderDetail workerOrder : workerOrderDetails1) {

            workerOrder.setWorkerOrderItems(workerOrderItemService.lambdaQuery()
                    .eq(WorkerOrderItem::getOrderId, workerOrder.getOrderId()).list());

            PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrderId);
            workerOrder.setPgOrderBase(pgOrderBase);


        }


        return workerOrderDetails1;

    }

    public IPage<DispatchVO> list(ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, DispatchVO.class);

        List<WebsitDispatch> websitDispatches = websitDispatchService.lambdaQuery().eq(WebsitDispatch::getCompanyWechatId, adminUser.getCompanyWechatId())
                .select(WebsitDispatch::getStreetCode, WebsitDispatch::getSaleTypeId, WebsitDispatch::getOrderSmallId,
                        WebsitDispatch::getCategoryId)
                .list();

        List<String> codeList = new ArrayList<>();
        for (WebsitDispatch websitDispatch : websitDispatches) {
            codeList.add(websitDispatch.getStreetCode() + websitDispatch.getSaleTypeId() + websitDispatch.getOrderSmallId()
                    + websitDispatch.getCategoryId());
        }

        IPage<DispatchVO> dispatchVOIPage = increMapper.listDispatch(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam, adminCompanyIds, codeList);

        return dispatchVOIPage;


    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(WebsitDispatch websitDispatch) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        websitDispatch.setCompanyWechatId(adminUser.getCompanyWechatId());
        websitDispatch.setCompanyWechatName(adminUser.getCompanyName());
        websitDispatch.insert();
    }

    public IPage<WebsitDispatchVO> listDispatch(ZfireParamBean zfireParamBean) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean, WebsitDispatchVO.class);

        IPage<WebsitDispatchVO> websitDispatchVOIPage = increMapper.listDispatchWebsit(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminCompanyIds);

        return websitDispatchVOIPage;
    }

    public List<DispatchCherVO> pList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.pList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    public List<DispatchCherVO> cList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.cList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    public List<DispatchCherVO> aList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.aList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    public List<DispatchCherVO> sList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.sList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    public List<DispatchCherVO> channel(String pId, String cityCode, String areaCode, String streetCode, List<String> dictCode, List<String> orderSmallId, List<String> categoryId, List<String> orderSourceId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.channel(pId, cityCode, areaCode, streetCode, dictCode, orderSmallId, categoryId, orderSourceId, adminCompanyIds);
    }

    public List<DispatchCherVO> smallList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.smallList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    public List<DispatchCherVO> categoryList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.categoryList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    public List<DispatchCherVO> sourceList(String pId, String cityCode, String areaCode, String streetCode, List<String> sales, List<String> orderSmallId, List<String> categoryId) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        return increMapper.sourceList(pId, cityCode, areaCode, streetCode, sales, orderSmallId, categoryId, adminCompanyIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveDispatch(WebsitDispatchAdd websitDispatchAdd) {
        AdminWebsit adminWebsit = adminWebsitService.getById(websitDispatchAdd.getWebsitId());

        Region region = regionService.getById(websitDispatchAdd.getStreetCode());

        List<WebsitDispatch> websitDispatches = new ArrayList<>();

        for (String orderSmallId : websitDispatchAdd.getOrderSmallIds()) {

            OrderSmallType orderSmallType = orderSmallTypeService.getById(orderSmallId);

            for (String categoryId : websitDispatchAdd.getCategoryIds()) {

                GoodsCategory goodsCategory = goodsCategoryService.getById(categoryId);

                for (String salesId : websitDispatchAdd.getSaleIds()) {

                    SysDictCompany sales = sysDictCompanyService.lambdaQuery().eq(SysDictCompany::getDictCode, salesId).last("limit 1").one();


                    WebsitDispatch websitDispatch = new WebsitDispatch();
                    websitDispatch.setWebsitId(adminWebsit.getWebsitId());
                    websitDispatch.setWebsitName(adminWebsit.getName());
                    websitDispatch.setProvinceCode(region.getProvinceCode());
                    websitDispatch.setProvinceName(region.getProvinceName());
                    websitDispatch.setCityCode(region.getCityCode());
                    websitDispatch.setCityName(region.getCityName());
                    websitDispatch.setAreaCode(region.getAreaCode());
                    websitDispatch.setAreaName(region.getAreaName());
                    websitDispatch.setStreetCode(region.getId());
                    websitDispatch.setStreetName(region.getName());
                    websitDispatch.setCompanyWechatId(adminWebsit.getCompanyWechatId());
                    websitDispatch.setCompanyWechatName(adminWebsit.getCompanyWechatName());


                    websitDispatch.setOrderSmallTypeText(orderSmallType.getOrderSmallTypeText());
                    websitDispatch.setOrderSmallId(orderSmallType.getId());

                    websitDispatch.setCategoryId(goodsCategory.getCategoryId());
                    websitDispatch.setCategoryName(goodsCategory.getName());
                    websitDispatch.setSaleTypeId(sales.getDictCode());
                    websitDispatch.setSaleTypeName(sales.getDictValue());


                    if (websitDispatchService.lambdaQuery().eq(WebsitDispatch::getStreetCode, region.getId())
                            .eq(WebsitDispatch::getOrderSmallId, websitDispatch.getOrderSmallId())
                            .eq(WebsitDispatch::getCategoryId, websitDispatch.getCategoryId())
                            .eq(WebsitDispatch::getSaleTypeId, websitDispatch.getSaleTypeId())
                            .count() > 0) {
                        throw new RemoteServiceException("存在街道：" + websitDispatch.getStreetName() + "，产品大类：" + websitDispatch.getCategoryName() +
                                "，承接渠道：" + websitDispatch.getSaleTypeName() + "，工单类型：" + websitDispatch.getOrderSmallTypeText());
                    }

                    websitDispatches.add(websitDispatch);


                }
            }
        }

        websitDispatchService.saveBatch(websitDispatches);
    }

    public void delDispatch(List<String> id) {
        websitDispatchService.removeByIds(id);
    }


    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file) throws IOException {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<Object> rows = ExcelUtils.importExcel(file);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(rows)) {
            throw new RemoteServiceException("导入内容为空");
        }


        //工单类型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, SysDictCompany> salesMap = sysDictCompanyLogic.dictByTypeOfValue(SysDictConstant.SALES_TYPE, 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<WebsitDispatch> websitDispatches = new ArrayList<>();
        for (Object o : rows) {
            List<Object> row = (List<Object>) o;

            String websitName = (String) row.get(0);
            String websitId = (String) row.get(1);
            String pName = (String) row.get(2);
            String cName = (String) row.get(3);
            String aName = (String) row.get(4);
            String sName = (String) row.get(5);
            String saleName = (String) row.get(6);
            String smallName = (String) row.get(7);
            String categoryName = (String) row.get(8);


            String[] salesNames = saleName.split("/");
            String[] smallNames = smallName.split("/");
            String[] categoryNames = categoryName.split("/");


            AdminWebsit adminWebsit = adminWebsitMap.get(websitId);
            Region region = orderBaseLogic.getRegion(pName, cName, aName, sName);

            if (region == null)
             throw new RemoteServiceException(pName+cName+aName+sName+"该地址查找不到");

            for (String sales : salesNames) {
                SysDictCompany saleOne = salesMap.get(sales);
                for (String small : smallNames) {
                    OrderSmallType orderSmallType = orderSmallTypeMap.get(small);
                    for (String category : categoryNames) {
                        GoodsCategory goodsCategory = categoryMap1.get(category);

                            WebsitDispatch websitDispatch = new WebsitDispatch();
                            websitDispatch.setWebsitId(adminWebsit.getWebsitId());
                            websitDispatch.setWebsitName(adminWebsit.getName());
                            websitDispatch.setProvinceCode(region.getProvinceCode());
                            websitDispatch.setProvinceName(region.getProvinceName());
                            websitDispatch.setCityCode(region.getCityCode());
                            websitDispatch.setCityName(region.getCityName());
                            websitDispatch.setAreaCode(region.getAreaCode());
                            websitDispatch.setAreaName(region.getAreaName());
                            websitDispatch.setStreetCode(region.getId());
                            websitDispatch.setStreetName(region.getName());
                            websitDispatch.setCompanyWechatId(adminUser.getCompanyWechatId());
                            websitDispatch.setCompanyWechatName(adminUser.getCompanyName());


                            websitDispatch.setOrderSmallTypeText(orderSmallType.getOrderSmallTypeText());
                            websitDispatch.setOrderSmallId(orderSmallType.getId());

                            websitDispatch.setCategoryId(goodsCategory.getCategoryId());
                            websitDispatch.setCategoryName(goodsCategory.getName());

                            websitDispatch.setSaleTypeName(saleOne.getDictValue());
                            websitDispatch.setSaleTypeId(saleOne.getDictCode());


                            if (websitDispatchService.lambdaQuery().eq(WebsitDispatch::getStreetCode, region.getId())
                                    .eq(WebsitDispatch::getOrderSmallId, websitDispatch.getOrderSmallId())
                                    .eq(WebsitDispatch::getCategoryId, websitDispatch.getCategoryId())
                                    .eq(WebsitDispatch::getSaleTypeId, websitDispatch.getSaleTypeId())
                                    .count() > 0) {
                                throw new RemoteServiceException("存在街道：" + websitDispatch.getStreetName() + "，产品大类：" + websitDispatch.getCategoryName() +
                                        "，销量类型：" + websitDispatch.getSaleTypeName() + "，工单类型：" + websitDispatch.getOrderSmallTypeText());
                            }

                            websitDispatches.add(websitDispatch);

                    }
                }
            }


        }

        websitDispatchService.saveBatch(websitDispatches);

    }

    @Transactional(rollbackFor = Exception.class)
    public void updateDispatch(WebsitDispatch websitDispatch) {

        if (websitDispatchService.lambdaQuery().eq(WebsitDispatch::getStreetCode, websitDispatch.getStreetCode())
                .eq(WebsitDispatch::getOrderSmallId, websitDispatch.getOrderSmallId())
                .eq(WebsitDispatch::getCategoryId, websitDispatch.getCategoryId())
                .eq(WebsitDispatch::getSaleTypeId, websitDispatch.getSaleTypeId())
                .ne(WebsitDispatch::getId, websitDispatch.getId())
                .count() > 0) {
            throw new RemoteServiceException("存在街道：" + websitDispatch.getStreetName() + "，产品大类：" + websitDispatch.getCategoryName() +
                    "，承接渠道：" + websitDispatch.getSaleTypeName()  + "，工单类型：" + websitDispatch.getOrderSmallTypeText());
        }

        websitDispatch.updateById();

    }

    public WebsitDispatch detailDispatch(String id) {

        return websitDispatchService.getById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void changWebsit(List<String> ids) {

        List<String> orderIds = new ArrayList<>();

        for (String id : ids) {
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

            PgOrderProduct pgOrderProduct = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, id)
                    .last("limit 1")
                    .one();

            if (!StringUtils.equalsAny(pgOrderBase.getOrderStatus(),"DSHPG","CJ","YPD","DXSPD","DZBPG","DWDSPGP","DXSSPGP","DTJXSSPGP","DZBSPGP","DFZXPD","DFZXSPGP")){
                continue;
            }

            if (websitDispatchService.lambdaQuery()
                    .eq( WebsitDispatch::getStreetCode, pgOrderBase.getStreetId())
                    .eq(WebsitDispatch::getSaleTypeId, pgOrderBase.getSaleType())
                    .eq( WebsitDispatch::getCategoryId,pgOrderProduct.getMainId())
                    .eq( WebsitDispatch::getOrderSmallId, pgOrderBase.getOrderSmallType())
                    .count() > 0) {

                WebsitDispatch websitDispatch = websitDispatchService.lambdaQuery()
                        .eq(WebsitDispatch::getStreetCode, pgOrderBase.getStreetId())
                        .eq(WebsitDispatch::getSaleTypeId, pgOrderBase.getSaleType())
                        .eq(WebsitDispatch::getCategoryId, pgOrderProduct.getMainId())
                        .eq(WebsitDispatch::getOrderSmallId, pgOrderBase.getOrderSmallType())
                        .last("limit 1").one();



                pgOrderBase.setWebsitId(websitDispatch.getWebsitId());
                pgOrderBase.setOrderStatus(OrderBaseStatusEnum.DWDPG.getKey());
                pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.DWDPG.getRemark());
                pgOrderBase.setWebsitName(websitDispatch.getWebsitName());
                pgOrderBase.setDispatchWebsitTime(new Date());
                pgOrderBase.updateById();

                orderLogLogic.addLog(pgOrderBase.getId(), "指派网点", "自动派工给网点【" +(pgOrderBase.getWebsitId())+ pgOrderBase.getWebsitName() + "】", pgOrderBase.getWebsitName());



            }
        }
    }
}
