package com.ywt.service;

import com.ywt.config.ParameterConfigurer;
import com.ywt.core.*;
import com.ywt.core.utils.Checker;
import com.ywt.core.utils.DateUtil;
import com.ywt.core.utils.FormatUtil;
import com.ywt.core.utils.serializers.JsonSerializer;
import com.ywt.domain.entity.center.HospitalRepository;
import com.ywt.domain.entity.center.SnsUserInfo;
import com.ywt.domain.entity.center.SnsUserInfoRepository;
import com.ywt.domain.entity.glasses.*;
import com.ywt.domain.models.ConstantDef;
import com.ywt.domain.models.enums.*;

import com.ywt.gapi.ResultCode;
import com.ywt.gapi.ordercenter.RefundResponse;
import com.ywt.params.mg.order.*;
import com.ywt.service.common.OrderCenterService;
import com.ywt.service.common.WeChatMessageService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Types;
import java.util.*;
import java.util.stream.Collectors;

@DubboService
@Service
public class MgGoodsOrdersService extends ServiceBase {

    private static final Logger logger = LoggerFactory.getLogger(MgGoodsOrdersService.class);

    @Autowired
    private GoodsOrdersRepository goodsOrdersRepository;

    @Autowired
    private GoodsOrdersDetailRepository goodsOrdersDetailRepository;

    @Autowired
    private PostAddressRepository postAddressRepository;

    @Autowired
    private DictTypeService dictTypeService;

    @Autowired
    private UserService userService;

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private OrderCenterService orderCenterService;

    @Autowired
    private ParameterConfigurer parameterConfigurer;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private GoodsOrdersService goodsOrdersService;

    @Autowired
    @Qualifier("sqlHelperGlasses")
    private SqlHelper sqlHelperGlasses;

    @Autowired
    @Qualifier("glassesJdbcTemplate")
    private JdbcTemplate glassesJdbcTemplate;

    @Autowired
    private GlassesIdGenerator glassesIdGenerator;

    @Autowired
    private WeChatMessageService weChatMessageService;

    @Autowired
    private SnsUserInfoRepository snsUserInfoRepository;

    private PagedList<Goods> getGoodsPagedList(GetGoodsListRequest request) {
        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();

        List<Object> paramList = new ArrayList<>();
        String whereSql = " ( 1=1 ) and deleted = 0 and shop_id = ? ";

        int shopId = userService.getShopId();
        shopId = shopId > 0 ? shopId : 1;
        paramList.add(shopId);

        int typeId = request.getTypeId();
        if (typeId > 0) {
            whereSql += " and type_id = ? ";
            paramList.add(typeId);
        }
        return sqlHelperGlasses.getPagedList(pageIndex, pageSize, "*", whereSql, "weight desc, id desc", Goods.class, paramList.toArray());
    }

    public BaseResponse getGoodsList(GetGoodsListRequest request) {
        PageDataResponse<Object> response = new PageDataResponse<>();
        List<Object> returnValue = new ArrayList<>();

        PagedList<Goods> goodsPageList = getGoodsPagedList(request);
        List<Goods> goodsList = goodsPageList.getItems();
        if (!Checker.isNone(goodsList)) {
            for (Goods goods : goodsList) {
                HashMap<Object, Object> map = new HashMap<>();
                map.put("goodsId", goods.getId());
                map.put("name", goods.getName());
                map.put("spec", goods.getSpec());
                map.put("unitName", goods.getUnitName());
                map.put("brandName", goods.getBrandName());
                map.put("unitPrice", FormatUtil.intShrink100ToStr(goods.getUnitPrice()));
                map.put("pic", goods.getPic());
                map.put("inventory", goods.getInventory());
                returnValue.add(map);
            }
        }
        response.setData(returnValue);
        response.setTotalCount(goodsPageList.getTotal());
        response.setPageIndex(request.getPageIndex());
        response.setPageSize(request.getPageSize());
        return response;
    }

    public DataResponse<CreateOrderResponse> createOrder(CreateOrderRequest request) {
        DataResponse<CreateOrderResponse> response = new DataResponse<>();
        List<GoodsDTO> goodsDtoList = request.getGoodsList();
        if (Checker.isNone(goodsDtoList)) {
            return response.failedWithParameterError("请先选择商品");
        }
        int getChannel = request.getGetChannel();
        String postMobile = request.getPostMobile();
        String postName = request.getPostName();
        String postProvince = request.getPostProvince();
        String postCity = request.getPostCity();
        String postArea = request.getPostArea();
        String postAddress = request.getPostAddress();
        boolean boo = getChannel == GetChannelEnum.MAIL.getValue()
                && (Checker.isNone(postMobile) || Checker.isNone(postName) || Checker.isNone(postProvince)
                || Checker.isNone(postCity) || ((!"台湾省".equals(postProvince)) && Checker.isNone(postArea)) || Checker.isNone(postAddress));
        if (boo) {
            return response.failedWithParameterError("请先填写好邮寄地址");
        }
        int detailPayAmount = 0;
        List<Goods> goodsList = getGoodsListByGoodsDTOList(goodsDtoList);
        for (GoodsDTO dto : goodsDtoList) {
            Goods goods = goodsList.stream().filter(p -> p.getId().equals(dto.getGoodsId())).findFirst().orElse(null);
            if (!Checker.isNone(goods)) {
                detailPayAmount += (goods.getUnitPrice() * dto.getDiscount() * dto.getGoodsNumber()) / 100;
                if (goods.getInventory() - dto.getGoodsNumber() < 0) {
                    return response.failedWithParameterError(goods.getName() + "库存不足");
                }
            }
        }
        int payAmount = request.getPayAmount();
        if (payAmount != detailPayAmount) {
            return response.failedWithParameterError("商品金额不匹配");
        }
        int addressId = 0;
        PostAddress address = null;
        if (getChannel == GetChannelEnum.MAIL.getValue()) {
            address = new PostAddress();
            addressId = glassesIdGenerator.genPostAddressId();
            address.setId(addressId);
            address.setMobile(postMobile);
            address.setName(postName);
            address.setAddressIds(request.getPostAddressIds());
            address.setProvince(postProvince);
            address.setCity(postCity);
            address.setArea(postArea);
            address.setAddress(postAddress);
            address.setDeleted(0);
            address.setCreatTime(new Date());
            address.setUpdateTime(new Date());
        }
        GoodsOrders orders = new GoodsOrders();
        int goodsOrdersId = glassesIdGenerator.genGoodsOrdersId();
        orders.setId(goodsOrdersId);
        orders.setShopId(userService.getShopId());
        orders.setHospitalId(userService.getHospitalId());
        orders.setGlassesParam(JsonSerializer.toJson(request.getParam()));
        orders.setUserId(0);
        orders.setPatientName(Checker.getStringValue(request.getPatientName()));
        orders.setAge(Checker.getIntegerValue(request.getAge()));
        orders.setSex(Checker.getIntegerValue(request.getSex()));
        orders.setMobile(Checker.getStringValue(request.getMobile()));
        orders.setPaymentStatus(PaymentStatusEnum.Pending.getValue());
        orders.setPayAmount(payAmount);
        orders.setStatus(GoodsOrdersStatusEnum.PendingPayment.getValue());
        orders.setGetChannel(getChannel);
        orders.setAddressId(addressId);
        orders.setDeleted(0);
        orders.setCreateTime(new Date());
        orders.setUpdateTime(new Date());
        orders.setOpBy(userService.getCurrentAdminAcount());

        ArrayList<GoodsOrdersDetail> detailList = new ArrayList<>();
        for (GoodsDTO dto : goodsDtoList) {
            GoodsOrdersDetail detail = new GoodsOrdersDetail();
            detail.setId(glassesIdGenerator.genGoodsOrdersDetailId());
            detail.setGoodsOrdersId(goodsOrdersId);
            detail.setRemark(dto.getRemark());
            Goods goods = goodsList.stream().filter(p -> p.getId().equals(dto.getGoodsId())).findFirst().orElse(null);
            if (!Checker.isNone(goods)) {
                detail.setGoodsId(goods.getId());
                detail.setGoodsName(goods.getName());
                detail.setGoodsPrice(new Double(goods.getUnitPrice() * dto.getDiscount() / 100.0).intValue());
                detail.setGoodsPic(Checker.getStringValue(goods.getPic()));
                detail.setGoodsSpec(Checker.getStringValue(goods.getSpec()));
                detail.setOldPrice(goods.getUnitPrice());
                detail.setTypeId(goods.getTypeId());
                detail.setTypeName(Checker.getStringValue(goods.getTypeName()));
                detail.setPayAmount(new Double(goods.getUnitPrice() * dto.getGoodsNumber() * dto.getDiscount() / 100.0).intValue());
            }
            detail.setGoodsNumber(dto.getGoodsNumber());
            detail.setDiscount(dto.getDiscount());
            detail.setDeleted(0);
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            detailList.add(detail);
        }
        int code = saveToDataBase(getChannel, address, orders, detailList);
        if (code != 0) {
            return response.failedWithAppError("数据保存失败");
        }
        invokeCreateOrders(orders);
        CreateOrderResponse createOrderResponse = new CreateOrderResponse();
        createOrderResponse.setGoodsOrdersId(goodsOrdersId);
        createOrderResponse.setPayAmount(FormatUtil.intShrink100ToStr(orders.getPayAmount()));
        response.setData(createOrderResponse);
        response.succeed("处理成功");
        return response;
    }

    private int saveToDataBase(int getChannel, PostAddress address, GoodsOrders orders, List<GoodsOrdersDetail> detailList) {
        try {
            if (getChannel == GetChannelEnum.MAIL.getValue()) {
                postAddressRepository.save(address);
            }
            goodsOrdersRepository.save(orders);
            goodsOrdersDetailRepository.saveAll(detailList);
        } catch (Exception e) {
            logger.error("#MgGoodsOrdersService#saveToDataBase:{},{}", e.getMessage(), e);
            return -1;
        }
        return 0;
    }

    private List<Goods> getGoodsListByGoodsDTOList(List<GoodsDTO> goodsList) {
        List<Integer> goodsIds = goodsList.stream().map(GoodsDTO::getGoodsId).collect(Collectors.toList());
        return getGoodsListByGoodsIds(goodsIds);
    }

    public List<Goods> getGoodsListByGoodsIds(List<Integer> goodsIds) {
        goodsIds = goodsIds.stream().filter(p -> !Checker.isNone(p) && p.intValue() > 0).collect(Collectors.toList());
        int size = goodsIds.size();
        if (!Checker.isNone(goodsIds)) {
            StringBuilder sqlBuilder = new StringBuilder("select * from  goods where deleted = 0 and ( ");
            for (int i = 0, j = goodsIds.size(); i < j; i++) {
                if (i == 0) {
                    sqlBuilder.append(" id = ");
                } else {
                    sqlBuilder.append(" or id =  ");
                }
                sqlBuilder.append(goodsIds.get(i));
            }
            sqlBuilder.append(" ) limit ").append(size);
            return glassesJdbcTemplate.query(sqlBuilder.toString(), new BeanPropertyRowMapper<>(Goods.class));
        }
        return null;
    }


    private void invokeCreateOrders(GoodsOrders orders) {
       com.ywt.gapi.ordercenter.CreateOrderResponse response = orderCenterService.createOrder(OrderTypeEnum.GLASSES.getValue(),
                orders.getId(),
                "",
                "rest://com.ywt.GlassesApiService/mg/order/paymentCallback",
                ConstantDef.GLASSES_PAY_CODE,
                orders.getPayAmount(),
                ConstantDef.GLASSES_PAY_BODY);
        if (response != null && response.getCode() == BaseResponse.SUCCEED) {
            //保存订单号、订单Id
            orders.setOrderId(response.getOrderId());
            orders.setOrderNo(response.getOrderNo());
            goodsOrdersRepository.save(orders);
        }
    }

    public BaseResponse paymentCallback(PaymentCallbackRequest request) {
        logger.info("On callback, request = {}", JsonSerializer.toJson(request));
        try {
            int bizId = Checker.getIntegerValue(request.getBizId());
            if (bizId <= 0) {
                logger.warn("MgGoodsOrdersService#paymentCallback(): bizId is less than 1.");
                return new BaseResponse().failedWithParameterError("bizId <= 0");
            }
            GoodsOrders orders = goodsOrdersRepository.findById(bizId);
            if (orders == null) {
                logger.warn("MgGoodsOrdersService#paymentCallback(id={}): No matched goodsOrders found!", bizId);
                return new BaseResponse().failedWithParameterError("找不到订单信息");
            }
            // 订单状态，防止重复调用
            if (orders.getStatus() != GoodsOrdersStatusEnum.PendingPayment.getValue()) {
                logger.warn("MgGoodsOrdersService#paymentCallback(id={}): 订单状态不正确!", bizId);
                return new BaseResponse().failedWithParameterError("订单状态不正确!");
            }

            orders.setStatus(GoodsOrdersStatusEnum.AlreadyPaid.getValue());
            orders.setPaymentStatus(PaymentStatusEnum.Success.getValue());
            orders.setPaymentTime(new Date());
            orders.setPaymentNo(request.getPaymentNo());
            orders.setPaymentChannel(request.getPaymentChannel());
            // 减去商品数量
            List<Goods> goods = new ArrayList<>();
            List<GoodsOrdersDetail> ordersDetailList = goodsOrdersDetailRepository.findByGoodsOrdersId(bizId);
            List<Integer> goodsIds = ordersDetailList.stream().map(GoodsOrdersDetail::getGoodsId).collect(Collectors.toList());
            List<Goods> goodsList = getGoodsListByGoodsIds(goodsIds);
            for (GoodsOrdersDetail detail : ordersDetailList) {
                if (!Checker.isNone(goodsList)) {
                    Goods gd = goodsList.stream().filter(p -> p.getId().equals(detail.getGoodsId())).findFirst().orElse(null);
                    if (!Checker.isNone(gd)) {
                        gd.setInventory(gd.getInventory() - detail.getGoodsNumber());
                        goods.add(gd);
                    }
                }
            }
            // 保存
            goodsOrdersRepository.save(orders);
            if (!Checker.isNone(goods)) {
                goodsRepository.saveAll(goods);
            }
            // 发消息通知
            sendPaySucessfulMessage(orders, goods);
        } catch (Exception e) {
            logger.error("MgGoodsOrdersService#paymentCallback(request={} ):\n {}", JsonSerializer.toJson(request), e.getMessage(), e);
            return new BaseResponse().failedWithAppError(e.getMessage());
        }
        return new BaseResponse().succeed();
    }


    private void sendPaySucessfulMessage(GoodsOrders orders, List<Goods> goodsList) {
        if (orders == null || Checker.isNone(goodsList)) {
            logger.warn("MgGoodsOrdersService#sendPaySucessfulMessage(): goodsOrders 不能为空!");
            return;
        }
        try {
            // 发送消息给用户
            // 白云
            int terminal2 = TerminalEnum.NFYYBYFY_WXAPP.getValue();
            //接收者（用户）的 openid
            SnsUserInfo snsUserInfo = snsUserInfoRepository.getSnsUserInfoByUserId(orders.getUserId(), terminal2);
            String openId2 = !Checker.isNone(snsUserInfo) ? snsUserInfo.getOpenId() : "";
            //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转
            String page = String.format(ConstantDef.NFYYBYFY_GOODS_ORDERS_DETAIL_URL, orders.getOrderId());
            Map<String, String> keywordMap = new HashMap<>();
            keywordMap.put("phrase1", "视光中心");
            keywordMap.put("character_string2", orders.getPaymentNo());
            int totalFee = Checker.getIntegerValue(orders.getPayAmount());
            keywordMap.put("amount3", String.format("%.2f元", totalFee / 100d));
            keywordMap.put("date4", DateUtil.convertToString(new Date()));
            // 目前只有白云医院，如果后续需要做兼容，可以针对医院单独做处理
            int hospitalId = orders.getHospitalId();
            weChatMessageService.sendMPSubscribeMessage(terminal2, openId2, ConstantDef.TPL_ID_NFYYBYFY_GLASSES_PAY_SUCCESS, page, keywordMap);
        } catch (Exception e) {
            logger.error("MgGoodsOrdersService#sendPaySucessfulMessage(goodsOrdersId={}): Notify new order failed! {}", orders.getId(), e.getMessage(), e);
        }
    }

    public BaseResponse confirmPayment(ConfirmPaymentRequest request) {
        BaseResponse baseResponse = new BaseResponse();
        int goodsOrdersId = request.getGoodsOrdersId();
        GoodsOrders orders = goodsOrdersRepository.getOne(goodsOrdersId);
        if (orders == null) {
            logger.warn("MgGoodsOrdersService#confirmPayment(id={}): No matched goodsOrders found!", goodsOrdersId);
            return baseResponse.failedWithParameterError("找不到订单信息");
        }
        // 判断状态是否OK
        if (orders.getStatus() != GoodsOrdersStatusEnum.PendingPayment.getValue()) {
            logger.warn("MgGoodsOrdersService#confirmPayment(id={}): 订单状态不正确!", goodsOrdersId);
            return baseResponse.failedWithParameterError("订单状态不正确!");
        }
        // 需要判断是否有足够的库存
        List<GoodsOrdersDetail> ordersDetailList = goodsOrdersDetailRepository.findByGoodsOrdersId(goodsOrdersId);
        List<Integer> goodsIds = ordersDetailList.stream().map(GoodsOrdersDetail::getGoodsId).collect(Collectors.toList());
        List<Goods> goodsList = getGoodsListByGoodsIds(goodsIds);
        for (GoodsOrdersDetail detail : ordersDetailList) {
            Goods goods = goodsList.stream().filter(p -> p.getId().equals(detail.getGoodsId())).findFirst().orElse(null);
            if (!Checker.isNone(goods)) {
                if (goods.getInventory() - detail.getGoodsNumber() < 0) {
                    return baseResponse.failedWithParameterError(goods.getName() + "库存不足");
                }
            }
        }

        int payAmountInt = Checker.getIntegerValue(orders.getPayAmount());

        com.ywt.gapi.ordercenter.PayByAdminResponse payByAdminResponse = orderCenterService.payByAdmin(payAmountInt,
                userService.getCurrentAdminAcount(),
                PaymentChannelEnum.Cash.getValue(),
                orders.getOrderId(),
                "");
        if (payByAdminResponse.getCode() != ResultCode.SUCCEED.getNumber()) {
            return baseResponse.failedWithAppError(payByAdminResponse.getInfo());
        }
        return baseResponse.succeed();
    }

    public BaseResponse refundOrder(RefundOrderRequest request) {
        BaseResponse baseResponse = new BaseResponse();
        int goodsOrdersId = request.getGoodsOrdersId();
        String remark = request.getRemark();

        GoodsOrders orders = goodsOrdersRepository.getOne(goodsOrdersId);
        if (orders == null) {
            logger.warn("MgGoodsOrdersService#refundOrder(id={}): No matched goodsOrders found!", goodsOrdersId);
            return baseResponse.failedWithParameterError("找不到订单信息");
        }
        // 判断状态是否OK
        if (orders.getStatus() != GoodsOrdersStatusEnum.AlreadyPaid.getValue()) {
            logger.warn("MgGoodsOrdersService#refundOrder(id={}): 订单状态不正确!", goodsOrdersId);
            return baseResponse.failedWithParameterError("订单状态不正确!");
        }
        int orderId = orders.getOrderId();

        /**
         * 退款
         *message RefundRequest {
         *    string orderNo = 1;          //订单号
         *    int32 orderId = 2;          //订单号
         *    int32 amount = 3;           //退款金额(单位：分), 当为0时，默认该订单总金额
         *    string opBy = 4;            //操作人, 当人工退款方式时必填
         *    int32 refundType = 5;       //退款方式，1: 人工, 2: 系统
         *    string refundNotifyMethod = 6; //退款成功后回调grpc方法，结构：(/${package}.${service}/${method})，如：/com.ywt.gapi.mq.MQExecutorService/executeGRPC
         *    string refundNotifyRestUrl = 7; //退款成功后回调rest服务方法，url格式: rest://com.ywt.MgDrugApiService/path1/path2
         *    string remark = 8;
         *    string custom = 9;          //本次操作自定义数据，【订单退款成功通知】会通过 custom 回发
         * }
         * @return
         */
        Map<String, Object> customMap = new HashMap<>();
        customMap.put("goodsOrdersId", goodsOrdersId);
        customMap.put("orderId", orderId);
        String adminAccount = userService.getCurrentAdminAcount();

        // 需要做加锁处理，防止重复点击
        String sql = "update goods_orders set refund_status = ? where id = ? and refund_status is null;";
        Object[] args = new Object[]{RefundStatusEnum.PENDING.getValue(), goodsOrdersId};
        int[] types = new int[]{Types.INTEGER, Types.INTEGER};
        int count = glassesJdbcTemplate.update(sql, args, types);
        if (count > 0) {
            RefundResponse refundResponse = orderCenterService.refund(orderId,
                    orders.getOrderNo(),
                    adminAccount,
                    JsonSerializer.toJson(customMap),
                    "",
                    "rest://com.ywt.GlassesApiService/mg/order/refundCallback");

            if (refundResponse.getCode() == ResultCode.SUCCEED.getNumber()) {
                sql = "update goods_orders set refund_no = ?, refund_remark = ?, refund_op_by = ? where id = ?;";
                args = new Object[]{refundResponse.getRefundNo(), remark, adminAccount, goodsOrdersId};
                types = new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.INTEGER};
                glassesJdbcTemplate.update(sql, args, types);
                return baseResponse.succeed("退款成功");
            } else {
                sql = "update goods_orders set refund_status = null where id = ?;";
                args = new Object[]{goodsOrdersId};
                types = new int[]{Types.INTEGER};
                glassesJdbcTemplate.update(sql, args, types);
                return baseResponse.failed(BaseResponse.PARAMETER_ERROR, refundResponse.getInfo());
            }
        }
        return baseResponse.succeed("正在退款中");
    }

    public BaseResponse refundCallback(RefundCallbackRequest request) {
        logger.info("MgGoodsOrdersService#refundCallback(): {}", JsonSerializer.toJson(request));
        try {
            int bizId = Checker.getIntegerValue(request.getBizId());
            int refundStatus = Checker.getIntegerValue(request.getRefundStatus());
            String refundNo = Checker.getStringValue(request.getRefundNo());
            String custom = Checker.getStringValue(request.getCustom());
            String sql =
                    "update goods_orders set " +
                            "refund_status = ?, " +
                            "status = ?, " +
                            "refund_time = now() " +
                            "where refund_no = ? and refund_status = ?;";
            Object[] args = new Object[]{
                    refundStatus,
                    GoodsOrdersStatusEnum.Refunded.getValue(),
                    refundNo,
                    RefundStatusEnum.PENDING.getValue()
            };
            int[] types = new int[]{
                    Types.INTEGER,
                    Types.INTEGER,
                    Types.VARCHAR,
                    Types.INTEGER
            };
            int count = glassesJdbcTemplate.update(sql, args, types);
            if (count > 0) {
                // 处理商品数量
                updateGoodsInventory(bizId);
                return new BaseResponse().succeed("处理成功");
            } else {
                return new BaseResponse().failedWithParameterError("流水号不存在或重复回调");
            }
        } catch (Exception e) {
            logger.error("MgGoodsOrdersService#refundCallback(): {}", e.getMessage(), e);
            return new BaseResponse().failedWithAppError();
        }
    }

    private void updateGoodsInventory(int bizId) {
        // 退款后，恢复商品数量
        List<Goods> goods = new ArrayList<>();
        List<GoodsOrdersDetail> ordersDetailList = goodsOrdersDetailRepository.findByGoodsOrdersId(bizId);
        List<Integer> goodsIds = ordersDetailList.stream().map(GoodsOrdersDetail::getGoodsId).collect(Collectors.toList());
        List<Goods> goodsList = getGoodsListByGoodsIds(goodsIds);
        for (GoodsOrdersDetail detail : ordersDetailList) {
            if (!Checker.isNone(goodsList)) {
                Goods gd = goodsList.stream().filter(p -> p.getId().equals(detail.getGoodsId())).findFirst().orElse(null);
                if (!Checker.isNone(gd)) {
                    gd.setInventory(gd.getInventory() + detail.getGoodsNumber());
                    goods.add(gd);
                }
            }
        }
        if (!Checker.isNone(goods)) {
            goodsRepository.saveAll(goods);
        }
    }

    public BaseResponse addOrUpdateGetChannel(addOrUpdateGetChannelRequest request) {
        BaseResponse response = new BaseResponse();
        int goodsOrdersId = request.getGoodsOrdersId();
        if (goodsOrdersId <= 0) {
            return response.failedWithParameterError("订单ID有误");
        }
        GoodsOrders goodsOrders = goodsOrdersRepository.findById(goodsOrdersId);
        if (Checker.isNone(goodsOrders)) {
            return response.failedWithParameterError("该订单不存在");
        }
        int getChannel = request.getGetChannel();
        if (getChannel == 1) {
            String postMobile = request.getMobile();
            String postName = request.getName();
            String postProvince = request.getProvince();
            String postCity = request.getCity();
            String postArea = request.getArea();
            String postAddress = request.getAddress();
            if ((Checker.isNone(postMobile) || Checker.isNone(postName) || Checker.isNone(postProvince)
                    || Checker.isNone(postCity) || Checker.isNone(postAddress))) {
                // 非台湾地区一定要精确到区
                if (Checker.isNone(postArea) && !"台湾省".equals(postProvince)) {
                    return response.failedWithParameterError("请先填写好邮寄地址");
                }
            } else {
                PostAddress address = new PostAddress();
                int addressId = glassesIdGenerator.genPostAddressId();
                address.setId(addressId);
                address.setMobile(request.getMobile());
                address.setName(request.getName());
                address.setAddressIds(request.getAddressIds());
                address.setProvince(request.getProvince());
                address.setCity(request.getCity());
                address.setArea(request.getArea());
                address.setAddress(request.getAddress());
                address.setDeleted(0);
                address.setCreatTime(new Date());
                address.setUpdateTime(new Date());

                goodsOrders.setAddressId(addressId);
                goodsOrders.setGetChannel(getChannel);
                postAddressRepository.save(address);
                goodsOrdersRepository.save(goodsOrders);

            }
        } else {
            goodsOrders.setGetChannel(getChannel);
            goodsOrders.setAddressId(0);
            goodsOrdersRepository.save(goodsOrders);
        }
        return response.succeed("处理成功");
    }

}
