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.CustomerDao;
import com.pine.admin.modules.business.entity.Customer;
import com.pine.admin.modules.business.service.LogisticsTemplateService;
import com.pine.admin.modules.business.service.OrderAttrService;
import com.pine.admin.modules.business.service.OrderSkuService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

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

import com.pine.admin.modules.business.dao.OrderDao;
import com.pine.admin.modules.business.entity.Order;
import com.pine.admin.modules.business.service.OrderService;


@Service("orderService")
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private OrderSkuService orderSkuService;
    @Autowired
    private OrderAttrService orderAttrService;
    @Autowired
    private LogisticsTemplateService logisticsTemplateService;


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

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

        return null;
    }

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

        log.info("getOrderByPage");
        try {
            if (!ShiroUtils.getShiroUserInfo().getName().contains("商城管理员")) {
                record.setDealerId(ShiroUtils.getShiroUserInfo().getDealerID());
            }
            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("record", record);
            parameter.put("page", page);
            return orderDao.queryByPage(parameter);
        } catch (Exception e) {
            log.error("getOrderByPage", e);
        }

        return null;
    }

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

        log.info("getOrderById");
        try {

            Order order = orderDao.getById(Long.valueOf(id));
            if (!ShiroUtils.getShiroUserInfo().getName().contains("商城管理员")) {
               if (!order.getDealerId().equals(ShiroUtils.getShiroUserInfo().getDealerID())){
                   throw new ApiException("无权限查看");
               }
            }
            if (Objects.isNull(order)) {
                log.error("order is not exist");
                return order;
            }

            this.FullOrderInfo(order);
            return order;
        } catch (Exception e) {

            log.error("getOrderById", e);
            throw new ApiException(e.getMessage());

        }
    }


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

        log.info("getOrder");
        try {

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

        return null;
    }

    @Override
    @Transactional
    public boolean create(Order record) {

        log.info("createOrder");
        try {

            int updates = orderDao.insertSelective(record);

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

        return false;
    }

    @Override
    @Transactional
    public boolean delete(String id) {

        log.info("deleteOrder");
        try {

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

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

        return false;
    }

    @Override
    @Transactional
    public boolean deltetByIds(String ids) {

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

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

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

        return false;
    }

    @Override
    @Transactional
    public boolean update(Order record) {

        log.info("updateOrder");
        try {

            int updates = orderDao.updateByPrimaryKeySelective(record);

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

        return false;
    }

    @Override
    public void FullOrderInfo(Order order) {
        //填充会员信息
        Customer customer = customerDao.getById(order.getCustomerId());
        if (Objects.nonNull(customer)) {
            order.setCustomerName(customer.getUsername());
            order.setCustomerMobile(customer.getMobile());
        } else {
            order.setCustomerName("");
            order.setCustomerMobile("");
        }
        order.setOrderSkus(orderSkuService.queryByOrderId(order.getId()));
        // 设置订单的附属信息
        order.setOrderAttr(orderAttrService.queryByOrderId(order.getId()));
        //设置物流模板信息
        order.setLogisticsTemplate(logisticsTemplateService.queryLogisticsTemplateWithCompany(order.getFreightTemplateId()));
    }

    @Override
    @Operation("核销订单")
    public String checkWriteOffVirtualRequest(Long orderId, String writeOffCode) {
        Map<String,Object> map = new HashMap<>();
        map.put("orderId",orderId);
        map.put("writeOffCode",writeOffCode);
        map.put("dealerName",ShiroUtils.getShiroUserInfo().getName());
        String resKey = RSAUtils.encrypt(RSAUtils.publicKey, JSONObject.toJSONString(map));

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

        data.put("data", resKey);

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

        String refundinfo = PostUtil.httpPost(Constant.dealerWriteOffVerification, 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("msg").toString();
    }
}
