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.goods.vo.SceneCountVo;
import com.fdkankan.platform.order.entity.DownloadOrder;
import com.fdkankan.platform.order.entity.Invoice;
import com.fdkankan.platform.order.mapper.IDownloadOrderMapper;
import com.fdkankan.platform.order.service.IDownloadOrderService;
import com.fdkankan.platform.order.service.IInvoiceService;
import com.fdkankan.platform.user.request.RequestDownloadOrder;
import com.fdkankan.platform.user.request.RequestIncrementOrder;
import com.fdkankan.platform.user.request.RequestOrder;
import com.fdkankan.platform.user.vo.ResponseDownloadOrder;
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 DownloadOrderServiceImpl extends ServiceImpl<IDownloadOrderMapper, DownloadOrder> implements IDownloadOrderService {

    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IInvoiceService invoiceService;
    @Resource
    private IDownloadOrderMapper downloadOrderMapper;

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

        DownloadOrder downloadOrderEntity = new DownloadOrder();
        downloadOrderEntity.setOrderSn(NumberUtils.getOrderSn());
        downloadOrderEntity.setAmount(total);
        downloadOrderEntity.setPayType(order.getPayType());
        downloadOrderEntity.setPayStatus(-1);
        downloadOrderEntity.setUserId(userId);
        downloadOrderEntity.setCount(order.getCount());
        downloadOrderEntity.setAbroad(order.getAbroad());
        downloadOrderEntity.setDownStatus(1);
        downloadOrderEntity.setSceneNum(order.getSceneNum());
        downloadOrderEntity.setSceneName(order.getSceneName());
        if(!this.save(downloadOrderEntity)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        ResponseDownloadOrder downloadOrder = new ResponseDownloadOrder();
        BeanUtils.copyProperties(downloadOrderEntity, downloadOrder);
        return downloadOrder;
    }

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

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

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

        ResponseInvoice responseInvoice = null;
        QueryWrapper<Invoice> invoiceQueryWrapper= null;
        for (ResponseDownloadOrder responseDownloadOrder : voPage.getRecords()) {
            invoiceQueryWrapper = new QueryWrapper<>();
            invoiceQueryWrapper.lambda().eq(Invoice::getDownloadOrderId,responseDownloadOrder.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);
                    responseDownloadOrder.setInvoice(responseInvoice);
                }
            }
        }
        return voPage;
    }

    private List<ResponseDownloadOrder> convert(List<DownloadOrder> records, String description) {
        List<ResponseDownloadOrder> result = new ArrayList<>();
        ResponseDownloadOrder responseDownloadOrder = null;
        for (DownloadOrder downloadOrderEntity : records) {
            responseDownloadOrder = new ResponseDownloadOrder();
            BeanUtils.copyProperties(downloadOrderEntity, responseDownloadOrder);
//            responseDownloadOrder.setName(name);
            result.add(responseDownloadOrder);
        }
        return result;
    }

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

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

    @Override
    public ResponseDownloadOrder getVoById(Long downloadOrderId) {
        DownloadOrder downloadOrderEntity  = getById(downloadOrderId);
        ResponseDownloadOrder responseDownloadOrder = new ResponseDownloadOrder();
        if(downloadOrderEntity!=null){
            BeanUtils.copyProperties(downloadOrderEntity,responseDownloadOrder);
        }
        return responseDownloadOrder;
    }

    @Override
    public HashMap<String, Integer> getCountBySceneNum() {
        HashMap<String,Integer> map = new HashMap<>();
        List<SceneCountVo> countBySceneNum = downloadOrderMapper.getCountBySceneNum();
        for (SceneCountVo sceneCountVo : countBySceneNum) {
            map.put(sceneCountVo.getSceneNum(),sceneCountVo.getTotal());
        }
        return map;
    }

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

    @Override
    public ResponseOrder findByOrderId(Long orderId) {
        DownloadOrder 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 = downloadOrderMapper.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));
                if(!ObjectUtils.isEmpty(order.getFinishTime())){
                    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[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";    }
}
