package com.izouma.awesomeadmin.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.izouma.awesomeadmin.dao.AlipayTempMapper;
import com.izouma.awesomeadmin.dao.NavigationPackageMapper;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.model.*;
import com.izouma.awesomeadmin.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.dao.UserOrderMapper;

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

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

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private NavigationPackageMapper navigationPackageMapper;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MemberPointService memberPointService;

    @Autowired
    private MemberCoinService memberCoinService;

    @Autowired
    private MarketCodeService marketCodeService;


    @Autowired
    private AlipayTempMapper alipayTempMapper;

    @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 Result createUserOrder(UserOrder record) {

        logger.info("createUserOrder");
        try {

            if (record.getUserId() != null && record.getPackageId() != null) {//用户和导游包都必须存在

                NavigationPackage navigationPackage = navigationPackageMapper.selectByPrimaryKey(record.getPackageId());

                if (navigationPackage == null || !"Y".equals(navigationPackage.getShelfFlag())) {
                    return new Result(false, "导游包未上线或不存在");
                }

                record.setLankMarkId(navigationPackage.getLandMarkId());

                BigDecimal totlePrice = navigationPackage.getPrice();
                record.setTotlePrice(totlePrice);
                BigDecimal dealPrice = totlePrice;

                //推广码进行折扣或减价
                if (StringUtils.isNotEmpty(record.getMarketCode())) {
                    MarketCode marketCode = new MarketCode();
                    marketCode.setCode(record.getMarketCode());
                    marketCode = marketCodeService.getMarketCode(marketCode);
                    if (marketCode == null) {
                        return new Result(false, "推广码不存在");
                    }

                    if (marketCode.getMarketType() == null) {
                        return new Result(false, "推广码无效");
                    }

                    MarketType marketType = marketCode.getMarketType();

                    if (AppConstant.MarketType.REDUCTION == marketType.getTypeFlag()) { //减免

                        dealPrice = totlePrice.subtract(marketType.getMoney());

                    } else if (AppConstant.MarketType.DISCOUNT == marketType.getTypeFlag()) {//折扣
                        dealPrice = totlePrice.multiply(marketType.getMoney().divide(BigDecimal.valueOf(100)));
                    }


                }

                record.setDealPrice(dealPrice);


                int updates = userOrderMapper.insertSelective(record);

                if (updates > 0) {
                    return new Result(true, record.getId());
                }
            }


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

        return new Result(false, "下单失败");
    }

    @Override
    public boolean deleteUserOrder(UserOrder record) {

        logger.info("deleteUserOrder");
        try {

            int updates = userOrderMapper.delete(record);

            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 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(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.getId());
                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.getId());
                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, "支付失败");
    }


    /**
     * <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);
        }

    }


}

