package com.bohuikeji.delivery.backstage.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.excel.OrderDataListener;
import com.bohuikeji.delivery.backstage.excel.OrderDom;
import com.bohuikeji.delivery.backstage.service.ITCustomerBigService;
import com.bohuikeji.delivery.backstage.service.ITLogisticsService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.ITOrderTemplateService;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.easypdf.my.TextUtils;
import com.bohuikeji.frame.module.admin.easypdf.util.TextUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 订单
 *
 * @author 10552
 */
@Slf4j
@RestController
@RequestMapping("/admin/order/batch")
public class BatchOrderController extends ControllerBase {

    @Autowired
    ITOrderService orderService;
    @Autowired
    ITLogisticsService logisticsService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ITOrderTemplateService orderTemplateService;
    @Autowired
    ITCustomerBigService bigService;

    /**
     * 上传批量订单文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @InitLog(value = "上传批量订单文件",action = "上传")
    @PostMapping("/upload/excel")
    public APIEntity updateExcel(MultipartFile file, Integer templateId, Integer playerId, String rmk) throws IOException {
        if (!FileUtil.checkFileSize(file.getSize(), 1, "M")) {
            return APIEntity.fail("抱歉，您上传的文件太大了,请拆分为1M及以下的文件上传！");
        }
        TOrderTemplate template = orderTemplateService.getById(templateId);
        if (template == null) {
            return APIEntity.fail("无法找到订单模板信息，请刷新页面再试！");
        }
        SysUser user=getLoginUser();
        TCustomerBig big;
       if(user.getRoleId().equals(17)){
           List<TCustomerBig> bigs=bigService.list(new QueryWrapper<TCustomerBig>().eq("user_id",user.getUserId()));
           if(bigs.size()>1){
               return APIEntity.fail("检测到您当前账号绑定了多个签约商户，请解绑其他商户再试！");
           }
           big=bigs.get(0);
       }
       else {
           big = bigService.getById(playerId);
       }
        if (big == null) {
            return APIEntity.fail("无法找到签约商户信息，请先选择或者绑定签约商户！");
        }
        String batchNum = "B" + NumberUtils.getShort();
        //log.info("开始计时：{}",System.currentTimeMillis());
        EasyExcel.read(file.getInputStream(), OrderDom.class, new OrderDataListener(redisUtil, orderService, logisticsService, template, big, batchNum, rmk)).sheet().headRowNumber(3).doRead();
        if (redisUtil.listSize("batchError:" + batchNum) > 0) {
            List<String> stringList = redisUtil.getListByRang("batchError:" + batchNum, 0, 100, String.class);
            redisUtil.del("batchError:" + batchNum);
            return APIEntity.success(stringList).setStatus(400).setMessage("批量导入失败！");

        }
        return APIEntity.success(redisUtil.get(batchNum + "Result"));
    }

    /**
     * 订单批量打印
     *
     * @param ids
     * @return
     */
    @InitLog(value = "订单批量打印",action = "打印")
    @PostMapping("/print")
    public APIEntity printBatchOrder(@RequestParam("ids") Integer[] ids) throws IOException {
        //订单列表
        Collection<TOrder> orderList = orderService.list(new QueryWrapper<TOrder>().in("order_id", ids).orderByDesc("order_id"));
        //待打印的物流包裹列表
        List<TLogistics> logisticList = logisticsService.list(new QueryWrapper<TLogistics>().in("order_id", ids));
        log.info("物流记录共有：{}",logisticList.size());
        //创建一key对多value的Map集合，其中key=订单号，value=物流单号
        MultiValueMap<Integer, String> multiValueMap = new LinkedMultiValueMap<>();
        for (TLogistics logistics : logisticList) {
            multiValueMap.add(logistics.getOrderId(), logistics.getLogisticsNum());
        }
        //创建并载入打印文档
        PDDocument pdf = new PDDocument();
        PDFont font = PDType0Font.load(
                pdf,
                FileUtil.readResourceFile("/static/fonts/Deng.ttf"));
        String printTime = "打印时间：" + LocalDateTime.now().format(StringUtils.dataTimeFormat);
        //定义打印单页，后面使用模板绘制重复使用
        PDPage page;
        //订单打印单页页面流，同样后面使用模板重复使用
        PDPageContentStream contents;
        //大客户信息缓存，默认5个
        Map<Integer,TCustomerBig> bigCatch=new HashMap<Integer,TCustomerBig>(5);
        //打印文档页号索引
        int index = 1;
        Integer userId = getLoginUser().getUserId();
        for (TOrder order : orderList) {
            for (String logisticsNum : multiValueMap.get(order.getOrderId())) {
                try {
                    //得到打印模板对象
                    PDDocument tmpDoc = PDDocument.load(FileUtil.readResourceFile("print/template.pdf"));
                    page = tmpDoc.getPage(0);
                    contents = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.APPEND, true, true);
                    //绘制打印时间
                    TextUtils.drawRow(contents, font, 8, 15, 785, printTime);
                    TCustomerBig big=bigCatch.get(order.getOrderBatchPlayerId());
                    if(big==null){
                        big=bigService.getById(order.getOrderBatchPlayerId());
                        if (big == null) {
                            return APIEntity.fail("该订单未找到对应的签约客户信息，请重新导入！");
                        }
                        bigCatch.put(order.getOrderBatchPlayerId(),big);
                    }
                    //绘制打印编号
                    TextUtils.drawRow(contents, font, 10, 60, 774, userId + "-" + big.getBigNum() + "-" + orderList.size() + "-" + index + "-" + order.getId());
                    //绘制派送方式
                    TextUtils.drawRow(contents, font, 12, 150, 810, order.getWayName());
                    PDImageXObject pdImage = PDImageXObject.createFromFileByContent(ZxingUtils.createBarCode(logisticsNum, 150, 38), pdf);
                    //绘制物流单号条形码(当前为订单号)
                    contents.drawImage(pdImage, 20, 730);
                    //绘制物流单号(当前为订单号)
                    TextUtils.drawRow(contents, font, 10, 70, 721, logisticsNum);
                    //绘制收件人信息
                    TextUtils.drawRow(contents, font, 9, 37, 703, order.getReceiptName() + "  " + order.getReceiptPhone());
                    //绘制收件人地址
                    TextUtils.drawRows(contents, font, 8, 12, 692, 16, order.getReceiptAddress().getAddress() + order.getReceiptAddress().getDetail());
                    //绘制车辆类型
                    TextUtils.drawRow(contents, font, 9, 152, 703, order.getVehicleName());
                    //绘制物品类型及价值
                    TextUtils.drawRow(contents, font, 8, 144, 688, order.getCargoName() + "/" + order.getWorthName());
                    //绘制重量
                    TextUtils.drawRow(contents, font, 8, 160, 680, order.getCargoWeight() + "公斤");
                    //绘制支付方式
                    TextUtils.drawRow(contents, font, 10, 162, 662, order.getPaymentType());
                    //绘制寄件人信息
                    TextUtils.drawRow(contents, font, 9, 37, 641, order.getMailingName() + "  " + order.getMailingPhone());
                    //绘制备注
                    TextUtils.drawRows(contents, font, 7, 145, 635, 10, order.getOrderRemarks());
                    //绘制包裹提示
                    TextUtils.drawRows(contents, font, 7, 145, 604, 10, order.getPackageCount()>1?"系统：共"+order.getPackageCount()+"个包裹":"");
                    //寄件人地址
                    TextUtils.drawRows(contents, font, 8, 12, 630, 16, order.getMailingAddress().getAddress() + order.getMailingAddress().getDetail());
                    //绘制订单号二维码
                    contents.drawImage(PDImageXObject.createFromFileByContent(ZxingUtils.createQREncode(order.getOrderNum(), 60, 60), pdf), 150, 540);
                    //绘制客户信息1
                    TextUtils.drawRows(contents, font, 8, 15, 578, 15, big.getBigName() + "-" + big.getBigNum());
                    //绘制客户信息2
                    TextUtils.drawRows(contents, font, 8, 15, 545, 15, order.getPlayerInfo());
                    pdf.addPage(page);
                    contents.close();
                    contents = null;
                    page = null;
                    tmpDoc = null;
                    index++;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        File tmpFile = PrintUtils.createTempFile(".pdf");
        pdf.save(tmpFile);
        pdf.close();
        log.info("打印文件位于：{}", tmpFile.getPath());
        return APIEntity.success(StaticComponent.ctx + "/upload/tempPath/" + tmpFile.getName());
    }


}
