package com.zfire.mall.manager.logic.trade;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.admin.respDto.AdminUserDto;
import com.zfire.mall.manager.bean.trade.*;
import com.zfire.mall.manager.commonmapper.trade.LoginOrderMapper;
import com.zfire.mall.manager.enums.*;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.admin.AdminUserLogic;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.k3.K3CustomerLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.zfire.bean.QueryParamBean;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LoginOrderLogic {

    @Resource
    LoginOrderMapper loginOrderMapper;
    @Resource
    CommonLogic commonLogic;
    @Resource
    LoginOrderValidLogic loginOrderValidLogic;
    @Resource
    TradeLoginOrderService tradeLoginOrderService;
    @Resource
    TradeLoginOrderItemService tradeLoginOrderItemService;
    @Resource
    TradeLoginOrderFileService tradeLoginOrderFileService;
    @Resource
    TradeLoginOperRecordService tradeLoginOperRecordService;
    @Resource
    TradeLoginCustomerInfoService tradeLoginCustomerInfoService;
    @Resource
    SysDictService sysDictService;
    @Resource
    CustomerBillLimitConfigService customerBillLimitConfigService;
    @Resource
    KingDeeCustomerService kingDeeCustomerService;
    @Resource
    K3CustomerLogic k3CustomerLogic;
    @Resource
    AdminUserLogic adminUserLogic;
    @Resource
    TradeCategoryConfigService tradeCategoryConfigService;
    @Resource
    LbsAmapService lbsAmapService;
    @Value("${lbs.web.key}")
    private String lbsWebKey;
    private final String url = "https://restapi.amap.com";

    public IPage<WorkLoginOrderVO> workListPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        this.commonSetParams(zfireParamBean, adminUser);
        return loginOrderMapper.workOrderList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getAdminUserId());
    }

    public IPage<HomeLoginOrderVO> homeListPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        this.commonSetParams(zfireParamBean, adminUser);
        return loginOrderMapper.homeOrderList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getAdminUserId());
    }

    public IPage<SpanLoginOrderVO> spanListPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        this.commonSetParams(zfireParamBean, adminUser);
        return loginOrderMapper.spanOrderList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getAdminUserId());
    }

    public TradeLoginOrderBean detail(String id) {
        TradeLoginOrder order = tradeLoginOrderService.getById(id);
        List<TradeLoginOrderItem> items = tradeLoginOrderItemService.lambdaQuery()
                .eq(TradeLoginOrderItem::getOrderId, id)
                .list();
        List<TradeLoginOrderFile> files = tradeLoginOrderFileService.lambdaQuery()
                .eq(TradeLoginOrderFile::getOrderId, id)
                .list();

        TradeLoginOrderBean bean = new TradeLoginOrderBean();
        BeanUtils.copyProperties(order, bean);
        bean.setItems(items);
        bean.setFiles(files);
        return bean;
    }

    private void commonSetParams(ZfireParamBean zfireParamBean, AdminUserCom adminUser) {
        if (adminUser.getIsCustomer()) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.customer_id")
                    .setCompare("=")
                    .setValue(adminUser.getCustomerId()));
        }
        if (CollectionUtil.isNotEmpty(adminUser.getAdminCompanyIds())) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.admin_company_id")
                    .setCompare("IN")
                    .setValue(adminUser.getAdminCompanyIds()));
        }
        if (adminUser.getIsService() && !adminUser.getIsTradeExaminer()) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.service_id")
                    .setCompare("=")
                    .setValue(adminUser.getAdminUserId()));
        }
//        if (adminUser.getIsTradeExaminer()) {
//            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.admin_websit_id")
//                    .setCompare("in")
//                    .setValue(adminUser.getAdminWebsitIds()));
//        }
        for (QueryParamBean param : zfireParamBean.getParams()) {
            if (param.getParam().equals("a.project_name") && Objects.nonNull(param.getValue()) && StringUtils.isNotBlank(param.getValue().toString())) {
                String value = param.getValue().toString();
                param.setValue(value.replaceAll("\\*", "%"));
            }
            if (param.getParam().equals("a.join_address") && Objects.nonNull(param.getValue()) && StringUtils.isNotBlank(param.getValue().toString())) {
                String value = param.getValue().toString();
                param.setValue(value.replaceAll("\\*", "%"));
            }
        }

        FieldUtils.supplyParam(zfireParamBean);
    }

    /**
     * 工装保存
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public TradeLoginOrderBean workAdd(TradeLoginOrderBean bean, boolean isRecord) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);

        // 检查经销商是否超过登录单超限制
        if (this.checkOrderLimit(bean)) {
            throw new RemoteServiceException("登录名额已满");
        }

        bean = loginOrderValidLogic.addParamsValid(adminUser, bean);
        bean.setOrderUpdateTime(DateUtil.date());
        bean.insert();

        for (TradeLoginOrderItem item : bean.getItems()) {
            item.setOrderId(bean.getId());
        }

        tradeLoginOrderItemService.saveOrUpdateBatch(bean.getItems());


        if (isRecord) {
            // 插入操作记录
            this.insertOperRecord(bean.getId(), "添加工程信息", TradeOperTypeEnum.ADD.getValue(), null, false);
        }

        // 保存或更新经销商信息
        this.saveOrUpdateCustomerInfo(bean);
        return bean;
    }

    /**
     * 家装保存
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public TradeLoginOrderBean homeAdd(TradeLoginOrderBean bean, boolean isRecord) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);

        // 检查经销商是否超过登录单超限制
        if (this.checkOrderLimit(bean)) {
            throw new RemoteServiceException("登录名额已满");
        }

        bean = loginOrderValidLogic.addParamsValid(adminUser, bean);
        bean.setOrderUpdateTime(DateUtil.date());
        bean.insert();

        for (TradeLoginOrderItem item : bean.getItems()) {
            item.setOrderId(bean.getId());
        }

        tradeLoginOrderItemService.saveOrUpdateBatch(bean.getItems());

        if (isRecord) {
            // 插入操作记录
            this.insertOperRecord(bean.getId(), "添加工程信息", TradeOperTypeEnum.ADD.getValue(), null, false);
        }

        // 保存或更新经销商信息
        this.saveOrUpdateCustomerInfo(bean);
        return bean;
    }

    /**
     * 工装编辑
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public TradeLoginOrderBean workEdit(TradeLoginOrderBean bean, boolean isRecord) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        TradeLoginOrder order = tradeLoginOrderService.getById(bean.getId());
        List<TradeLoginOrderItem> items = tradeLoginOrderItemService.lambdaQuery()
                .eq(TradeLoginOrderItem::getOrderId, bean.getId())
                .list();
        if (Objects.isNull(order)) {
            throw new RemoteServiceException("单据不存在");
        }

        boolean isNotEdit = true;

        if (order.getOrderStatus().equals(TradeOrderStatusEnum.SAVE.getKey())
                || order.getOrderStatus().equals(TradeOrderStatusEnum.RETURN.getKey())
                || (adminUser.getIsTradeExaminer() && order.getStatus().equals(TradeFollowStatusEnum.ING.getKey()))) {
            isNotEdit = false;
        }

        if (isNotEdit) {
            throw new RemoteServiceException("单据不能编辑");
        }

        bean.setOrderStatus(order.getOrderStatus());
        bean.setOrderUpdateTime(adminUser.getIsTradeExaminer() ? null : DateUtil.date());
        bean = loginOrderValidLogic.editParamsValid(adminUser, bean);

        // 新旧数据值对比
        this.beanChangeContent(order, bean);

        bean.editParamsSetter(order);
        bean.setLoginStatus(order.getLoginStatus());
        order.updateById();

        tradeLoginOrderItemService.lambdaUpdate()
                .eq(TradeLoginOrderItem::getOrderId, bean.getId())
                .remove();
        for (TradeLoginOrderItem item : bean.getItems()) {
            item.setOrderId(bean.getId());
        }
        tradeLoginOrderItemService.saveOrUpdateBatch(bean.getItems());

        if (isRecord) {
            // 插入操作记录
            this.insertOperRecord(bean.getId(), bean.getOldNewContent(), TradeOperTypeEnum.EDIT.getValue(), null, false);
        }

        // 保存或更新经销商信息
        this.saveOrUpdateCustomerInfo(bean);
        return bean;
    }

    /**
     * 家装编辑
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public TradeLoginOrderBean homeEdit(TradeLoginOrderBean bean, boolean isRecord) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        TradeLoginOrder order = tradeLoginOrderService.getById(bean.getId());
        List<TradeLoginOrderItem> items = tradeLoginOrderItemService.lambdaQuery()
                .eq(TradeLoginOrderItem::getOrderId, bean.getId())
                .list();
        if (Objects.isNull(order)) {
            throw new RemoteServiceException("单据不存在");
        }

        boolean isNotEdit = true;

        if (order.getOrderStatus().equals(TradeOrderStatusEnum.SAVE.getKey())
                || order.getOrderStatus().equals(TradeOrderStatusEnum.RETURN.getKey())
                || (adminUser.getIsTradeExaminer() && order.getStatus().equals(TradeFollowStatusEnum.ING.getKey()))) {
            isNotEdit = false;
        }

        if (isNotEdit) {
            throw new RemoteServiceException("单据不能编辑");
        }

        bean.setOrderStatus(order.getOrderStatus());
        bean.setOrderUpdateTime(adminUser.getIsTradeExaminer() ? null : DateUtil.date());
        bean = loginOrderValidLogic.editParamsValid(adminUser, bean);

        // 新旧数据值对比
        this.beanChangeContent(order, bean);

        bean.editParamsSetter(order);
        bean.setLoginStatus(order.getLoginStatus());
        order.updateById();

        tradeLoginOrderItemService.lambdaUpdate()
                .eq(TradeLoginOrderItem::getOrderId, bean.getId())
                .remove();
        for (TradeLoginOrderItem item : bean.getItems()) {
            item.setOrderId(bean.getId());
        }
        tradeLoginOrderItemService.saveOrUpdateBatch(bean.getItems());

        if (isRecord) {
            // 插入操作记录
            this.insertOperRecord(bean.getId(), bean.getOldNewContent(), TradeOperTypeEnum.EDIT.getValue(), null, false);
        }

        // 保存或更新经销商信息
        this.saveOrUpdateCustomerInfo(bean);
        return bean;
    }

    /**
     * 工装提交
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public void workSubmit(TradeLoginOrderBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
//        TradeLoginOrder order;
//        List<TradeLoginOrderItem> items;

        if (StringUtils.isBlank(bean.getId())) {
            // 记录为空新增

            bean = this.workAdd(bean, true);
        } else {
            // 记录不为空编辑
//            order = tradeLoginOrderService.getById(bean.getId());
//            items = tradeLoginOrderItemService.lambdaQuery()
//                    .eq(TradeLoginOrderItem::getOrderId, bean.getId())
//                    .list();
            bean = this.workEdit(bean, true);

            if (this.checkOrderLimit(bean)) {
                throw new RemoteServiceException("登录名额已满");
            }
        }

        boolean isUpdateSubmitTime = false;
        if ((Objects.nonNull(bean.getSubmitTime()) && adminUser.getIsTradeExaminer())
                || (StringUtils.isNotBlank(bean.getLoginStatus()) && bean.getLoginStatus().equals(TradeLoginStatusEnum.OK.getKey()))) {
            isUpdateSubmitTime = true;
        }

        bean.setOrderStatus(TradeOrderStatusEnum.WAIT.getKey())
                .setSubmitBy(adminUser.getNickName())
                .setSubmitName(adminUser.getNickName())
                .setSubmitTime(isUpdateSubmitTime ? bean.getSubmitTime() : DateUtil.date());
        if (StringUtils.isBlank(bean.getProjectNo())) {
            bean.setProjectNo(commonLogic.generateTradeLoginNo(bean.getIsSpan() ? "SPAN" : OrderTypeEnum.TRADE.getKey(), 8));
        }

        bean.updateById();

        tradeLoginOrderItemService.lambdaUpdate()
                .eq(TradeLoginOrderItem::getOrderId, bean.getId())
                .remove();
        tradeLoginOrderItemService.saveOrUpdateBatch(bean.getItems());
    }

    /**
     * 家装提交
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public void homeSubmit(TradeLoginOrderBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
//        TradeLoginOrder order;
//        List<TradeLoginOrderItem> items;

        if (StringUtils.isBlank(bean.getId())) {
            // 记录为空新增
            bean = this.homeAdd(bean, true);
        } else {
            // 记录不为空编辑
//            order = tradeLoginOrderService.getById(bean.getId());
//            items = tradeLoginOrderItemService.lambdaQuery()
//                    .eq(TradeLoginOrderItem::getOrderId, bean.getId())
//                    .list();
            bean = this.homeEdit(bean, true);

            if (this.checkOrderLimit(bean)) {
                throw new RemoteServiceException("登录名额已满");
            }
        }

        boolean isUpdateSubmitTime = false;
        if ((Objects.nonNull(bean.getSubmitTime()) && adminUser.getIsTradeExaminer())
                || (StringUtils.isNotBlank(bean.getLoginStatus()) && bean.getLoginStatus().equals(TradeLoginStatusEnum.OK.getKey()))) {
            isUpdateSubmitTime = true;
        }

        bean.setOrderStatus(TradeOrderStatusEnum.WAIT.getKey())
                .setSubmitBy(adminUser.getNickName())
                .setSubmitName(adminUser.getNickName())
                .setSubmitTime(isUpdateSubmitTime ? bean.getSubmitTime() : DateUtil.date());
        if (StringUtils.isBlank(bean.getProjectNo())) {
            bean.setProjectNo(commonLogic.generateTradeLoginNo(bean.getIsSpan() ? "SPAN" : OrderTypeEnum.TRADE.getKey(), 8));
        }
        bean.updateById();

        tradeLoginOrderItemService.lambdaUpdate()
                .set(TradeLoginOrderItem::getProjectNo, bean.getProjectNo())
                .eq(TradeLoginOrderItem::getOrderId, bean.getId())
                .update();
    }

    /**
     * 工装审核
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public void workExamine(TradeLoginOrderBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        TradeLoginOrder order = tradeLoginOrderService.getById(bean.getId());
        if (Objects.isNull(order)) {
            throw new RemoteServiceException("单据不存在");
        }
        if (!adminUser.getIsTradeExaminer()) {
            throw new RemoteServiceException("非审核员，不能审核");
        }
        if (!adminUser.getAdminWebsitIds().contains(order.getAdminWebsitId())) {
            throw new RemoteServiceException("单据非当前审核员负责，不能审核");
        }
        if (order.getOrderStatus().equals(TradeOrderStatusEnum.SAVE.getKey())) {
            throw new RemoteServiceException("当前单据状态不支持审核");
        }

        if (bean.getLoginStatus().equals(TradeLoginStatusEnum.OK.getKey())
                || bean.getLoginStatus().equals(TradeLoginStatusEnum.FAIL.getKey())) {
            order.setOrderStatus(bean.getLoginStatus())
                    .setLoginStatus(bean.getLoginStatus());

//            if (order.getLoginStatus().equals(TradeLoginStatusEnum.FAIL.getKey())) {
//                //登录不成功时
//                if (StringUtils.isBlank(bean.getSuccessLoginProject())) {
//                    throw new RemoteServiceException("登录成功项目不能为空");
//                }
//                if (bean.getSuccessLoginProject().equals(order.getProjectNo())) {
//                    throw new RemoteServiceException("登录成功项目不能是当前单据的项目编号");
//                }
//            }

            if (StringUtils.isNotBlank(bean.getCommonFollowProject())) {
                // 如果上一次有共同项目记录，先清除
                if (StringUtils.isNotBlank(order.getCommonFollowProject())) {
                    String[] historyProjectNoList = order.getCommonFollowProject().split(",");
                    for (String projectNo : historyProjectNoList) {
                        if (StringUtils.isBlank(projectNo) || projectNo.equals(order.getProjectNo())) {
                            continue;
                        }
                        TradeLoginOrder loginOrder = tradeLoginOrderService.lambdaQuery()
                                .eq(TradeLoginOrder::getProjectNo, projectNo)
                                .eq(TradeLoginOrder::getIsSpan, order.getIsSpan())
                                .one();
                        if (Objects.nonNull(loginOrder)) {
                            String[] oldList = loginOrder.getCommonFollowProject().split(",");
                            String newStr = Arrays.stream(oldList).filter(v -> !v.equals(order.getProjectNo())).collect(Collectors.joining(","));
                            loginOrder.setCommonFollowProject(newStr);
                            loginOrder.updateById();
                        }
                    }
                }
                String[] projectNoList = bean.getCommonFollowProject().split(",");
                for (String projectNo : projectNoList) {
                    if (StringUtils.isBlank(projectNo) || projectNo.equals(order.getProjectNo())) {
                        continue;
                    }
                    TradeLoginOrder loginOrder = tradeLoginOrderService.lambdaQuery()
                            .eq(TradeLoginOrder::getProjectNo, projectNo)
                            .eq(TradeLoginOrder::getIsSpan, order.getIsSpan())
                            .one();
                    if (Objects.nonNull(loginOrder)) {
                        String commonFollowProject = loginOrder.getCommonFollowProject();
                        if (StringUtils.isNotBlank(commonFollowProject) && !commonFollowProject.contains(order.getProjectNo())) {
                            loginOrder.setCommonFollowProject(commonFollowProject + "," + order.getProjectNo());
                        } else {
                            loginOrder.setCommonFollowProject(order.getProjectNo());
                        }
                        loginOrder.updateById();
                    }
                }
            }
        } else {
//            if (StringUtils.isBlank(bean.getExamineNote())) {
//                throw new RemoteServiceException("驳回：审核备注不能为空");
//            }
            order.setOrderStatus(TradeOrderStatusEnum.RETURN.getKey())
                    .setLoginStatus(TradeLoginStatusEnum.REJECT.getKey());
//                    .setSubmitTime(null)
//                    .setSubmitName("");
//            tradeLoginOrderService.lambdaUpdate()
//                    .set(TradeLoginOrder::getSubmitTime, null)
//                    .set(TradeLoginOrder::getSubmitBy, null)
//                    .eq(TradeLoginOrder::getId, order.getId())
//                    .update();
        }

        TradeLoginOrder successOrder = tradeLoginOrderService.lambdaQuery()
                .select(TradeLoginOrder::getServiceNumber, TradeLoginOrder::getServiceName, TradeLoginOrder::getCustomerNumber, TradeLoginOrder::getCustomerName)
                .eq(TradeLoginOrder::getIsSpan, order.getIsSpan())
                .eq(TradeLoginOrder::getProjectNo, bean.getSuccessLoginProject())
                .last("limit 1")
                .one();


        order.setNote(bean.getNote())
                .setSuccessLoginProject(bean.getSuccessLoginProject())
                .setCommonFollowProject(bean.getCommonFollowProject())
                .setConfirmBy(adminUser.getNickName())
                .setConfirmName(adminUser.getNickName())
                .setConfirmTime(DateUtil.date())
                .setSuccessServiceNumber(bean.getSuccessServiceNumber())
                .setSuccessServiceName(bean.getSuccessServiceName())
                .setSuccessCustomerNumber(bean.getSuccessCustomerNumber())
                .setSuccessCustomerName(bean.getSuccessCustomerName());

        order.updateById();

        tradeLoginOrderFileService.lambdaUpdate()
                .eq(TradeLoginOrderFile::getOrderId, order.getId())
                .remove();
        for (TradeLoginOrderFile item : bean.getFiles()) {
            item.setId(null);
            item.setOrderId(bean.getId());
        }
        tradeLoginOrderFileService.saveOrUpdateBatch(bean.getFiles());

        // 插入操作记录
        Map<String, Object> fieldMap = EnumUtil.getNameFieldMap(TradeLoginStatusEnum.class, "value");
        this.insertOperRecord(bean.getId(), "审核工程信息：" + fieldMap.get(bean.getLoginStatus()),
                TradeOperTypeEnum.EXAMINE.getValue(), null, false);
    }

    /**
     * 家装审核
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public void homeExamine(TradeLoginOrderBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        TradeLoginOrder order = tradeLoginOrderService.getById(bean.getId());
        if (Objects.isNull(order)) {
            throw new RemoteServiceException("单据不存在");
        }
        if (!adminUser.getIsTradeExaminer()) {
            throw new RemoteServiceException("非审核员，不能审核");
        }
        if (!adminUser.getAdminWebsitIds().contains(order.getAdminWebsitId())) {
            throw new RemoteServiceException("单据非当前审核员负责，不能审核");
        }
        if (order.getOrderStatus().equals(TradeOrderStatusEnum.SAVE.getKey())) {
            throw new RemoteServiceException("当前单据状态不支持审核");
        }

        if (bean.getLoginStatus().equals(TradeLoginStatusEnum.OK.getKey())
                || bean.getLoginStatus().equals(TradeLoginStatusEnum.FAIL.getKey())) {
            order.setOrderStatus(bean.getLoginStatus())
                    .setLoginStatus(bean.getLoginStatus());

//            if (order.getLoginStatus().equals(TradeLoginStatusEnum.FAIL.getKey())) {
//                // 登录不成功时
//                if (StringUtils.isBlank(bean.getSuccessLoginProject())) {
//                    throw new RemoteServiceException("登录成功项目不能为空");
//                }
//                if (bean.getSuccessLoginProject().equals(order.getProjectNo())) {
//                    throw new RemoteServiceException("登录成功项目不能是当前单据的项目编号");
//                }
//                order.setSuccessLoginProject(bean.getSuccessLoginProject());
//            }

            if (StringUtils.isNotBlank(bean.getCommonFollowProject())) {
                // 如果上一次有共同项目记录，先清除
                if (StringUtils.isNotBlank(order.getCommonFollowProject())) {
                    String[] historyProjectNoList = order.getCommonFollowProject().split(",");
                    for (String projectNo : historyProjectNoList) {
                        if (StringUtils.isBlank(projectNo) || projectNo.equals(order.getProjectNo())) {
                            continue;
                        }
                        TradeLoginOrder loginOrder = tradeLoginOrderService.lambdaQuery()
                                .eq(TradeLoginOrder::getProjectNo, projectNo)
                                .eq(TradeLoginOrder::getIsSpan, order.getIsSpan())
                                .one();
                        if (Objects.nonNull(loginOrder)) {
                            String[] oldList = loginOrder.getCommonFollowProject().split(",");
                            String newStr = Arrays.stream(oldList).filter(v -> !v.equals(order.getProjectNo())).collect(Collectors.joining(","));
                            loginOrder.setCommonFollowProject(newStr);
                            loginOrder.updateById();
                        }
                    }
                }
                String[] projectNoList = bean.getCommonFollowProject().split(",");
                for (String projectNo : projectNoList) {
                    if (StringUtils.isBlank(projectNo) || projectNo.equals(order.getProjectNo())) {
                        continue;
                    }
                    TradeLoginOrder loginOrder = tradeLoginOrderService.lambdaQuery()
                            .eq(TradeLoginOrder::getProjectNo, projectNo)
                            .eq(TradeLoginOrder::getIsSpan, order.getIsSpan())
                            .one();
                    if (Objects.nonNull(loginOrder)) {
                        String commonFollowProject = loginOrder.getCommonFollowProject();
                        if (StringUtils.isNotBlank(commonFollowProject) && !commonFollowProject.contains(order.getProjectNo())) {
                            loginOrder.setCommonFollowProject(commonFollowProject + "," + order.getProjectNo());
                        } else {
                            loginOrder.setCommonFollowProject(order.getProjectNo());
                        }
                        loginOrder.updateById();
                    }
                }
            }
        } else {
//            if (!order.getIsSpan() && StringUtils.isBlank(bean.getExamineNote())) {
//                throw new RemoteServiceException("驳回：审核备注不能为空");
//            }
            order.setOrderStatus(TradeOrderStatusEnum.RETURN.getKey())
                    .setLoginStatus(TradeLoginStatusEnum.REJECT.getKey());
//                    .setSubmitTime(null)
//                    .setSubmitBy(null);
//            tradeLoginOrderService.lambdaUpdate()
//                    .set(TradeLoginOrder::getSubmitTime, null)
//                    .set(TradeLoginOrder::getSubmitBy, null)
//                    .eq(TradeLoginOrder::getId, order.getId())
//                    .update();
        }

        TradeLoginOrder successOrder = tradeLoginOrderService.lambdaQuery()
                .select(TradeLoginOrder::getServiceNumber, TradeLoginOrder::getServiceName, TradeLoginOrder::getCustomerNumber, TradeLoginOrder::getCustomerName)
                .eq(TradeLoginOrder::getIsSpan, order.getIsSpan())
                .eq(TradeLoginOrder::getProjectNo, bean.getSuccessLoginProject())
                .last("limit 1")
                .one();

        Map<String, Object> noteFieldMap = EnumUtil.getNameFieldMap(TradeExamineNoteEnum.class, "value");
        order.setExamineNote(bean.getExamineNote())
                .setNote(StringUtils.isNotBlank(bean.getExamineNote()) ? noteFieldMap.get(bean.getExamineNote()).toString() : "" + bean.getNote())
                .setSuccessLoginProject(bean.getSuccessLoginProject())
                .setCommonFollowProject(bean.getCommonFollowProject())
                .setConfirmBy(adminUser.getNickName())
                .setConfirmName(adminUser.getNickName())
                .setConfirmTime(DateUtil.date())
                .setSuccessServiceNumber(bean.getSuccessServiceNumber())
                .setSuccessServiceName(bean.getSuccessServiceName())
                .setSuccessCustomerNumber(bean.getSuccessCustomerNumber())
                .setSuccessCustomerName(bean.getSuccessCustomerName());

        order.updateById();

        tradeLoginOrderFileService.lambdaUpdate()
                .eq(TradeLoginOrderFile::getOrderId, order.getId())
                .remove();
        for (TradeLoginOrderFile item : bean.getFiles()) {
            item.setId(null);
            item.setOrderId(bean.getId());
        }
        tradeLoginOrderFileService.saveOrUpdateBatch(bean.getFiles());

        // 插入操作记录
        Map<String, Object> fieldMap = EnumUtil.getNameFieldMap(TradeLoginStatusEnum.class, "value");
        this.insertOperRecord(bean.getId(), "审核工程信息：" + fieldMap.get(bean.getLoginStatus()),
                TradeOperTypeEnum.EXAMINE.getValue(), null, false);
    }

    /**
     * 插入操作记录
     * @param id
     * @param content
     * @param type
     * @param remark
     */
    private TradeLoginOperRecord insertOperRecord(String id, String content, String type, String remark, boolean isReturn) {
        TradeLoginOperRecord record = new TradeLoginOperRecord();
        record.setRefId(id)
                .setOperType(type)
//                .setOperBeforeContent(JSONUtil.toJsonStr(beforeBean))
//                .setOperBeforeContent(Objects.nonNull(afterBean) ? JSONUtil.toJsonStr(beforeBean) : null)
                .setOperContent(content)
                .setRemark(remark);

        if (!isReturn) {
            record.insert();
        }

        return record;
    }

    /**
     * 插入或更新经销商信息
     * @param bean
     */
    private void saveOrUpdateCustomerInfo(TradeLoginOrderBean bean) {
        TradeLoginCustomerInfo info = new TradeLoginCustomerInfo();

        info.setCustomerId(bean.getCustomerId())
                .setLinkName(Optional.ofNullable(bean.getCustomerLinkName()).orElse(""))
                .setLinkMobile(Optional.ofNullable(bean.getCustomerLinkMobile()).orElse(""))
                .setAddress(Optional.ofNullable(bean.getCustomerAddress()).orElse(""));
        tradeLoginCustomerInfoService.saveOrUpdate(info);
    }

    /**
     * 一键更新
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdate(UpdateLoginStatusBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.isNull(bean.getStatus())) {
            throw new RemoteServiceException("工单跟进状态不能为空");
        }
        if (CollectionUtil.isEmpty(bean.getIds())) {
            throw new RemoteServiceException("单号不能为空");
        }
        List<TradeLoginOrder> orderList = tradeLoginOrderService.lambdaQuery()
                .in(TradeLoginOrder::getId, bean.getIds())
                .list();
        Date cur = DateUtil.date();

        tradeLoginOrderService.lambdaUpdate()
                .set(TradeLoginOrder::getStatus, bean.getStatus().getKey())
                .set(TradeLoginOrder::getUpdateBy, adminUser.getNickName())
                .set(TradeLoginOrder::getUpdateName, adminUser.getNickName())
                .set(TradeLoginOrder::getUpdateTime, cur)
                .set(TradeLoginOrder::getOrderUpdateTime, cur)
                .in(TradeLoginOrder::getId, bean.getIds())
                .eq(TradeLoginOrder::getLoginStatus, TradeLoginStatusEnum.OK.getKey())
                .eq(TradeLoginOrder::getStatus, TradeFollowStatusEnum.ING.getKey())
                .eq(TradeLoginOrder::getIsApplyUpdate, IsEnum.NO.getKey())
                .update();

        // 插入操作记录
        Map<String, Object> fieldMap = EnumUtil.getNameFieldMap(TradeFollowStatusEnum.class, "value");
        List<TradeLoginOperRecord> records = new ArrayList<>();

        for (TradeLoginOrder order : orderList) {
            if (order.getLoginStatus().equals(TradeLoginStatusEnum.OK.getKey())
                    && order.getStatus().equals(TradeFollowStatusEnum.ING.getKey())
                    && !order.getIsApplyUpdate()) {
                TradeLoginOperRecord record = this.insertOperRecord(order.getId(), "更新工程信息：原跟单状态" + fieldMap.get(order.getStatus())
                                + "，更新后跟单状态" + fieldMap.get(bean.getStatus().getKey()),
                        bean.getStatus().getKey().equals(TradeFollowStatusEnum.LOSS.getKey()) ? TradeFollowStatusEnum.LOSS.getValue() : TradeOperTypeEnum.UPDATE.getValue(),
                        null, true);
                record.setCreateTime(cur);
                records.add(record);
            }
        }
        tradeLoginOperRecordService.saveBatch(records);
    }

    /**
     * 删除
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
//        if (!adminUser.getIsTradeExaminer()) {
//            throw new RemoteServiceException("非审核员不能操作");
//        }
        tradeLoginOrderService.lambdaUpdate()
                .eq(!adminUser.getIsTradeExaminer(), TradeLoginOrder::getOrderStatus, TradeOrderStatusEnum.SAVE.getKey())
                .in(adminUser.getIsTradeExaminer(), TradeLoginOrder::getOrderStatus, TradeOrderStatusEnum.WAIT.getKey(),
                        TradeOrderStatusEnum.OK.getKey(),
                        TradeOrderStatusEnum.FAIL.getKey(),
                        TradeOrderStatusEnum.RETURN.getKey())
                .in(TradeLoginOrder::getId, ids.stream().distinct().collect(Collectors.toList()))
                .remove();
    }

    /**
     * 申请修改
     * @param bean
     */
    @Transactional(rollbackFor = Exception.class)
    public void applyUpdate(UpdateLoginStatusBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (CollectionUtil.isEmpty(bean.getIds())) {
            throw new RemoteServiceException("单号不能为空");
        }
        String id = bean.getIds().get(0);
        TradeLoginOrder order = tradeLoginOrderService.getById(id);
        if (Objects.isNull(order)
                || !(order.getOrderStatus().equals(TradeOrderStatusEnum.OK.getKey())
                && order.getStatus().equals(TradeFollowStatusEnum.ING.getKey()))
                || order.getIsApplyUpdate()) {
            throw new RemoteServiceException("单据状态不允许申请修改");
        }
        String companyId = null;
        String companyName = null;
        if (adminUser.getIsCustomer()) {
            KingDeeCustomer customer = kingDeeCustomerService.getById(adminUser.getCustomerId());
            if (Objects.nonNull(customer)) {
                KingDeeCustomer parent = kingDeeCustomerService.getById(customer.getParentId());
                if (Objects.nonNull(parent)) {
                    companyId = customer.getParentId();
                    companyName = parent.getName();
                }
            }
        } else {
            companyId = "1";
            companyName = "韶关弘格有限公司";
        }
        tradeLoginOrderService.lambdaUpdate()
                .set(TradeLoginOrder::getApplyUpdateBy, adminUser.getAdminUserId())
                .set(TradeLoginOrder::getApplyUpdateName, adminUser.getNickName())
                .set(TradeLoginOrder::getApplyUpdateCompanyId, companyId)
                .set(TradeLoginOrder::getApplyUpdateCompanyName, companyName)
                .set(TradeLoginOrder::getIsApplyUpdate, IsEnum.YES.getKey())
                .eq(TradeLoginOrder::getId, id)
                .update();

        this.insertOperRecord(id, "申请修改工程信息",
                TradeOperTypeEnum.APPLY_UPDATE.getValue(), bean.getRemark(), false);
    }

    /**
     * 审核修改
     * @param bean
     */
    public void examineUpdate(UpdateLoginStatusBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (!adminUser.getIsTradeExaminer()) {
            throw new RemoteServiceException("非审核员不能操作");
        }
        if (CollectionUtil.isEmpty(bean.getIds())) {
            throw new RemoteServiceException("单号不能为空");
        }
        if (Objects.isNull(bean.getIsSuccess())) {
            throw new RemoteServiceException("审核确认不能为空");
        }
        String id = bean.getIds().get(0);
        TradeLoginOrder order = tradeLoginOrderService.getById(id);
        if (Objects.isNull(order.getLoginStatus())
                || order.getLoginStatus().equals(TradeLoginStatusEnum.REJECT.getKey())
                || !order.getIsApplyUpdate()) {
            throw new RemoteServiceException("单据状态不允许审核修改");
        }
        tradeLoginOrderService.lambdaUpdate()
                .set(TradeLoginOrder::getIsApplyUpdate, IsEnum.NO.getKey())
                .set(bean.getIsSuccess(), TradeLoginOrder::getOrderStatus, TradeOrderStatusEnum.RETURN.getKey())
                .eq(TradeLoginOrder::getId, id)
                .update();

        this.insertOperRecord(id, "申请修改工程信息" + (bean.getIsSuccess() ? "同意" : "拒绝"),
                TradeOperTypeEnum.APPLY_UPDATE.getValue(), bean.getRemark(), false);
    }

    /**
     * 替换业务员
     * @param bean
     */
    public void replaceService(UpdateLoginStatusBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (!adminUser.getIsTradeExaminer()) {
            throw new RemoteServiceException("非审核员不能操作");
        }
        if (StringUtils.isBlank(bean.getServiceId()) || StringUtils.isBlank(bean.getServiceName())) {
            throw new RemoteServiceException("业务员不能为空");
        }
        if (CollectionUtil.isEmpty(bean.getIds())) {
            throw new RemoteServiceException("单号不能为空");
        }

        List<TradeLoginOrder> orderList = tradeLoginOrderService.lambdaQuery()
                .in(TradeLoginOrder::getId, bean.getIds())
                .list();
        tradeLoginOrderService.lambdaUpdate()
                .set(TradeLoginOrder::getServiceId, bean.getServiceId())
                .set(TradeLoginOrder::getServiceName, bean.getServiceName())
                .in(TradeLoginOrder::getId, bean.getIds())
                .update();

        // 插入操作记录
        List<TradeLoginOperRecord> records = new ArrayList<>();
        Date cur = DateUtil.date();
        for (TradeLoginOrder order : orderList) {
            TradeLoginOperRecord record = this.insertOperRecord(order.getId(), "替换业务员：原业务员" + order.getServiceName()
                            + "，更新后业务员" + bean.getServiceName(),
                    TradeOperTypeEnum.REPLACE_SERVICE.getValue(),
                    null, true);
            record.setCreateTime(cur);
            records.add(record);
        }
        tradeLoginOperRecordService.saveBatch(records);
    }

    public UpdateLoginStatusBean applyUpdateQuery(String id) {
        TradeLoginOrder order = tradeLoginOrderService.getById(id);
        TradeLoginOperRecord record = tradeLoginOperRecordService.lambdaQuery()
                .eq(TradeLoginOperRecord::getRefId, id)
                .eq(TradeLoginOperRecord::getOperType, TradeOperTypeEnum.APPLY_UPDATE.getValue())
                .orderByDesc(TradeLoginOperRecord::getCreateTime)
                .last("limit 1")
                .one();

        if (Objects.isNull(order)) {
            throw new RemoteServiceException("单据记录为空");
        }
        if (Objects.isNull(record)) {
            throw new RemoteServiceException("申请修改记录为空");
        }
        UpdateLoginStatusBean bean = new UpdateLoginStatusBean();
        bean.setApplyBy(order.getApplyUpdateName());
        bean.setApplyCompany(order.getApplyUpdateCompanyName());
        bean.setApplyReason(record.getRemark());

        return bean;
    }

    /**
     * 附近跟进中的项目
     * @param id
     * @return
     */
    public List<PositionProjectBean> positionProject(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (!adminUser.getIsTradeExaminer()) {
            return new ArrayList<>();
        }
        TradeLoginOrder order = tradeLoginOrderService.getById(id);
        if (Objects.isNull(order)) {
            throw new RemoteServiceException("暂无附近跟进中的项目");
        }
        SysDict rate = sysDictService.lambdaQuery()
                .eq(SysDict::getDictType, "MAP_ENGIN_RATE")
                .eq(SysDict::getDictCode, "100")
                .one();
        if (Objects.isNull(rate)) {
            throw new RemoteServiceException("找不到地图半径");
        }
        return loginOrderMapper.queryPositionProject(id, order.getLnt(), order.getLat(), rate.getDictValue());
    }

    public IPage<TradeLoginOrder> ref(String projectNo, String projectName, String address, String orderType, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        boolean isSpan = false;
        String type = orderType.equals("工装登录") ? TradeLoginOrderTypeEnum.WORK.getKey() : TradeLoginOrderTypeEnum.HOME.getKey();
        if ("跨区登录".equals(orderType)) {
            type = "";
            isSpan = true;
        }

        return tradeLoginOrderService.lambdaQuery()
                .select(TradeLoginOrder::getProjectNo,TradeLoginOrder::getProjectName,TradeLoginOrder::getEnginLinkName,TradeLoginOrder::getEnginLinkMobile,TradeLoginOrder::getAddress,TradeLoginOrder::getJoinAddress)
                .eq(adminUser.getIsCustomer(), TradeLoginOrder::getCustomerId, adminUser.getCustomerId())
                .like(StringUtils.isNotEmpty(projectNo), TradeLoginOrder::getProjectNo, projectNo)
                .like(StringUtils.isNotEmpty(projectName), TradeLoginOrder::getProjectName, projectName)
                .like(StringUtils.isNotEmpty(address), TradeLoginOrder::getAddress, address)
//                .eq(TradeLoginOrder::getStatus, TradeFollowStatusEnum.ING.getKey())
                .eq(TradeLoginOrder::getIsSpan, isSpan)
                .eq(StringUtils.isNotBlank(type), TradeLoginOrder::getOrderType, type)
                .eq(TradeLoginOrder::getOrderStatus, TradeOrderStatusEnum.OK.getKey())
                .eq(TradeLoginOrder::getLoginStatus, TradeLoginStatusEnum.OK.getKey())
                .and(v -> v.eq(TradeLoginOrder::getRefCustomerId, "")
                        .or(adminUser.getIsCustomer(), vo -> vo.eq(TradeLoginOrder::getRefCustomerId, adminUser.getCustomerId())))
                .orderByDesc(TradeLoginOrder::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
    }

    private void beanChangeContent(TradeLoginOrder oldOrder, TradeLoginOrderBean newOrder) {
        StringBuilder sb = new StringBuilder();
        Map<String, Object> followMap = EnumUtil.getNameFieldMap(TradeFollowStatusEnum.class, "value");
        Map<String, Object> categoryMap = EnumUtil.getNameFieldMap(TradeLoginCategoryEnum.class, "value");
        Map<String, Object> orderMap = EnumUtil.getNameFieldMap(TradeLoginOrderTypeEnum.class, "value");
        Map<String, Object> typeMap = EnumUtil.getNameFieldMap(TradeLoginTypeEnum.class, "value");
        Map<String, Object> machineMap = EnumUtil.getNameFieldMap(TradeMachineTypeEnum.class, "value");
        Map<String, Object> areaMap = EnumUtil.getNameFieldMap(TradeProjectAreaEnum.class, "value");
        Map<String, Object> rateMap = EnumUtil.getNameFieldMap(TradeSuccessRateEnum.class, "value");

        if (oldOrder.getIsSpan()) {
            if (!Objects.equals(oldOrder.getOrderType(), newOrder.getOrderType())) {
                sb.append("原项目性质：");
                sb.append(orderMap.get(oldOrder.getOrderType()));
                sb.append(", 新项目性质：");
                sb.append(orderMap.get(newOrder.getOrderType()));
                sb.append("\n");
            }
        }

        if (!Objects.equals(oldOrder.getProjectArea(), newOrder.getProjectArea())) {
            if (oldOrder.getIsSpan()) {
                sb.append("原业务所在区域：");
                sb.append(Optional.ofNullable(areaMap.get(oldOrder.getProjectArea())).orElse(""));
                sb.append(", 新业务所在区域：");
                sb.append(Optional.ofNullable(areaMap.get(newOrder.getProjectArea())).orElse(""));
                sb.append("\n");
            } else {
                sb.append("原项目所在区域：");
                sb.append(Optional.ofNullable(areaMap.get(oldOrder.getProjectArea())).orElse(""));
                sb.append(", 新项目所在区域：");
                sb.append(Optional.ofNullable(areaMap.get(newOrder.getProjectArea())).orElse(""));
                sb.append("\n");
            }
        }

        if (!Objects.equals(oldOrder.getServiceId(), newOrder.getServiceId())) {
            sb.append("原业务员名称：");
            sb.append(oldOrder.getServiceName());
            sb.append(", 新业务员名称：");
            sb.append(newOrder.getServiceName());
            sb.append("\n");
        }

        if (oldOrder.getOrderType().equals(TradeLoginOrderTypeEnum.WORK.getKey())) {
            if (!Objects.equals(oldOrder.getPartyAId(), newOrder.getPartyAId())) {
                sb.append("原甲方名称：");
                sb.append(oldOrder.getPartyA());
                sb.append(", 新甲方名称：");
                sb.append(newOrder.getPartyA());
                sb.append("\n");
            }
        }

        if (!Objects.equals(oldOrder.getCustomerId(), newOrder.getCustomerId())) {
            sb.append("原经销商：");
            sb.append(oldOrder.getCustomerName());
            sb.append(", 新经销商：");
            sb.append(newOrder.getCustomerName());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getCustomerLinkName(), newOrder.getCustomerLinkName())) {
            sb.append("原经销商联系人：");
            sb.append(oldOrder.getCustomerLinkName());
            sb.append(", 新经销商联系人：");
            sb.append(newOrder.getCustomerLinkName());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getCustomerLinkMobile(), newOrder.getCustomerLinkMobile())) {
            sb.append("原经销商联系电话：");
            sb.append(oldOrder.getCustomerLinkMobile());
            sb.append(", 新经销商联系电话：");
            sb.append(newOrder.getCustomerLinkMobile());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getCustomerAddress(), newOrder.getCustomerAddress())) {
            sb.append("原经销商办公地址：");
            sb.append(oldOrder.getCustomerAddress());
            sb.append(", 新经销商办公地址：");
            sb.append(newOrder.getCustomerAddress());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getFollowCustomer(), newOrder.getFollowCustomer())) {
            sb.append("原跟进经销商：");
            sb.append(oldOrder.getFollowCustomer());
            sb.append(", 新跟进经销商：");
            sb.append(newOrder.getFollowCustomer());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getFollowCustomerMobile(), newOrder.getFollowCustomerMobile())) {
            sb.append("原跟进经销商电话：");
            sb.append(oldOrder.getFollowCustomerMobile());
            sb.append(", 新跟进经销商电话：");
            sb.append(newOrder.getFollowCustomerMobile());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getProjectName(), newOrder.getProjectName())) {
            sb.append("原工程项目名称：");
            sb.append(oldOrder.getProjectName());
            sb.append(", 新工程项目名称：");
            sb.append(newOrder.getProjectName());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getEnginLinkName(), newOrder.getEnginLinkName())) {
            sb.append("原工程联系人：");
            sb.append(oldOrder.getEnginLinkName());
            sb.append(", 新工程联系人：");
            sb.append(newOrder.getEnginLinkName());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getEnginLinkMobile(), newOrder.getEnginLinkMobile())) {
            sb.append("原工程联系电话：");
            sb.append(oldOrder.getEnginLinkMobile());
            sb.append(", 新工程联系电话：");
            sb.append(newOrder.getEnginLinkMobile());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getAddress(), newOrder.getAddress())) {
            sb.append("原详细地址：");
            sb.append(oldOrder.getAddress());
            sb.append(", 新详细地址：");
            sb.append(newOrder.getAddress());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getProjectCategory(), newOrder.getProjectCategory())) {
            sb.append("原项目类别：");
            sb.append(categoryMap.get(oldOrder.getProjectCategory()));
            sb.append(", 新项目类别：");
            sb.append(categoryMap.get(newOrder.getProjectCategory()));
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getType(), newOrder.getType())) {
            sb.append("原类型：");
            sb.append(typeMap.get(oldOrder.getType()));
            sb.append(", 新类型：");
            sb.append(typeMap.get(newOrder.getType()));
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getExtent(), newOrder.getExtent())) {
            sb.append("原建筑面积：");
            sb.append(oldOrder.getExtent());
            sb.append(", 新建筑面积：");
            sb.append(newOrder.getExtent());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getUseExtent(), newOrder.getUseExtent())) {
            sb.append("原空调使用面积：");
            sb.append(oldOrder.getUseExtent());
            sb.append(", 新空调使用面积：");
            sb.append(newOrder.getUseExtent());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getTradeParentId(), newOrder.getTradeParentId())) {
            sb.append("原项目所在行业分类：");
            sb.append(oldOrder.getTradeParentName());
            sb.append(", 新项目所在行业分类：");
            sb.append(newOrder.getTradeParentName());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getTradeId(), newOrder.getTradeId())) {
            sb.append("原行业细分：");
            sb.append(oldOrder.getTradeName());
            sb.append(", 新行业细分：");
            sb.append(newOrder.getTradeName());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getMachineType(), newOrder.getMachineType())) {
            sb.append("原机组类型：");
            sb.append(machineMap.get(oldOrder.getMachineType()));
            sb.append(", 新机组类型：");
            sb.append(machineMap.get(newOrder.getMachineType()));
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getSuccessRate(), newOrder.getSuccessRate())) {
            sb.append("原成功机率：");
            sb.append(rateMap.get(oldOrder.getSuccessRate()));
            sb.append(", 新成功机率：");
            sb.append(rateMap.get(newOrder.getSuccessRate()));
            sb.append("\n");
        }

        if (Objects.nonNull(oldOrder.getPreSignDate()) && oldOrder.getPreSignDate().getTime() != newOrder.getPreSignDate().getTime()) {
            sb.append("原预计签定合同日期：");
            sb.append(DateUtil.formatDate(oldOrder.getPreSignDate()));
            sb.append(", 新预计签定合同日期：");
            sb.append(DateUtil.formatDate(newOrder.getPreSignDate()));
            sb.append("\n");
        } else if (Objects.isNull(oldOrder.getPreSignDate())) {
            sb.append("原预计签定合同日期：");
            sb.append(" ");
            sb.append(", 新预计签定合同日期：");
            sb.append(DateUtil.formatDate(newOrder.getPreSignDate()));
            sb.append("\n");
        }

        if (oldOrder.getPreDeviceAmount().compareTo(newOrder.getPreDeviceAmount()) != 0) {
            sb.append("原预计设备金额：");
            sb.append(oldOrder.getPreDeviceAmount());
            sb.append(", 新预计设备金额：");
            sb.append(newOrder.getPreDeviceAmount());
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getStatus(), newOrder.getStatus())) {
            sb.append("原工程跟进状态：");
            sb.append(followMap.get(oldOrder.getStatus()));
            sb.append(", 新工程跟进状态：");
            sb.append(followMap.get(newOrder.getStatus()));
            sb.append("\n");
        }

        if (!Objects.equals(oldOrder.getOtherInfo(), newOrder.getOtherInfo())) {
            sb.append("原其他相关信息：");
            sb.append(oldOrder.getOtherInfo());
            sb.append(", 新其他相关信息：");
            sb.append(newOrder.getOtherInfo());
        }

        newOrder.setOldNewContent(sb.toString());
    }

    private boolean checkOrderLimit(TradeLoginOrderBean bean) {
        boolean isOver = false;
        CustomerBillLimitConfig config = customerBillLimitConfigService.lambdaQuery()
                .eq(CustomerBillLimitConfig::getCustomerId, bean.getCustomerId())
                .eq(CustomerBillLimitConfig::getState, IsEnum.YES.getKey())
                .one();
        if (Objects.nonNull(config)) {
            OrderTypeCountBean countBean = loginOrderMapper.orderCount(bean.getCustomerId());
            if (bean.getIsSpan()) {
                isOver = countBean.getSpanCount() >= config.getSpanLoginLimit();
            }
            if (!bean.getIsSpan() && bean.getOrderType().equals(TradeLoginOrderTypeEnum.WORK.getKey())) {
                isOver = countBean.getWorkCount() >= config.getWorkLoginLimit();
            }
            if (!bean.getIsSpan() && bean.getOrderType().equals(TradeLoginOrderTypeEnum.HOME.getKey())) {
                isOver = countBean.getHomeCount() >= config.getHomeLoginLimit();
            }
        }
        return isOver;
    }

    public IPage<DataLoginOrderVO> dataListPage(ZfireParamBean zfireParamBean) {
        FieldUtils.supplyParam(zfireParamBean);
        IPage<DataLoginOrderVO> page = loginOrderMapper.dataListPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        for (DataLoginOrderVO record : page.getRecords()) {
            BigDecimal homeSignCount = BigDecimal.valueOf(record.getHomeSignCount());
            BigDecimal homeLossCount = BigDecimal.valueOf(record.getHomeLossCount());
            if (homeSignCount.compareTo(BigDecimal.ZERO) > 0) {
                record.setHomeSignRate(homeSignCount.divide(homeSignCount.add(homeLossCount), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                record.setHomeSignRate(BigDecimal.ZERO);
            }
            if (homeSignCount.compareTo(BigDecimal.ZERO) > 0) {
                record.setHomeLossRate(homeLossCount.divide(homeSignCount.add(homeLossCount), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                record.setHomeLossRate(BigDecimal.ZERO);
            }

            BigDecimal workSignCount = BigDecimal.valueOf(record.getWorkSignCount());
            BigDecimal workLossCount = BigDecimal.valueOf(record.getWorkLossCount());
            if (workSignCount.compareTo(BigDecimal.ZERO) > 0) {
                record.setWorkSignRate(workSignCount.divide(workSignCount.add(workLossCount), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                record.setWorkSignRate(BigDecimal.ZERO);
            }
            if (workLossCount.compareTo(BigDecimal.ZERO) > 0) {
                record.setWorkLossRate(workLossCount.divide(workSignCount.add(workLossCount), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                record.setWorkLossRate(BigDecimal.ZERO);
            }

            BigDecimal spanSignCount = BigDecimal.valueOf(record.getSpanSignCount());
            BigDecimal spanLossCount = BigDecimal.valueOf(record.getSpanLossCount());
            if (spanSignCount.compareTo(BigDecimal.ZERO) > 0) {
                record.setSpanSignRate(spanSignCount.divide(spanSignCount.add(spanLossCount), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                record.setSpanSignRate(BigDecimal.ZERO);
            }
            if (spanLossCount.compareTo(BigDecimal.ZERO) > 0) {
                record.setSpanLossRate(spanLossCount.divide(spanSignCount.add(spanLossCount), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                record.setSpanLossRate(BigDecimal.ZERO);
            }

        }
        return page;
    }

    /**
     * 操作记录
     * @param id
     * @return
     */
    public List<TradeLoginOperRecord> operationRecord(String id) {
        return tradeLoginOperRecordService.lambdaQuery()
                .eq(TradeLoginOperRecord::getRefId, id)
                .orderByDesc(TradeLoginOperRecord::getCreateTime)
                .list();
    }

    public IPage<LoginOrderVO> listPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        this.commonSetParams(zfireParamBean, adminUser);
        return loginOrderMapper.list(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getAdminUserId());
    }

    public TradeLoginCustomerInfo customerHistory(String customerId) {
        return tradeLoginCustomerInfoService.getById(customerId);
    }

    public String importData(InputStream inputStream, HttpServletRequest request, String confirmBy, String confirmName) {
        try {
            //读取excel数据
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            reader.addHeaderAlias("单据类型", "orderType");
            reader.addHeaderAlias("是否跨区", "isSpanStr");
            reader.addHeaderAlias("项目所在区域", "projectArea");
            reader.addHeaderAlias("项目编号", "projectNo");
            reader.addHeaderAlias("登录日期", "submitTime");
            reader.addHeaderAlias("更新日期", "orderUpdateTime");
            reader.addHeaderAlias("业务员名称", "serviceName");
            reader.addHeaderAlias("甲方名称", "partyA");
            reader.addHeaderAlias("经销商编号", "customerNumber");
            reader.addHeaderAlias("经销商名称", "customerName");
            reader.addHeaderAlias("经销商联系人", "customerLinkName");
            reader.addHeaderAlias("经销商联系电话", "customerLinkMobile");
            reader.addHeaderAlias("经销商办公地址", "customerAddress");
            reader.addHeaderAlias("跟进经销商", "followCustomer");
            reader.addHeaderAlias("跟进经销商电话", "followCustomerMobile");
            reader.addHeaderAlias("工程项目名称", "projectName");
            reader.addHeaderAlias("工程联系人", "enginLinkName");
            reader.addHeaderAlias("工程联系电话", "enginLinkMobile");
            reader.addHeaderAlias("详细地址", "joinAddress");
            reader.addHeaderAlias("项目类别", "projectCategory");
            reader.addHeaderAlias("类型", "type");
            reader.addHeaderAlias("建筑面积", "extent");
            reader.addHeaderAlias("空调使用面积", "useExtent");
            reader.addHeaderAlias("项目所在行业分类名称", "tradeParentName");
            reader.addHeaderAlias("行业细分名称", "tradeName");
            reader.addHeaderAlias("项目性质", "projectMent");
            reader.addHeaderAlias("机组类型", "machineType");
            reader.addHeaderAlias("成功机率", "successRate");
            reader.addHeaderAlias("预计签定合同日期", "preSignDate");
            reader.addHeaderAlias("预计设备金额", "preDeviceAmount");
            reader.addHeaderAlias("工程跟进状态", "status");
            reader.addHeaderAlias("备注", "remark");
            reader.addHeaderAlias("其他相关信息", "otherInfo");
            reader.addHeaderAlias("登录状态", "loginStatus");
            reader.addHeaderAlias("登录成功项目编号", "successLoginProject");
            reader.addHeaderAlias("登录成功经销商名称", "successCustomerName");
            reader.addHeaderAlias("登录成功业务员", "successServiceName");
            reader.addHeaderAlias("审核备注", "note");
            reader.addHeaderAlias("共同跟进项目编号", "commonFollowProject");
            reader.addHeaderAlias("附件名称", "oldFileName");
            reader.addHeaderAlias("附件下载链接", "oldFileUrl");
            reader.addHeaderAlias("登录机型", "loginMachine");

            List<TradeOrderImportBean> orderList = reader.readAll(TradeOrderImportBean.class);

            int handleCount = 0;
            if (CollectionUtil.isNotEmpty(orderList)) {
                List<KingDeeCustomer> customerList = kingDeeCustomerService.list();

                // 经销商
                Map<String, KingDeeCustomer> customerMap = customerList.stream()
                        .collect(Collectors.toMap(KingDeeCustomer::getNumber, Function.identity()));

                List<AdminUserDto> serviceList = adminUserLogic.listService(null, null, null, false, null, true, null, 1, -1, request)
                        .getRecords();

                // 业务员
                Map<String, AdminUserDto> serviceMap = serviceList.stream()
                        .collect(Collectors.toMap(AdminUserDto::getNickName, Function.identity(), (key1, key2) -> key2));

                List<TradeCategoryConfig> parentCategoryList = tradeCategoryConfigService.lambdaQuery()
                        .eq(TradeCategoryConfig::getParentId, 0)
                        .list();

                // 行业大类
                Map<String, TradeCategoryConfig> parentMap = parentCategoryList.stream()
                        .collect(Collectors.toMap(TradeCategoryConfig::getName, Function.identity()));

                List<TradeCategoryConfig> categoryList = tradeCategoryConfigService.lambdaQuery()
                        .ne(TradeCategoryConfig::getParentId, 0)
                        .list();

                // 行业小类
                Map<String, TradeCategoryConfig> categoryMap = categoryList.stream()
                        .collect(Collectors.toMap(TradeCategoryConfig::getName, Function.identity()));

                Map<String, TradeCategoryConfig> notCategoryMap = categoryList.stream()
                        .collect(Collectors.toMap(TradeCategoryConfig::getParentId, Function.identity(), (key1, key2) -> key1));

                // 省、市、区、街道
                List<LbsAmap> provinceList = lbsAmapService.lambdaQuery()
                        .eq(LbsAmap::getLevel, "province")
                        .list();

                List<LbsAmap> cityList = lbsAmapService.lambdaQuery()
                        .eq(LbsAmap::getLevel, "city")
                        .list();

                List<LbsAmap> districtList = lbsAmapService.lambdaQuery()
                        .eq(LbsAmap::getLevel, "district")
                        .list();

                List<LbsAmap> streetList = lbsAmapService.lambdaQuery()
                        .eq(LbsAmap::getLevel, "street")
                        .list();

                Map<String, LbsAmap> provinceMap = provinceList.stream()
                        .collect(Collectors.toMap(LbsAmap::getName, Function.identity()));

                Map<String, LbsAmap> cityMap = cityList.stream()
                        .collect(Collectors.toMap(v -> v.getCityCode() + v.getName(), Function.identity()));

                Map<String, LbsAmap> districtMap = districtList.stream()
                        .collect(Collectors.toMap(v -> v.getCityCode() + v.getAdCode() + v.getName(), Function.identity()));

                Map<String, LbsAmap> streetMap = streetList.stream()
                        .collect(Collectors.toMap(v -> v.getParentLbsId() + v.getName(), Function.identity()));

                List<SysDict> machineTypeList = sysDictService.lambdaQuery()
                        .eq(SysDict::getDictType, "LOGIN_MACHINE_TYPE")
                        .list();

                Map<String, SysDict> machineTypeMap = machineTypeList.stream()
                        .collect(Collectors.toMap(SysDict::getDictValue, Function.identity()));


                for (TradeOrderImportBean bean : orderList) {
                    TradeLoginOrder order = new TradeLoginOrder();
                    order.setIsOld(true);
                    bean.setOrderType(TradeLoginOrderTypeEnum.findKeyByValue(bean.getOrderType()));
                    if (StringUtils.isBlank(bean.getOrderType())) {
                        throw new RemoteServiceException("第" + (handleCount+2) + "行，单据类型不能为空");
                    }
                    bean.setIsSpan(IsEnum.findKeyByValue(bean.getIsSpanStr()));
                    if (Objects.isNull(bean.getIsSpan())) {
                        throw new RemoteServiceException("第" + (handleCount+2) + "行，是否跨区不能为空");
                    }
                    if (StringUtils.isBlank(bean.getProjectArea())) {
                        throw new RemoteServiceException("第" + (handleCount+2) + "行，项目所在区域不能为空");
                    }
                    if (StringUtils.isBlank(bean.getProjectNo())) {
//                        throw new RemoteServiceException("第" + (handleCount+2) + "行，项目编号不能为空");
                        bean.setProjectNo(commonLogic.generateTradeLoginNo(bean.getIsSpan() ? "SPAN" : OrderTypeEnum.TRADE.getKey(), 8));
                    }
                    Integer count = tradeLoginOrderService.lambdaQuery()
                            .eq(TradeLoginOrder::getOrderType, bean.getOrderType())
                            .eq(TradeLoginOrder::getIsSpan, bean.getIsSpan())
                            .eq(TradeLoginOrder::getProjectNo, bean.getProjectNo())
                            .count();
                    if (count > 0) {
                        handleCount++;
                        continue;
                    }
                    if (StringUtils.isBlank(bean.getServiceName())) {
                        throw new RemoteServiceException("第" + (handleCount+2) + "行，业务员名称不能为空");
                    }
                    AdminUserDto service = serviceMap.get(bean.getServiceName().trim());
                    if (Objects.isNull(service)) {
                        throw new RemoteServiceException("第" + (handleCount+2) + "行，" + bean.getServiceName() + "系统找不到对应的业务员名称");
                    }
                    bean.setServiceId(service.getAdminUserId());
                    bean.setServiceNumber(service.getUserName());
//                    if (StringUtils.isBlank(bean.getCustomerNumber())) {
//                        throw new RemoteServiceException("第" + (handleCount+2) + "行，经销商名称不能为空");
//                    }
                    KingDeeCustomer customer = customerMap.get(bean.getCustomerNumber().trim());
//                    if (Objects.isNull(customer)) {
//                        throw new RemoteServiceException("第" + (handleCount+2) + "行，"+ bean.getCustomerNumber() +"系统找不到对应的经销商编号");
//                    }
                    if (Objects.nonNull(customer)) {
                        bean.setCustomerId(customer.getId());
                    }
                    if (StringUtils.isBlank(bean.getJoinAddress())) {
                        throw new RemoteServiceException("第" + (handleCount+2) + "行，详细地址不能为空");
                    }
                    if (StringUtils.isBlank(lbsWebKey)) {
                        throw new RemoteServiceException("未配置地图key");
                    }

                    // 获取高德地址
                    String reqUrl = url + "/v3/geocode/geo?key=" + lbsWebKey + "&address=" + bean.getJoinAddress();
                    JSONObject addressObj = this.reqGeocodeUrl(reqUrl, (handleCount+2));
                    if (Objects.nonNull(addressObj)) {
                        String lbsProvince = addressObj.get("province", String.class);
                        String lbsCity = addressObj.get("city", String.class);
                        String lbsCityCode = addressObj.get("citycode", String.class);
                        String lbsDistrict = addressObj.get("district", String.class);
                        String lbsAdCode = addressObj.get("adcode", String.class);
                        String lbsStreet = addressObj.get("street", String.class);
                        String lbsLocation = addressObj.get("location", String.class);

                        LbsAmap province = provinceMap.get(lbsProvince);
                        LbsAmap city = cityMap.get(lbsCityCode + lbsCity);
                        LbsAmap district = districtMap.get(lbsCityCode + lbsAdCode + lbsDistrict);
                        LbsAmap street = Objects.nonNull(district) ? streetMap.get(district.getLbsId() + lbsStreet) : null;
                        String[] split = lbsLocation.split(",");
                        bean.setLnt(split[0]);
                        bean.setLat(split[1]);

                        bean.setProvinceId(Objects.nonNull(province) ? province.getLbsId() : null);
                        bean.setCityId(Objects.nonNull(city) ? city.getLbsId() : null);
                        bean.setAreaId(Objects.nonNull(district) ? district.getLbsId() : null);
                        bean.setStreetId(Objects.nonNull(street) ? street.getLbsId() : null);
                    }
                    bean.setAddress(bean.getJoinAddress());

                    if (StringUtils.isNotBlank(bean.getTradeParentName())) {
//                        throw new RemoteServiceException("第" + (handleCount+2) + "行，项目所在行业分类名称不能为空");
                        TradeCategoryConfig parentCategory = parentMap.get(bean.getTradeParentName());
                        if (Objects.isNull(parentCategory)) {
                            throw new RemoteServiceException("第" + (handleCount+2) + "行，系统找不到项目所在行业分类名称");
                        }

                        TradeCategoryConfig categoryConfig = categoryMap.get(bean.getTradeName());
                        if (Objects.isNull(categoryConfig)) {
                            categoryConfig = notCategoryMap.get(parentCategory.getId());
                        }
                        bean.setTradeParentId(parentCategory.getId());
                        bean.setTradeId(categoryConfig.getId());
                    }

                    SysDict sysDict = machineTypeMap.get(bean.getMachineType());
                    bean.setMachineType(Objects.nonNull(sysDict) ? sysDict.getDictCode() : null);

                    if (StringUtils.isNotBlank(bean.getLoginStatus())) {
                        String str = StrUtil.trim(bean.getLoginStatus());
                        if (str.equals("登录成功")) {
                            bean.setLoginStatus(TradeLoginStatusEnum.OK.getKey());
                            bean.setOrderStatus(TradeOrderStatusEnum.OK.getKey());
                        } else if (str.equals("登录不成功")) {
                            bean.setLoginStatus(TradeLoginStatusEnum.FAIL.getKey());
                            bean.setOrderStatus(TradeOrderStatusEnum.FAIL.getKey());
                        } else if (str.equals("驳回")) {
                            bean.setLoginStatus(TradeLoginStatusEnum.REJECT.getKey());
                            bean.setOrderStatus(TradeOrderStatusEnum.RETURN.getKey());
                        } else if (str.equals("未审核")) {
                            bean.setOrderStatus(TradeOrderStatusEnum.WAIT.getKey());
                        }
                    } else {
                        bean.setOrderStatus(TradeOrderStatusEnum.RETURN.getKey());
                    }

                    BeanUtils.copyProperties(bean, order);
                    order.setId(IdWorker.getIdStr())
                            .setAdminCompanyId("1")
                            .setAdminWebsitId("1")
                            .setAdminUserId("1406884583118491649")
                            .setConfirmBy(confirmBy)
                            .setConfirmName(confirmName)
                            .setConfirmTime(bean.getSubmitTime())
                            .insert();

                    tradeLoginOrderService.lambdaUpdate()
                            .set(TradeLoginOrder::getCreateTime, bean.getSubmitTime())
                            .set(TradeLoginOrder::getUpdateTime, bean.getSubmitTime())
                            .eq(TradeLoginOrder::getId, order.getId())
                            .update();

                    if (StringUtils.isNotBlank(bean.getLoginMachine())) {
                        String[] machine = bean.getLoginMachine().split(",");

                        List<TradeLoginOrderItem> items = new ArrayList<>();
                        for (String s : machine) {
                            TradeLoginOrderItem item = new TradeLoginOrderItem();
                            item.setOrderId(order.getId())
                                    .setProjectNo(order.getProjectNo())
                                    .setQty(1)
                                    .setSpecification(s)
                                    .setIsOld(true);
                            items.add(item);
                        }
                        tradeLoginOrderItemService.saveBatch(items);
                        bean.setLoginMachine(null);
                    }

                    handleCount++;
                }
            }

            log.info("导入" + orderList.size() + "条, 执行" + handleCount + "条");

            return "导入" + orderList.size() + "条, 执行" + handleCount + "条";
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }

    private JSONObject reqGeocodeUrl(String reqUrl, int idx) {
        String body = HttpUtil.get(reqUrl);
        JSONObject resultJson = JSONUtil.parseObj(body);
        String status = resultJson.get("status", String.class);
        String info = resultJson.get("info", String.class);
        if ("0".equals(status)) {
            log.info("第" + idx + "行，高德逆编码失败：" + info);
            return null;
        }

        JSONArray districts = resultJson.getJSONArray("geocodes");

        if (districts.size() < 1) {
//            throw new RemoteServiceException("第" + idx + "行，详细地址高德未找到匹配的内容");
            return null;
        }

        return districts.getJSONObject(0);
    }

    public void checkLimit(TradeLoginOrderBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (!adminUser.getIsCustomer()) {
            return;
        }
        bean.setCustomerId(adminUser.getCustomerId());
        if (this.checkOrderLimit(bean)) {
            throw new RemoteServiceException("登录名额已满");
        }
    }

    public IPage<LoginOrderVO> recycleListPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        if (!adminUser.getIsTradeExaminer()) {
            throw new RemoteServiceException("非登录审核员权限,禁止查询");
        }
        this.commonSetParams(zfireParamBean, adminUser);
        return loginOrderMapper.recycleListPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public void recycleDel(List<String> ids) {
        loginOrderMapper.batchInsertLogin(ids);
        loginOrderMapper.recycleDel(ids);
    }

    public void recycleRestore(List<String> ids) {
        loginOrderMapper.recycleRestore(ids);
    }
}
