package com.cftech.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.invoice.model.Invoice;
import com.cftech.invoice.model.InvoiceDto;
import com.cftech.invoice.service.InvoiceService;
import com.cftech.order.model.*;
import com.cftech.order.dao.OrderMapper;
import com.cftech.order.service.OrderService;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.sql.Conds;

import com.cftech.order.utils.InvoiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单管理ServiceImpl
 *
 * @author Licc
 * @date: 2020-10-10 14:20
 */
@Service("orderService")
public class OrderServiceImpl extends GenericServiceImpl<Order> implements OrderService {

    @Autowired
    @Qualifier("orderMapper")
    private OrderMapper orderMapper;
    @Autowired
    private MpAccountsService mpAccountsService;
    private Order orders;

    @Autowired
    private InvoiceUtil invoiceUtil;

    @Autowired
    private InvoiceService invoiceService;



    @Override
    public GenericDao<Order> getGenericMapper() {
        return orderMapper;
    }

    @Override
    public List<Order> fetchSearchBy(Conds conds, Sort sort, int page, int pageSize, Long userid) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("offset", page > 0 ? page : 0);
        params.put("limit", pageSize > 0 ? pageSize : 0);
        params.put("sort", sort);
        //非管理员查询所有
        if (userid != null && userid != 1L) {
            params.put("userid", userid);
        }
        return orderMapper.fetchSearchByPage(params);
    }

    @Override
    public Integer count(Conds conds, Long userid) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        //非管理员查询所有
        if (userid != null && userid != 1L) {
            params.put("userid", userid);
        }
        return orderMapper.count(params);
    }

    @Override
    public List<ProductOrder> listProduct() {
        return orderMapper.listProduct();
    }

    @Override
    public OrderFromVO fetchId(Serializable id) {
        return orderMapper.fetchId(id);
    }

    @Override
    public List<OrderFromVO> fetchProductId(Serializable id) {
        return orderMapper.fetchProductId(id);
    }

    @Override
    public Integer updateStatus(Long id, String status, String orderCancel) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("status", status);
        params.put("orderCancel", orderCancel);
        return orderMapper.updateStatus(params);
    }

    @Transactional
    @Override
    public JSONObject newlyAdded(String datas, Long accountsId) {
        JSONObject rtnJson = new JSONObject();
        OrderDetailDto orderDetailDto = null;
        Map<String, Object> params = new HashMap<String, Object>();
        datas = datas.replaceAll("&quot;", "\"");
        JSONArray jsonArray = JSONArray.parseArray(datas);

        try {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                long id = jsonObject.getLong("id");
                String idDetail = jsonObject.getString("idDetail");
                long productId = jsonObject.getLong("productId");
                long drugsNum = jsonObject.getLong("drugsNum");
                double price = jsonObject.getDouble("price");
                double amount = jsonObject.getDouble("amount");
                double orderAmount = jsonObject.getDouble("orderAmount");
                params.put("id", id);
                params.put("accountsId", accountsId);
                params.put("productId", productId);
                params.put("drugsNum", drugsNum);
                params.put("price", price);
                params.put("amount", amount);
                params.put("orderAmount", orderAmount);
                params.put("idDetail", idDetail);
                if (StringUtils.isNotBlank(idDetail)) {
                    orderMapper.updateDetill(params);
                    //更新订单
                    Order newOrder = orderMapper.fetchOrder(id);
                    newOrder.setStatus("1");
                    newOrder.setOrderAmount(orderAmount);
                    newOrder.setOrderTime(new Date());
                    orderMapper.update(newOrder);
                    rtnJson.put("errorNo", "0");
                    return rtnJson;
                } else {
                    ProductDto productDtos = orderMapper.fetchProduct(params);
                    Order orders = orderMapper.fetchOrder(id);
                    orderDetailDto = new OrderDetailDto();
                    orderDetailDto.setOrderCode(orders.getNumber());
                    orderDetailDto.setOrderId(id);
                    orderDetailDto.setOpenid(orders.getOpenid());
                    orderDetailDto.setPrice(price);
                    orderDetailDto.setAmount(amount);
                    orderDetailDto.setDrugsNum(drugsNum);
                    orderDetailDto.setDrugsId(productDtos.getId());
                    orderDetailDto.setDrugsCode(productDtos.getProductNumber());
                    orderDetailDto.setDrugsSku(productDtos.getFormat());
                    orderDetailDto.setAccountsId(accountsId);
                    Integer detill = orderMapper.saveDetill(orderDetailDto);
                    if (detill > 0) {
                        Order newOrder = orderMapper.fetchOrder(id);
                        //更新订单
                        newOrder.setStatus("1");
                        newOrder.setOrderAmount(orderAmount);
                        newOrder.setOrderTime(new Date());
                        orderMapper.update(newOrder);
                        rtnJson.put("errorNo", "0");
                        rtnJson.put("errorMsg", "修改成功");
                        return rtnJson;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", "1");
        }
        rtnJson.put("errorNo", "1");
        return rtnJson;

    }

    @Override
    public JSONObject deleteAll(Long id) {
        JSONObject jsonObject = new JSONObject();
        Integer integer = orderMapper.deleteAll(id);
        if (integer < 0) {
            jsonObject.put("errorNo", "1");
        }
        jsonObject.put("errorNo", "0");
        return jsonObject;
    }

    @Override
    public JSONObject confirm(OrderMobileDto orderMobileDto) {
        MpAccountsEntity mpAccountsAppid = mpAccountsService.getMpAccountsAppid(orderMobileDto.getAppId());
        JSONObject rtnJson = new JSONObject();
        try {
            if (StringUtils.isEmpty(orderMobileDto.getOpenId())) {
                rtnJson.put("errorNo", "1");
                rtnJson.put("errorMsg", "openid不能为空");
                return rtnJson;
            }

            List<OrderMobile> orderMobiles = orderMapper.orderFall(orderMobileDto);
            for (OrderMobile orderMobile : orderMobiles) {
                if (orderMobile.getId() != null) {
                    List<ProductMobile> mobiles = orderMapper.orderDetill(orderMobile.getId());
                    orderMobile.setProductMobile(mobiles);
                }
            }

            JSONObject object = new JSONObject();
            object.put("orderMobiles", orderMobiles);

            rtnJson.put("errorNo", "0");
            rtnJson.put("data", object);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", "1");

        }
        return rtnJson;
    }

    @Override
    public JSONObject orderSize(String openId, String appId) {
        JSONObject rtnJson = new JSONObject();
        try {
            if (StringUtils.isEmpty(openId)) {
                rtnJson.put("errorNo", "0");
                rtnJson.put("errorMsg", "openid不能为空");
                return rtnJson;
            }
            MpAccountsEntity mpAccountsAppid = mpAccountsService.getMpAccountsAppid(appId);
            OrderSizeVO productMobiles = orderMapper.orderSize(openId);
            if (productMobiles != null) {
                rtnJson.put("errorNo", "0");
                rtnJson.put("data", productMobiles);
                return rtnJson;
            }
            rtnJson.put("errorNo", "1");
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", "1");
        }
        return rtnJson;
    }

    @Override
    public JSONObject orderList(OrderMobileDto orderMobileDto) {
        JSONObject rtnJson = new JSONObject();
        JSONObject object = new JSONObject();
        try {
            if (StringUtils.isEmpty(orderMobileDto.getOpenId())) {
                rtnJson.put("errorNo", "0");
                rtnJson.put("errorMsg", "openid不能为空");
                return rtnJson;
            }
            if (orderMobileDto.getStatus() == null) {
                rtnJson.put("errorNo", "0");
                rtnJson.put("errorMsg", "订单状态不能为空");
                return rtnJson;
            }
            MpAccountsEntity mpAccountsAppid = mpAccountsService.getMpAccountsAppid(orderMobileDto.getAppId());
            List<OrderMobile> orderMobiles = orderMapper.orderList(orderMobileDto);
            for (OrderMobile orderMobile : orderMobiles) {
                Long mobileId = orderMobile.getId();
                if (mobileId != null) {
                    List<ProductMobile> mobiles = orderMapper.orderDetill(mobileId);
                    orderMobile.setProductMobile(mobiles);
                }
            }
            object.put("orderMobiles", orderMobiles);
            rtnJson.put("errorNo", "0");
            rtnJson.put("data", object);
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", "1");
        }
        return rtnJson;
    }

    @Override
    public Integer isThreeUsers(String openid) {
        return orderMapper.isThreeUsers(openid);
    }

    @Override
    public JSONObject invoice(InvoiceDto invoiceDto) {
        JSONObject jsonObject = new JSONObject();
        MpAccountsEntity mpAccountsEntity = null;
        if (StringUtils.isNotBlank(invoiceDto.getAppId())){
             mpAccountsEntity = mpAccountsService.getMpAccountsAppid(invoiceDto.getAppId());
        }else{
            jsonObject.put("errorNo","2");
            jsonObject.put("errorMsg","appId不能为空");
            return jsonObject;
        }

        try {
            Conds conds = new Conds();
            conds.in("o.id",invoiceDto.getId().split(","));
            conds.equal("o.del_flag", Constants.DEL_FLAG_0);
            List<Order> list = orderMapper.fetchSearchBy(conds, null, 0, 0, null);
            if(list.size() > 0){
                for (Order order : list){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    order.setCreateTimeStr(format.format(order.getCreateTime()));
                    String str = invoiceUtil.startInvoice(order,order.getNickName(),invoiceDto.getEmail(),"0","0");
                    JSONObject json = JSON.parseObject(str);
                    if ( org.apache.commons.lang3.StringUtils.isNotBlank(json.getString("code")) && json.getString("code").equals("E0000")){
                        //开票成功 添加一条开票记录
                        //流水号
                        String invoiceSerialNum = json.getJSONObject("result").getString("invoiceSerialNum");
                        Invoice invoice = new Invoice();
                        //发票抬头
                        if(invoiceDto.getType().equals("1")){
                            //抬头类型为公司则设置发票抬头
                            invoice.setInvoiceTitle(invoiceDto.getInvoiceTitle());
                        }
                        invoice.setInvoiceContent(invoiceDto.getInvoiceContent());
                        invoice.setInvoiceType("1");
                        invoice.setInvoiceForm("1");
                        invoice.setClerkId(order.getMemberName());
                        invoice.setOrderId(order.getNumber());
                        invoice.setPushMode("0");
                        invoice.setEmail(invoiceDto.getEmail());
                        invoice.setStatus("0");
                        invoice.setInvoiceSerialNum(invoiceSerialNum);
                        invoice.setAccountsId(mpAccountsEntity.getId());
                        invoiceService.save(invoice);
                        jsonObject.put("errorNo", 0);
                    }else{
                        jsonObject.put("errorNo", 1);
                        jsonObject.put("errorMsg", org.apache.commons.lang3.StringUtils.isEmpty(json.getString("describe")) ? json.getString("message") : json.getString("describe"));
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("errorNo","1");
            jsonObject.put("errorMsg","程序异常");
        }
        return jsonObject;
    }

}