package com.pine.admin.modules.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pine.admin.aop.Operation;
import com.pine.admin.modules.business.dao.OfflinePaymentsDao;
import com.pine.admin.modules.business.entity.CarOrder;
import com.pine.admin.modules.business.entity.OfflinePayments;
import com.pine.admin.shiro.ShiroUtils;
import com.pine.common.exception.ApiException;
import com.pine.common.utils.Constant;
import com.pine.common.utils.PostUtil;
import com.pine.common.utils.RSAUtils;
import io.swagger.annotations.Api;
import javafx.geometry.Pos;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import com.pine.common.dto.Page;
import org.springframework.transaction.annotation.Transactional;

import com.pine.admin.modules.business.dao.CarOrderDao;
import com.pine.admin.modules.business.service.CarOrderService;
import springfox.documentation.spring.web.json.Json;


@Service("carOrderService")
@Slf4j
public class CarOrderServiceImpl implements CarOrderService {

    @Autowired
    private CarOrderDao carOrderDao;
    @Autowired
    private OfflinePaymentsDao offlinePaymentsDao;

    @Override
    @Transactional
    public List<CarOrder> getAllList(CarOrder record) {

        log.info("getCarOrderList");
        try {
            return carOrderDao.queryAll(record);
        } catch (Exception e) {
            log.error("getCarOrderList", e);
        }

        return null;
    }
    @Override
    public List<CarOrder> getBackByPage(Page page, CarOrder record) {
        log.info("getBackByPage");
        try {
            if (!ShiroUtils.getShiroUserInfo().getName().contains("商城管理员")) {
                record.setCarSupplier(ShiroUtils.getShiroUserInfo().getName());
            }
            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("record", record);
            parameter.put("page", page);

            return carOrderDao.queryBackByPage(parameter);

        }catch (Exception e){
            log.error("getBackByPage", e);

        }
        return null;
    }


    @Override
    @Transactional
    public List<CarOrder> getByPage(Page page, CarOrder record) {

        log.info("getCarOrderByPage");
        try {

            // 首付/尾款支付状态查询

            if (!ShiroUtils.getShiroUserInfo().getName().contains("商城管理员")) {
                record.setCarSupplier(ShiroUtils.getShiroUserInfo().getName());
            }
            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("record", record);
            parameter.put("page", page);
//            if (!StringUtils.isEmpty(record.getOfflinePayType())){
//                //如果不是查询在线支付的直接 走查询线下和未支付的接口
//                if (!record.getOfflinePayType().equals("2")){
//                    return carOrderDao.queryOfflineByPage(parameter);
//                }
//            }
            return carOrderDao.queryOfflineByPage(parameter);
        } catch (Exception e) {
            log.error("getCarOrderByPage", e);
        }

        return null;
    }

    @Override
    @Transactional
    public CarOrder getById(String id) {

        log.info("getCarOrderById");
        try {

            return carOrderDao.selectByPrimaryKey(Integer.valueOf(id));
        } catch (Exception e) {
            log.error("getCarOrderById", e);
        }

        return null;
    }

    @Override
    @Transactional
    public CarOrder getOne(CarOrder record) {

        log.info("getCarOrder");
        try {

            return carOrderDao.queryOne(record);
        } catch (Exception e) {
            log.error("getCarOrder", e);
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(CarOrder record) {

        log.info("createCarOrder");
        try {

            int updates = carOrderDao.insertSelective(record);

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

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String id) {

        log.info("deleteCarOrder");
        try {

            int updates = carOrderDao.delete(Integer.valueOf(id));

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

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deltetByIds(String ids) {

        log.info("deleteeCarOrder byIDS");
        try {

            String[] id = ids.split(";");
            int updates = carOrderDao.deleteIds(id);

            if (id.length == updates) {
                return true;
            }
        } catch (Exception e) {
            log.error("deleteeCarOrder byIDS", e);
        }

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(CarOrder record) {

        log.info("updateCarOrder");
        try {

            int updates = carOrderDao.updateByPrimaryKeySelective(record);

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

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Operation("线下审核")
    public boolean offlineReview(Long id, String loanStatus, BigDecimal downPaymentRate) {


        log.info("offlineReview");
        try {
            Map<String, String> map = new HashMap<>();

            if (!"5".equals(loanStatus)) {
                if (!"6".equals(loanStatus)) {
                    throw new ApiException("非法参数");
                }
            }

            CarOrder carOrder = new CarOrder();
            carOrder.setId(id);
            CarOrder carOrderLast = getCarOrder(id);
            carOrder.setLoanStatus(loanStatus);
            map.put("status", String.valueOf(0));
            DecimalFormat decimalFormat = new DecimalFormat("0.##");

            if ("5".equals(loanStatus)) {
                map.put("status", String.valueOf(1));
                if (null == downPaymentRate) {
                    throw new ApiException("请输入首付比例");
                }
                carOrder.setDownPaymentRate(downPaymentRate);
//                carOrder.setDownPaymentPrice();
                //计算首付金额
                BigDecimal downPaymentPrice = carOrderLast.getTotalPrice().multiply(downPaymentRate).subtract(carOrderLast.getDepositPrice());
                downPaymentPrice = new BigDecimal(decimalFormat.format(downPaymentPrice));
                carOrder.setDownPaymentPrice(downPaymentPrice);
            }
            carOrder.setOfflineAuditTime(new Date());
//            int updates = carOrderDao.updateByPrimaryKeySelective(carOrder);

            //消息通知
            map.put("orderId", String.valueOf(id));
            //传过来地20直接传
            map.put("ratio", decimalFormat.format(downPaymentRate));


            String s = JSONObject.toJSONString(map);

            String encrypt = RSAUtils.encrypt(RSAUtils.publicKey, s);

            Map<String, String> data = new HashMap<>();

            data.put("data", encrypt);


            String offlineaudit = PostUtil.httpPost(Constant.offlineaudit, data, "application/json");

            log.info(offlineaudit);
            Map maps = (Map) JSON.parse(offlineaudit);


            if (maps.get("code").equals("1")) {
                return true;
            } else {
                throw new ApiException(maps.get("msg").toString());
            }
        } catch (Exception e) {
            log.error("offlineReview", e);
            throw new ApiException(e.getMessage());

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Operation("交付")
    public boolean pay(Long id, String invoicePath) {
        log.info("pay");
        try {
            /**
             * 查询订单
             *
             */
            CarOrder carOrder = getCarOrder(id);

            carOrder.setStatus("3");

            carOrder.setOrderFinishTime(new Date());

            int c = carOrderDao.updateByPrimaryKeySelective(carOrder);

            //判断是什么订单 支付方式  1 全款 2 贷款
            OfflinePayments offlinePayments = new OfflinePayments();
            offlinePayments.setCarOrderId(carOrder.getId());
            OfflinePayments check = offlinePaymentsDao.queryOne(offlinePayments);
            if (null != check) {
                throw new ApiException("已经支付");
            }
            if ("1".equals(carOrder.getPayType())) {
                offlinePayments.setPaytype("1");
                offlinePayments.setTailStatus("1");
                offlinePayments.setDownPaymentStatus("1");
                offlinePayments.setInvoicePath(invoicePath);
            } else {
                offlinePayments.setPaytype("2");
                offlinePayments.setDownPaymentStatus("1");
                offlinePayments.setInvoicePath(invoicePath);
            }

            int i = offlinePaymentsDao.insertSelective(offlinePayments);
            if (c > 0 && i > 0) {
                return true;
            }
        } catch (Exception e) {
            log.info("pay", e);
            throw new ApiException(e.getMessage());
        }

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Operation("交车")
    public boolean delivery(Long id, String invoicePath) {

        log.info("delivery");
        try {
            /**
             * 查询订单
             *
             */

            CarOrder carOrder = getCarOrder(id);



            OfflinePayments offlinePayments = new OfflinePayments();
            offlinePayments.setCarOrderId(carOrder.getId());
            offlinePayments = offlinePaymentsDao.queryOne(offlinePayments);
            if (null == offlinePayments) {
                throw new ApiException("非法流程");
            }
            if (!StringUtils.isEmpty(offlinePayments.getDeliveryPath())) {
                throw new ApiException("交车流程已经提交");

            }

            offlinePayments.setDeliveryPath(invoicePath);
            int o = offlinePaymentsDao.updateByPrimaryKeySelective(offlinePayments);
//            offlinePaymentsDao.queryOne(carOrder.getId());
            if ( o > 0) {
                return true;
            }

//            offlinePaymentsDao.insertSelective(offlinePayments);

        } catch (Exception e) {
            log.info("delivery", e);
            throw new ApiException(e.getMessage());
        }

        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Operation("查询退款")
    public String refund(String orderId, String customerId) {
        log.info("delivery");

        try {

            Map<String, String> map = new HashMap<>();

            map.put("orderId", orderId);
            map.put("customerId", customerId);

            String s = JSONObject.toJSONString(map);

            String encrypt = RSAUtils.encrypt(RSAUtils.publicKey, s);

            Map<String, String> data = new HashMap<>();

            data.put("data", encrypt);

            System.out.println(JSONObject.toJSONString(data));

            String refundinfo = PostUtil.httpPost(Constant.validatebacking, data, "application/json");
            log.info(refundinfo);

            Map maps = (Map) JSON.parse(refundinfo);
            if (!maps.get("code").toString().equals("1")) {
                throw new ApiException(maps.get("msg").toString());
            }
            return maps.get("code").toString();
        } catch (Exception e) {
            log.info("delivery", e);
            throw new ApiException(e.getMessage());
        }

    }


    private CarOrder getCarOrder(Long id) {
        CarOrder carOrder = new CarOrder();
        carOrder.setId(id);
        CarOrder carOrderLast = carOrderDao.queryOne(carOrder);

        if (null == carOrderLast) {
            throw new ApiException("订单不存在");
        }
        return carOrderLast;
    }

}
