package com.izouma.awesomeadmin.service.impl;

import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dao.*;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.dto.WxPayRefundData;
import com.izouma.awesomeadmin.model.*;
import com.izouma.awesomeadmin.service.MemberCoinService;
import com.izouma.awesomeadmin.service.MemberPointService;
import com.izouma.awesomeadmin.service.UserInfoService;
import com.izouma.awesomeadmin.service.UserOrderService;
import com.izouma.awesomeadmin.util.AlipayClientFactory;
import com.izouma.awesomeadmin.util.MbappUtil;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import com.izouma.awesomeadmin.util.WXRefundService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * service接口实现类
 */
@Service
public class UserOrderServiceImpl implements UserOrderService {

    private static Logger logger = Logger.getLogger(UserOrderServiceImpl.class);

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WxpayTempMapper wxpayTempMapper;

    @Autowired
    private MemberPointService memberPointService;

    @Autowired
    private MemberCoinService memberCoinService;

    @Autowired
    private AlipayTempMapper alipayTempMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private SystemConfigMapper systemConfigMapper;

    @Autowired
    private OrderRepairMapper orderRepairMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;


    @Override
    public List<UserOrder> getUserOrderList(UserOrder record) {

        logger.info("getUserOrderList");
        try {

            return userOrderMapper.queryAllUserOrder(record);
        } catch (Exception e) {
            logger.error("getUserOrderList", e);
        }

        return null;
    }

    @Override
    public List<UserOrder> getUserOrderByPage(Page page, UserOrder record) {

        logger.info("getUserOrderByPage");
        try {

            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("record", record);
            parameter.put(AppConstant.PAGE, page);

            return userOrderMapper.queryUserOrderByPage(parameter);
        } catch (Exception e) {
            logger.error("getUserOrderByPage", e);
        }

        return null;
    }

    @Override
    public UserOrder getUserOrderById(String id) {

        logger.info("getUserOrderyId");
        try {

            return userOrderMapper.selectByPrimaryKey(Integer.valueOf(id));
        } catch (Exception e) {
            logger.error("getUserOrderById", e);
        }

        return null;
    }

    @Override
    public UserOrder getUserOrder(UserOrder record) {

        logger.info("getUserOrder");
        try {

            return userOrderMapper.queryUserOrder(record);
        } catch (Exception e) {
            logger.error("getUserOrder", e);
        }

        return null;
    }

    @Override
    public boolean createUserOrder(UserOrder record) {

        logger.info("createUserOrder");
        try {
            record.setOrderCode(MbappUtil.getOrderIdByUUId());
            if (record.getQuantity() != null && record.getUnitPrice() != null) {
                BigDecimal unitPrice = record.getUnitPrice();

                /**
                 * 计算价格开始
                 */
                ProductInfo productInfo = new ProductInfo();
                productInfo.setId(record.getProductId());

                productInfo = productInfoMapper.queryProductInfo(productInfo);

                if (productInfo != null) {
                    unitPrice = productInfo.getPrice();

                    if (productInfo.getProductPriceList() != null && productInfo.getProductPriceList().size() > 0) {
                        for (ProductPrice productPrice : productInfo.getProductPriceList()) {
                            if (productPrice.getMaxCounts() != null
                                    && productPrice.getMinCounts() != null
                                    && record.getQuantity() <= productPrice.getMaxCounts()
                                    && record.getQuantity() >= productPrice.getMinCounts()) {
                                unitPrice = productPrice.getPrice();
                            } else if (productPrice.getMaxCounts() == null
                                    && productPrice.getMinCounts() != null
                                    && record.getQuantity() >= productPrice.getMinCounts()) {
                                unitPrice = productPrice.getPrice();
                            } else if (productPrice.getMinCounts() == null
                                    && productPrice.getMaxCounts() != null
                                    && record.getQuantity() <= productPrice.getMaxCounts()) {
                                unitPrice = productPrice.getPrice();
                            }
                        }
                    }

                }
                /**
                 * 计算价格结束
                 */

                BigDecimal totlePrice = unitPrice.multiply(BigDecimal.valueOf(record.getQuantity()));
                record.setTotlePrice(totlePrice);
                BigDecimal dealPrice = totlePrice;
                record.setDealPrice(dealPrice);
                record.setOffPrice(totlePrice.subtract(dealPrice));


                int updates = userOrderMapper.insertSelective(record);


                if (StringUtils.isNotEmpty(record.getUserAddressId())) {
                    UserAddress userAddress = userAddressMapper.selectByPrimaryKey(Integer.valueOf(record.getUserAddressId()));

                    if (userAddress != null) {
                        OrderAddress orderAddress = new OrderAddress();

                        orderAddress.setOrderId(record.getId());
                        orderAddress.setUserId(record.getUserId());
                        orderAddress.setRealName(userAddress.getRealName());
                        orderAddress.setTelephone(userAddress.getTelephone());
                        orderAddress.setPostcode(userAddress.getPostcode());
                        orderAddress.setAddress(userAddress.getAddress());
                        orderAddress.setAddressDetail(userAddress.getAddressDetail());
                        orderAddress.setUserAddressId(record.getUserAddressId());

                        orderAddressMapper.insertSelective(orderAddress);


                    }

                }

                //购买减库存。
                if (productInfo != null) {
                    ProductInfo updateProduct = new ProductInfo();

                    updateProduct.setId(productInfo.getId());
                    updateProduct.setInventory(productInfo.getInventory() - record.getQuantity());
                    updateProduct.setSalesVolume(productInfo.getSalesVolume() + record.getQuantity());
                    productInfoMapper.updateByPrimaryKeySelective(updateProduct);
                }


                if (updates > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            logger.error("createUserOrder", e);
        }

        return false;
    }

    @Override
    public boolean deleteUserOrder(String id) {

        logger.info("deleteUserOrder");
        try {

            int updates = userOrderMapper.delete(id);

            if (updates > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("deleteUserOrder", e);
        }

        return false;
    }

    @Override
    public boolean updateUserOrder(UserOrder record) {

        logger.info("updateUserOrder");
        try {

            int updates = userOrderMapper.updateByPrimaryKeySelective(record);

            if (updates > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("updateUserOrder", e);
        }

        return false;
    }


    @Override
    public Result payOrder(String orderId, double coin, double point, double cash, int payMode) {

        logger.info("payOrder：支付订单");
        try {

            UserOrder userOrder = new UserOrder();

            userOrder.setId(Integer.valueOf(orderId));

            userOrder = userOrderMapper.queryUserOrder(userOrder);

            if (userOrder == null) {
                return new Result(false, "支付失败，订单不存在");
            }

            double money = userOrder.getDealPrice().doubleValue();

            if (AppConstant.PayMode.COIN == payMode) {
                //如果支付总额不足则用余额补足；
                if (money > (coin + point + cash)) {
                    coin = money - point - cash;
                }
            }


            UserInfo userInfo = userInfoService.getUserInfoById(userOrder.getUserId() + "");

            if (userInfo == null) {
                return new Result(false, "支付失败，用户不存在！");
            }

            /**
             * 余额
             */
            double moneyCoin = userInfo.getMoneyCoin();
            if (coin > moneyCoin) {
                return new Result(false, "支付失败，余额不足");
            }

            /**
             * 商城积分
             */
            double moneyPoint = userInfo.getMoneyPoint();
            if (point > moneyPoint) {
                return new Result(false, "支付失败，商城积分不足");
            }


            if (money > (coin + point + cash)) {
                return new Result(false, "支付失败，金额不足");
            }

            if (point > 0) {
                //积分兑换区 只能用商城积分
                MemberPoint memberPoint = new MemberPoint();
                memberPoint.setCreateUser("系统");
                memberPoint.setOrderId(orderId);
                memberPoint.setUserId(userOrder.getUserId() + "");
                memberPoint.setMoney(String.valueOf(-point + 0.0));
                memberPoint.setBalance(String.valueOf(moneyPoint - point));
                memberPoint.setTypeFlag(AppConstant.CoinType.CONSUMPTION);
                memberPoint.setRemark("购买商品消费，订单号：" + userOrder.getOrderCode());
                memberPointService.createMemberPoint(memberPoint);


            }


            // 个人店铺，只能用余额支付
            if (coin > 0) {

                MemberCoin memberCoin = new MemberCoin();
                memberCoin.setCreateUser("系统");
                memberCoin.setOrderId(orderId);
                memberCoin.setUserId(userOrder.getUserId() + "");
                memberCoin.setMoney(String.valueOf(-coin + 0.0));
                memberCoin.setBalance(String.valueOf(moneyCoin - coin));
                memberCoin.setTypeFlag(AppConstant.CoinType.CONSUMPTION);
                memberCoin.setRemark("购买积分商品消费，订单号：" + userOrder.getOrderCode());
                memberCoinService.createMemberCoin(memberCoin);

            }


            UserInfo updateUser = new UserInfo();
            updateUser.setId(userOrder.getUserId());
            updateUser.setMoneyCoin(moneyCoin - coin);
            updateUser.setMoneyPoint(moneyPoint - point);
            userInfoService.updateUserInfo(updateUser);

            //更新为已经支付
            UserOrder userOrderPay = new UserOrder();

            userOrderPay.setId(Integer.valueOf(orderId));
            userOrderPay.setCoin(BigDecimal.valueOf(coin));
            userOrderPay.setPoint(BigDecimal.valueOf(point));
            userOrderPay.setCash(BigDecimal.valueOf(cash));
            userOrderPay.setPayMode(payMode);
            userOrderPay.setPayTime(new Date());
            userOrderPay.setStatusFlag(AppConstant.OrderStatus.PAY_OVER);

            userOrderMapper.updateByPrimaryKeySelective(userOrderPay);

            return new Result(true, "支付成功");
        } catch (Exception e) {
            logger.error("payOrder：支付订单异常", e);
        }
        return new Result(false, "支付失败");
    }

    @Override
    public double calculatedPrice(String orderId, double coin, double point) {

        logger.info("calculatedPrice：计算价格");
        try {

            UserOrder userOrder = new UserOrder();

            userOrder.setId(Integer.valueOf(orderId));

            userOrder = userOrderMapper.queryUserOrder(userOrder);

            double money = userOrder.getDealPrice().doubleValue();

            double cash = money - coin - point;

            return cash;

        } catch (Exception e) {
            logger.error("calculatedPrice：计算价格异常", e);
        }
        return 0;
    }


    @Override
    public Result payOrder(HttpServletRequest request, HttpServletResponse response) {

        logger.info("payOrder：支付订单");
        try {

            System.out.print("微信支付回调数据开始");
            String inputLine;
            String notityXml = "";
            String resXml = "";

            try {
                while ((inputLine = request.getReader().readLine()) != null) {
                    notityXml += inputLine;
                }
                request.getReader().close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("接收到的报文：" + notityXml);

            Map m = parseXmlToList2(notityXml);

            if ("SUCCESS".equals(m.get("result_code").toString())) {
                //支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                String attach = m.get("attach").toString();
                JSONObject attachJson = new JSONObject(attach);

                payOrder(attachJson.getString("orderId"), attachJson.getDouble("coin"),
                        attachJson.getDouble("point"), attachJson.getDouble("cash"), AppConstant.PayMode.WEI_XIN);

                WxpayTemp wxpayTemp = new WxpayTemp();

                wxpayTemp.setOrderId(attachJson.getString("orderId"));
                wxpayTemp.setCoin(BigDecimal.valueOf(attachJson.getDouble("coin")));
                wxpayTemp.setPoint(BigDecimal.valueOf(attachJson.getDouble("point")));
                wxpayTemp.setCash(BigDecimal.valueOf(attachJson.getDouble("cash")));
                wxpayTemp.setTotalAmount(BigDecimal.valueOf(attachJson.getInt("total") / 100.0));
                wxpayTemp.setOutTradeNo(m.get("out_trade_no").toString());
                wxpayTemp.setTransactionId(m.get("transaction_id").toString());
                wxpayTemp.setTypeFlag(AppConstant.Aliapi.BUY);

                wxpayTempMapper.insertSelective(wxpayTemp);

            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            System.out.println("微信支付回调数据结束");

            HttpSession seesion = request.getSession();
            seesion.setAttribute("notify", "微信支付回调");
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (Exception e) {
            logger.error("payOrder：支付订单异常", e);
        }
        return new Result(false, "支付失败");
    }

    @Override
    public Result recharge(HttpServletRequest request, HttpServletResponse response) {

        logger.info("recharge：支付充值");
        try {

            System.out.print("微信支付回调数据开始 支付充值");
            String inputLine;
            String notityXml = "";
            String resXml = "";

            try {
                while ((inputLine = request.getReader().readLine()) != null) {
                    notityXml += inputLine;
                }
                request.getReader().close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("接收到的报文：" + notityXml);

            Map m = parseXmlToList2(notityXml);

            if ("SUCCESS".equals(m.get("result_code").toString())) {
                //支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                String attach = m.get("attach").toString();
                JSONObject attachJson = new JSONObject(attach);

                Integer userId = attachJson.getInt("userId");
                Integer money = attachJson.getInt("money") / 100;

                UserInfo userInfo = userInfoService.getUserInfoById(userId + "");


                /**
                 * 余额
                 */
                double moneyCoin = userInfo.getMoneyCoin();
                UserInfo updateUser = new UserInfo();
                updateUser.setId(userId);
                updateUser.setMoneyCoin(moneyCoin + money);
                userInfoService.updateUserInfo(updateUser);


                MemberCoin memberCoin = new MemberCoin();
                memberCoin.setCreateUser("微信充值");
                memberCoin.setUserId(userId + "");
                memberCoin.setMoney(String.valueOf(money));
                memberCoin.setBalance(String.valueOf(moneyCoin + money));
                memberCoin.setTypeFlag(AppConstant.CoinType.RECHARGE);
                memberCoin.setRemark("微信充值，" + money);
                memberCoinService.createMemberCoin(memberCoin);


                WxpayTemp wxpayTemp = new WxpayTemp();

                wxpayTemp.setUserId(String.valueOf(userId));
                wxpayTemp.setOutTradeNo(m.get("out_trade_no").toString());
                wxpayTemp.setTransactionId(m.get("transaction_id").toString());
                wxpayTemp.setTotalAmount(BigDecimal.valueOf(money));
                wxpayTemp.setTypeFlag(AppConstant.Aliapi.RECHARGE);

                wxpayTempMapper.insertSelective(wxpayTemp);

            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            System.out.println("微信支付回调数据结束");

            HttpSession seesion = request.getSession();
            seesion.setAttribute("notify", "微信支付回调");
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (Exception e) {
            logger.error("payOrder：支付订单异常", e);
        }
        return new Result(false, "支付失败");
    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map parseXmlToList2(String xml) {

        Map retMap = new HashMap();
        try {
            StringReader read = new StringReader(xml);
            // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
            InputSource source = new InputSource(read);
            // 创建一个新的SAXBuilder
            SAXBuilder sb = new SAXBuilder();
            // 通过输入源构造一个Document
            org.jdom.Document doc = sb.build(source);
            Element root = (Element) doc.getRootElement();// 指向根节点
            List<Element> es = root.getChildren();
            if (es != null && es.size() != 0) {
                for (Element element : es) {
                    retMap.put(element.getName(), element.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }


    /**
     * <p>支付宝支付成功回调接口。</p>
     *
     * @param tradeNo
     * @param tradeStatus
     */
    @Override
    public void alipaySuccess(String tradeNo, String tradeStatus) {

        logger.info("alipaySuccess：支付宝支付成功回调接口 tradeNo：" + tradeNo + ", tradeStatus:" + tradeStatus);
        try {
            AlipayTemp alipayTemp = new AlipayTemp();
            alipayTemp.setOutTradeNo(tradeNo);
            alipayTemp = alipayTempMapper.queryAlipayTemp(alipayTemp);

            if (alipayTemp != null) {

                if (!AppConstant.Aliapi.TRADE_SUCCESS.equals(alipayTemp.getTradeStatus())) {

                    payOrder(alipayTemp.getOrderId() + "", alipayTemp.getCoin().doubleValue(),
                            alipayTemp.getPoint().doubleValue(), alipayTemp.getCash().doubleValue(), AppConstant.PayMode.ALIPAY);

                    alipayTemp.setTradeStatus(tradeStatus);

                    alipayTempMapper.updateByPrimaryKeySelective(alipayTemp);
                }

            }

        } catch (Exception e) {
            logger.error("alipaySuccess：支付宝支付成功回调接口异常 tradeNo：" + tradeNo + ", tradeStatus:" + tradeStatus, e);
        }

    }

    @Override
    public Result cancel(UserOrder record) {

        logger.info("cancel：取消订单");
        try {
            UserOrder userOrder = userOrderMapper.selectByPrimaryKey(record.getId());
            if (userOrder != null) {
                if (AppConstant.OrderStatus.NO_PAY == userOrder.getStatusFlag()) {

                    record.setStatusFlag(AppConstant.OrderStatus.CANCEL);
                    userOrderMapper.updateByPrimaryKeySelective(record);

                    /**
                     * 获取产品信息
                     */
                    ProductInfo productInfo = new ProductInfo();
                    productInfo.setId(userOrder.getProductId());

                    productInfo = productInfoMapper.queryProductInfo(productInfo);

                    //取消加库存库存。
                    if (productInfo != null) {
                        ProductInfo updateProduct = new ProductInfo();

                        updateProduct.setId(productInfo.getId());
                        updateProduct.setInventory(productInfo.getInventory() + userOrder.getQuantity());
                        productInfoMapper.updateByPrimaryKeySelective(updateProduct);
                    }

                }


            }

            return new Result(true, "cancel：取消订单成功");

        } catch (Exception e) {
            logger.error("cancel：取消订单异常", e);
        }
        return new Result(false, "cancel：取消订单失败");
    }

    @Override
    public Result confirm(UserOrder record) {

        logger.info("confirm：确认完成订单");
        try {
            UserOrder userOrder = userOrderMapper.selectByPrimaryKey(record.getId());
            if (userOrder != null) {

                boolean confirmFlag = false;

                if (AppConstant.ProductType.IMAGE.equals(userOrder.getProductType())
                        && AppConstant.OrderStatus.ACCEPT == userOrder.getStatusFlag()) {//修图完成
                    confirmFlag = true;
                    record.setStatusFlag(AppConstant.OrderStatus.FINISH);

                } else if (AppConstant.ProductType.PHYSICAL.equals(userOrder.getProductType())
                        && AppConstant.OrderStatus.WAIT_REPAIR == userOrder.getStatusFlag()) {//已发货
                    confirmFlag = true;
                    record.setStatusFlag(AppConstant.OrderStatus.FINISH);

                }

                if (confirmFlag) {

                    record.setConfirmTime(new Date());
                    userOrderMapper.updateByPrimaryKeySelective(record);

                    //结算商家
                    jieSuan(userOrder.getId() + "");

                    /**
                     * 获取产品信息
                     */
                    ProductInfo productInfo = new ProductInfo();
                    productInfo.setId(userOrder.getProductId());

                    productInfo = productInfoMapper.queryProductInfo(productInfo);

                    //取消加库存库存。
                    if (productInfo != null) {
                        ProductInfo updateProduct = new ProductInfo();

                        updateProduct.setId(productInfo.getId());
                        updateProduct.setInventory(productInfo.getInventory() + userOrder.getQuantity());
                        productInfoMapper.updateByPrimaryKeySelective(updateProduct);
                    }


                }


            }

            return new Result(true, "confirm：确认完成成功");

        } catch (Exception e) {
            logger.error("confirm：确认完成异常", e);
        }
        return new Result(false, "confirm：确认完成失败");
    }

    @Override
    public Result jieSuan(String orderId) {

        logger.info("jieSuan：结算订单");
        try {

            UserOrder userOrder = new UserOrder();

            userOrder.setId(Integer.valueOf(orderId));

            userOrder = userOrderMapper.queryUserOrder(userOrder);
            if (userOrder != null) {

                SystemConfig systemConfig = systemConfigMapper.selectByPrimaryKey(1);


                double money = userOrder.getDealPrice().doubleValue();


                UserInfo shangJiaUser = userInfoService.getUserInfoById(userOrder.getProductInfo().getStoreInfo().getUserId() + "");

                double shangJiaCoin = shangJiaUser.getMoneyCoin();
                double fee = 0;

                if ("Y".equals(systemConfig.getUseFlag())) {
                    fee = money * Double.valueOf(systemConfig.getOrderRate()) / 100.0;
                }

                //更新商家余额
                MemberCoin memberCoin = new MemberCoin();
                memberCoin.setCreateUser("系统");
                memberCoin.setUserId(shangJiaUser.getId() + "");
                memberCoin.setOrderId(orderId);
                memberCoin.setMoney(String.valueOf(money - fee));
                memberCoin.setBalance(String.valueOf(shangJiaCoin + money - fee));
                memberCoin.setTypeFlag(AppConstant.CoinType.SALE);
                memberCoin.setRemark("售卖商品获得" + money + "订单号：" + userOrder.getOrderCode() + ";服务费：" + fee);
                memberCoinService.createMemberCoin(memberCoin);


                UserInfo updateShangJia = new UserInfo();
                updateShangJia.setId(shangJiaUser.getId());
                updateShangJia.setMoneyCoin(shangJiaCoin + money - fee);
                userInfoService.updateUserInfo(updateShangJia);

            }

            return new Result(true, "jieSuan：结算订单成功");

        } catch (Exception e) {
            logger.error("jieSuan：结算订单异常", e);
        }
        return new Result(false, "jieSuan：结算订单失败");
    }


    @Override
    public Result refundFail(String orderId) {

        logger.info("refundFail：拒绝退款");
        try {

            UserOrder userOrder = userOrderMapper.selectByPrimaryKey(Integer.valueOf(orderId));
            if (userOrder != null) {

                if (AppConstant.OrderStatus.REFUNDING == userOrder.getStatusFlag()) {

                    UserOrder updateOrder = new UserOrder();
                    updateOrder.setId(userOrder.getId());
                    updateOrder.setStatusFlag(AppConstant.OrderStatus.REFUND_FAIL);
                    userOrderMapper.updateByPrimaryKeySelective(updateOrder);

                }
            }

            return new Result(true, "拒绝退款成功");

        } catch (Exception e) {
            logger.error("refundFail：拒绝退款异常", e);
        }
        return new Result(false, "拒绝退款失败");
    }


    @Override
    public Result refundOrder(String orderId) {

        logger.info("refundOrder：退款");
        try {

            UserOrder userOrder = userOrderMapper.selectByPrimaryKey(Integer.valueOf(orderId));
            if (userOrder != null) {

                if (AppConstant.OrderStatus.REFUNDING == userOrder.getStatusFlag()) {


                    double coin = userOrder.getCoin().doubleValue();

                    double point = userOrder.getPoint().doubleValue();

                    double cash = userOrder.getCash().doubleValue();

                    int payMode = userOrder.getPayMode();
                    UserInfo userInfo = userInfoService.getUserInfoById(userOrder.getUserId() + "");


                    /**
                     * 余额
                     */
                    double moneyCoin = userInfo.getMoneyCoin();

                    /**
                     * 商城积分
                     */
                    double moneyPoint = userInfo.getMoneyPoint();


                    if (coin > 0) {

                        MemberCoin memberCoin = new MemberCoin();
                        memberCoin.setCreateUser("系统");
                        memberCoin.setUserId(userInfo.getId() + "");
                        memberCoin.setOrderId(orderId);
                        memberCoin.setMoney(String.valueOf(coin + 0.0));
                        memberCoin.setBalance(String.valueOf(moneyCoin + coin));
                        memberCoin.setTypeFlag(AppConstant.CoinType.REFUND);
                        memberCoin.setRemark("退款，订单号：" + userOrder.getOrderCode());
                        memberCoinService.createMemberCoin(memberCoin);

                    }

                    if (point > 0) {
                        MemberPoint memberPoint = new MemberPoint();
                        memberPoint.setCreateUser("系统");
                        memberPoint.setOrderId(orderId);
                        memberPoint.setUserId(userInfo.getId() + "");
                        memberPoint.setMoney(String.valueOf(point + 0.0));
                        memberPoint.setBalance(String.valueOf(moneyPoint + point));
                        memberPoint.setTypeFlag(AppConstant.CoinType.REFUND);
                        memberPoint.setRemark("退款，订单号：" + userOrder.getOrderCode());
                        memberPointService.createMemberPoint(memberPoint);
                    }


                    if (cash > 0) {
                        if (AppConstant.PayMode.ALIPAY == payMode) {
                            AlipayTemp alipayTemp = new AlipayTemp();
                            alipayTemp.setTradeStatus(AppConstant.Aliapi.TRADE_SUCCESS);
                            alipayTemp.setOrderId(orderId);
                            alipayTemp.setTypeFlag(AppConstant.Aliapi.BUY);
                            alipayTemp = alipayTempMapper.queryAlipayTemp(alipayTemp);
                            if (alipayTemp != null) {

                                AlipayClientFactory.refund(alipayTemp.getOutTradeNo(), cash);
                            }
                        }

                        if (AppConstant.PayMode.WEI_XIN == payMode) {

                            WxpayTemp wxpayTemp = new WxpayTemp();
                            wxpayTemp.setOrderId(orderId);
                            wxpayTemp.setTypeFlag(AppConstant.Aliapi.BUY);
                            wxpayTemp = wxpayTempMapper.queryWxpayTemp(wxpayTemp);

                            if (wxpayTemp != null) {

                                String out_refund_no = MbappUtil.create_out_trade_no();
                                WxPayRefundData data = new WxPayRefundData();
                                data.setAppid(PropertiesFileLoader.getProperties("weixinappid"));
                                data.setMch_id(PropertiesFileLoader.getProperties("weixin_mch_id"));
                                data.setDevice_info(AppConstant.DEVICE_INFO);
                                data.setNonce_str(MbappUtil.create_nonce_str());
                                data.setOut_trade_no(wxpayTemp.getOutTradeNo());
                                data.setTransaction_id(wxpayTemp.getTransactionId());
                                data.setOut_refund_no(out_refund_no);
                                data.setTotal_fee((int) (cash * 100));
                                data.setRefund_fee((int) (cash * 100));
                                data.setOp_user_id(PropertiesFileLoader.getProperties("weixin_mch_id"));

                                WXRefundService.refund(data, "UTF-8", PropertiesFileLoader.getProperties("weixin_cert_path"), PropertiesFileLoader.getProperties("weixin_mch_id"));

                                wxpayTemp.setOutRefundNo(out_refund_no);

                                wxpayTempMapper.updateByPrimaryKeySelective(wxpayTemp);

                            }
                        }
                    }

                    UserInfo updateUser = new UserInfo();
                    updateUser.setId(userInfo.getId());
                    updateUser.setMoneyCoin(moneyCoin + coin);
                    updateUser.setMoneyPoint(moneyPoint + point);
                    userInfoService.updateUserInfo(updateUser);

                    UserOrder updateOrder = new UserOrder();
                    updateOrder.setId(userOrder.getId());
                    updateOrder.setStatusFlag(AppConstant.OrderStatus.REFUND_SUCCESS);


                    userOrderMapper.updateByPrimaryKeySelective(updateOrder);

                }
            }

            return new Result(true, "退款成功");

        } catch (Exception e) {
            logger.error("refundOrder：退款异常", e);
        }
        return new Result(false, "退款失败");
    }

    @Override
    public Result ziDong() {

        logger.info("ziDong：定时任务");
        try {

            //取消无效订单
            autoCancel();


            return new Result(true, "定时任务成功");

        } catch (Exception e) {
            logger.error("ziDong：定时任务异常", e);
        }
        return new Result(false, "定时任务失败");
    }

    @Override
    public Result autoCancel() {

        logger.info("autoCancel：取消无用订单");
        try {
            //获取待取消订单
            List<UserOrder> userOrders = userOrderMapper.getAutoCancel();

            for (UserOrder userOrder : userOrders) {

                UserOrder record = new UserOrder();
                record.setId(userOrder.getId());
                record.setCancelReason("30分钟未支付，系统自动取消！");
                cancel(record);
            }

            return new Result(true, "取消无用订单成功");

        } catch (Exception e) {
            logger.error("autoCancel：取消无用订单异常", e);
        }
        return new Result(false, "取消无用订单失败");
    }

    /**
     * 返修
     *
     * @param record
     * @return
     */
    @Override
    public boolean repair(UserOrder record) {

        logger.info("repair");
        try {
            int updates = userOrderMapper.updateByPrimaryKeySelective(record);

            OrderRepair orderRepair = new OrderRepair();
            orderRepair.setOrderId(record.getId() + "");
            orderRepairMapper.repairByOrderId(orderRepair);


            if (updates > 0) {
                return true;
            }

        } catch (Exception e) {
            logger.error("repair", e);
        }

        return false;
    }
}

