package com.fdkankan.platform.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.TbStatus;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.common.util.NumberUtils;
import com.fdkankan.platform.common.ConstantExcel;
import com.fdkankan.platform.common.ExcelUtil;
import com.fdkankan.platform.goods.common.SkuCache;
import com.fdkankan.platform.goods.service.IGoodsSkuService;
import com.fdkankan.platform.goods.vo.ResponseGoodsSku;
import com.fdkankan.platform.order.entity.IncrementOrder;
import com.fdkankan.platform.order.entity.Invoice;
import com.fdkankan.platform.order.mapper.IIncrementOrderMapper;
import com.fdkankan.platform.order.service.IIncrementOrderService;
import com.fdkankan.platform.order.service.IInvoiceService;
import com.fdkankan.platform.user.request.RequestIncrementOrder;
import com.fdkankan.platform.user.request.RequestOrder;
import com.fdkankan.platform.user.vo.ResponseIncrementOrder;
import com.fdkankan.platform.user.vo.ResponseInvoice;
import com.fdkankan.platform.user.vo.ResponseOrder;
import com.fdkankan.platform.util.ResultConvertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 增值权益订单表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Service
public class IncrementOrderServiceImpl extends ServiceImpl<IIncrementOrderMapper, IncrementOrder> implements IIncrementOrderService {

    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IInvoiceService invoiceService;
    @Resource
    private IIncrementOrderMapper incrementOrderMapper;

    @Override
    public ResponseIncrementOrder saveByOrderParam(Long userId, RequestIncrementOrder order, BigDecimal price) {
        BigDecimal total = price.multiply(new BigDecimal(order.getCount()));

        IncrementOrder incrementOrderEntity = new IncrementOrder();
        incrementOrderEntity.setOrderSn(NumberUtils.getOrderSn());
        incrementOrderEntity.setAmount(total);
        incrementOrderEntity.setPayType(order.getPayType());
        incrementOrderEntity.setPayStatus(-1);
        incrementOrderEntity.setUserId(userId);
        incrementOrderEntity.setCount(order.getCount());
        incrementOrderEntity.setAbroad(order.getAbroad());
        incrementOrderEntity.setStatus(order.getIncrementId() == null ? 1 : 2);
        incrementOrderEntity.setIncrementId(order.getIncrementId());
        if(!this.save(incrementOrderEntity)){
            throw  new BusinessException(ErrorCode.ERROR_MSG);
        }
        ResponseIncrementOrder incrementOrder = new ResponseIncrementOrder();
        BeanUtils.copyProperties(incrementOrderEntity, incrementOrder);
        return incrementOrder;
    }

    @Override
    public Page<ResponseIncrementOrder> getPageByParam(Long userId, RequestIncrementOrder param) {
        QueryWrapper<IncrementOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IncrementOrder::getTbStatus, TbStatus.VALID.code());
        queryWrapper.lambda().eq(IncrementOrder::getUserId,userId);
        queryWrapper.lambda().eq(IncrementOrder::getPayStatus,1);
        queryWrapper.lambda().orderByDesc(IncrementOrder::getTradeTime);
        Page<IncrementOrder> entityPage = new Page<>(param.getPageNum(),param.getPageSize());
        Page<IncrementOrder> page = this.page(entityPage, queryWrapper);

        ResponseGoodsSku sku = goodsSkuService.getVoBySkuSn(SkuCache.skusMap.get("5"));

        List<ResponseIncrementOrder> responseList = this.convert(page.getRecords(), sku.getDescription());
        Page<ResponseIncrementOrder> voPage = new Page<ResponseIncrementOrder>(param.getPageNum(), param.getPageSize());
        voPage.setTotal(page.getTotal());
        voPage.setRecords(responseList);

        ResponseInvoice responseInvoice = null;
        QueryWrapper<Invoice> invoiceQueryWrapper= null;
        for (ResponseIncrementOrder responseIncrementOrder : voPage.getRecords()) {
            invoiceQueryWrapper = new QueryWrapper<>();
            invoiceQueryWrapper.lambda().eq(Invoice::getIncrementOrderId,responseIncrementOrder.getId());
            List<Invoice> list = invoiceService.list(invoiceQueryWrapper);
            if(list.size() > 0){
                Invoice invoiceEntity = list.get(0);
                if(invoiceEntity != null){
                    responseInvoice = new ResponseInvoice();
                    BeanUtils.copyProperties(invoiceEntity, responseInvoice);
                    responseIncrementOrder.setInvoice(responseInvoice);
                }
            }
        }
        return voPage;

    }

    private List<ResponseIncrementOrder> convert(List<IncrementOrder> list, String name){
        List<ResponseIncrementOrder> result = new ArrayList<>();
        ResponseIncrementOrder responseIncrementOrder = null;
        for (IncrementOrder incrementOrderEntity : list) {
            responseIncrementOrder = new ResponseIncrementOrder();
            BeanUtils.copyProperties(incrementOrderEntity, responseIncrementOrder);
            responseIncrementOrder.setName(name);
            result.add(responseIncrementOrder);
        }
        return result;
    }

    @Override
    public IncrementOrder getByOrderSn(String orderSn) {
        QueryWrapper<IncrementOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IncrementOrder::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(IncrementOrder::getOrderSn,orderSn);
        List<IncrementOrder> list = this.list(queryWrapper);
        if(list == null || list.size()<=0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public boolean paySuccessIncrementOrder(String orderSn, String tradeNo, int paymentTypeName) {
        LambdaUpdateWrapper<IncrementOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(IncrementOrder::getPayType,paymentTypeName)
                .set(IncrementOrder::getNumber,tradeNo)
                .set(IncrementOrder::getPayStatus, 1)
                .set(IncrementOrder::getTradeTime, new Date())
                .eq(IncrementOrder::getOrderSn,orderSn)
                .eq(IncrementOrder::getTbStatus,TbStatus.VALID.code());
        return this.update(updateWrapper);
    }

    @Override
    public ResponseIncrementOrder getVoById(Long incrementOrderId) {
        IncrementOrder incrementOrderEntity  = getById(incrementOrderId);
        ResponseIncrementOrder responseIncrementOrder = new ResponseIncrementOrder();
        if(incrementOrderEntity!=null){
            BeanUtils.copyProperties(incrementOrderEntity,responseIncrementOrder);
        }
        return responseIncrementOrder;
    }

    @Override
    public Page<ResponseOrder> getOrderList(RequestOrder param) {
        Page<ResponseOrder> orderList = incrementOrderMapper.getOrderList(new Page<>(param.getPageNum(), param.getPageSize()), param);
        ResultConvertUtil.getOrderList(orderList.getRecords());
        return orderList;
    }

    @Override
    public ResponseOrder findOrderByOrderId(Long orderId) {
        IncrementOrder order = this.getById(orderId);
        ResponseOrder responseOrder = new ResponseOrder();
        if (order != null){
            responseOrder.setId(order.getId());
            responseOrder.setOrderSn(order.getOrderSn());
            responseOrder.setOrderStatus("已完成");
            if (order.getPayStatus().equals(1)) {
                responseOrder.setPaymentStatus("已付款");
            }
            if (order.getPayStatus().equals(-2)) {
                responseOrder.setPaymentStatus("已退款");
            }
            if (order.getPayStatus() <= 0) {
                responseOrder.setPaymentStatus("未付款");
            }
            responseOrder.setPaymentTypeName(order.getPayType());
            responseOrder.setTotalAmount(order.getAmount());
            responseOrder.setOrderTime(order.getCreateTime());
            responseOrder.setFinishTime(order.getTradeTime());
            responseOrder.setUserId(order.getUserId());
            Invoice  invoice = invoiceService.getInvoiceByDownloadOrderId(order.getId());
            if(invoice != null){
                ResponseInvoice responseInvoice = new ResponseInvoice();
                BeanUtils.copyProperties(invoice, responseInvoice);
                responseOrder.setInvoice(responseInvoice);
            }
        }
        return responseOrder;
    }

    @Override
    public String export(RequestOrder param) {
        List<ResponseOrder> orders = incrementOrderMapper.getOrderList(null,param).getRecords();
        List<Map> dataList = new ArrayList<Map>();
        int serNum = 1;
        for (int i = 0; i < orders.size(); ++i) {
            ResponseOrder order = orders.get(i);
            Map<String, String> item = new HashMap();
            String num = order.getOrderSn();
            if (order.getPaymentStatus().equals("0") || order.getPaymentStatus().equals("-1")) { //未支付
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[0], String.valueOf(serNum));
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[1], "");
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[10], "未付款");
            } else if (order.getPaymentStatus().equals("1")){
                //支付成功
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[0], String.valueOf(serNum));
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[1], new SimpleDateFormat("yyyyMMddhhmmss").format(order.getFinishTime()));
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[10], "已付款");
            } else if(order.getPaymentStatus().equals("-2")){
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[10], "全额退款");
            }

            item.put(ConstantExcel.ORDEREXCELCOLENNAME[2], order.getOrderSn());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[3], order.getUserName());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[4], String.valueOf(order.getTotalAmount()));
            if (order.getPaymentTypeName() == -1) {
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[5], "未支付");
            } else {
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[5], ConstantExcel.PAYFORM[order.getPaymentTypeName()]);
            }
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[6], order.getShipAddress());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[7], order.getShipMobile());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[8], order.getShipName());
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[9], "已确认");

            item.put(ConstantExcel.ORDEREXCELCOLENNAME[12], order.getTradeNum());

            Invoice invoice = invoiceService.getInvoiceByDownloadOrderId(order.getId());
            if (!ObjectUtils.isEmpty(invoice)) {
                int type = invoice.getType();
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[13], ConstantExcel.INVOICE[type - 1]);
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[14], invoice.getTitle());
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[15], invoice.getCode());
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[16], invoice.getOrganizedAddress());
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[17], invoice.getRegisterPhone());
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[18], invoice.getBankName());
                item.put(ConstantExcel.ORDEREXCELCOLENNAME[19], invoice.getBankAccount());
            }
            ++serNum;
            dataList.add(item);
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(new Date());

        String filePath = FileUtils.getResource().concat("excel/");
        FileUtils.createDir(filePath);

        ExcelUtil.writeExcel(dataList, 20, filePath + dateStr + ".xls", 1);

        return filePath + dateStr + ".xls";    }
}
