package cn.ezhizao.project.business.carrier.controller;

import cn.ezhizao.common.constant.Constants;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.common.utils.pdf.PdfImages;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.task.RyTask;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.carrier.domain.BizCarrier;
import cn.ezhizao.project.business.carrier.domain.BizCarrierCategory;
import cn.ezhizao.project.business.carrier.service.IBizCarrierCategoryService;
import cn.ezhizao.project.business.carrier.service.IBizCarrierService;
import cn.hutool.core.io.IoUtil;
import com.alibaba.nacos.common.utils.IoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.VerticalAlignment;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * 载具Controller
 *
 * @author ezhizao
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/business/carrier")
public class BizCarrierController extends BaseController {
    @Resource
    private IBizCarrierService iBizCarrierService;

    @Resource
    private IBizCarrierCategoryService iBizCarrierCategoryService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RyTask task;

    @Value("${file.upload.path}")
    private String filePath;
    @Value("${file.upload.url}")
    private String fileUrl;

    /**
     * 查询载具列表
     */
    @PreAuthorize("@ss.hasPermi('business:carrier:list')")
    @Log(title = "载具查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizCarrier data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        Integer zero = 0;
//        String tenantId = request.getHeader("tenantId");
//        if (tenantId != null && !zero.toString().equals(tenantId)) {
//            data.setTenantId(Long.valueOf(tenantId));
//        }
        startPage();
        List<BizCarrier> list = iBizCarrierService.getList(data);
        for (BizCarrier item : list
        ) {
            if (item.getQcCode().equals("")) {
                task.GenerateQcCode(item);
            }
        }
        return getDataTable(list);
    }

    /**
     * 批量新增载具
     * @param bizCarrier
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/saveCarrier")
    @Log(title = "载具新增", businessType = BusinessType.INSERT)
    public AjaxResult saveCarrier(@RequestBody BizCarrier bizCarrier) throws JsonProcessingException {

        if(bizCarrier.getStartCode()==null||bizCarrier.getEndCode()==null || bizCarrier.getStartCode().equals("") || bizCarrier.getEndCode().equals("")){
            return error("请输入正确的起始码和结束码");
        }
        List<String> code = new ArrayList<>();

        for (int i = Integer.parseInt(bizCarrier.getStartCode()); i <= Integer.parseInt(bizCarrier.getEndCode()); i++) {
            String a = String.format("%06d", i);
            code.add(a);
        }
        List<BizCarrier>carrierList = new ArrayList<>();

        // 输出 List A 中的元素
        for (String str : code) {
            BizCarrier carrier = new BizCarrier();
            carrier.setCode(str);
            carrier.setCategoryId(bizCarrier.getParentId());
            carrier.setIsAllowMore(bizCarrier.getIsAllowMore()==null?0: bizCarrier.getIsAllowMore());
            carrier.setIsInspection(bizCarrier.getIsInspection()==null?0: bizCarrier.getIsInspection());
            carrier.setTenantId(1L);
            carrierList.add(carrier);
        }

        return success(iBizCarrierService.saveBatch(carrierList));
    }


    /**
     * 查询载具列表
     */
    @PreAuthorize("@ss.hasPermi('business:carrier:list')")
    @Log(title = "载具下载", businessType = BusinessType.EXPORT)
    @Transactional
    @PostMapping("/download")
    public AjaxResult download(@RequestBody Map<String, Object> data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        Integer zero = 0;
        String tenantId = request.getHeader("tenantId");
        QueryWrapper<BizCarrier> queryWrapper = new QueryWrapper<>();
        final String param1 = "categoryId";
        long categoryId = 0L;
        if (data.get(param1) != null) {
            categoryId = Long.parseLong(data.get(param1).toString());
        }
        if (tenantId != null && !zero.toString().equals(tenantId)) {
            queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
        }
        queryWrapper.eq("qc_code", "");
        List<BizCarrier> list = iBizCarrierService.list(queryWrapper);
        for (BizCarrier item : list) {
            task.GenerateQcCode(item);
        }
        return success();
    }

    /**
     * 获取载具详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:carrier:query')")
    @Log(title = "载具查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(iBizCarrierService.getById(id));
    }

    /**
     * 新增载具
     */
//    @PreAuthorize("@ss.hasPermi('business:carrier:add, business:carrier:edit')")
    @Log(title = "载具新增", businessType = BusinessType.INSERT)
    @PostMapping(value = "/save")
    public AjaxResult save(@RequestBody BizCarrier bizCarrier) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        final String tenantId = request.getHeader("tenantId");
        QueryWrapper<BizCarrier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", bizCarrier.getCode());
        queryWrapper.eq("is_abandoned", 0);
        queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
        long currentCarrierId = 0L;
        if (bizCarrier.getId() != null) {
            currentCarrierId = bizCarrier.getId();
        }
        queryWrapper.ne("id", currentCarrierId);
        List<BizCarrier> carriers = iBizCarrierService.list(queryWrapper);
        if (carriers.size() > 0) {
            return AjaxResult.warn("该载具编码已存在");
        }
        bizCarrier.setTenantId(Long.valueOf(tenantId));
        boolean bool = iBizCarrierService.saveOrUpdate(bizCarrier);
        task.GenerateQcCode(bizCarrier);
        return bool ? success(bizCarrier) : error("操作失败!");
    }
    @Log(title = "载具修改", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update")
    public AjaxResult update(@RequestBody BizCarrier bizCarrier) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {

        return success(iBizCarrierService.updateById(bizCarrier));
    }

    /**
     * 删除载具
     */
//    @PreAuthorize("@ss.hasPermi('business:carrier:remove')")
    @Log(title = "载具删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(iBizCarrierService.removeBatchByIds(ids));
    }

    @Log(title="载具码pdf", businessType = BusinessType.UPDATE)
    @GetMapping("/printUpdate/{ids}")
    public AjaxResult printUpdate(@PathVariable List<Long> ids) {
        List<BizCarrier> carriers = iBizCarrierService.query().in("id", ids.isEmpty() ? Collections.singletonList(-1) : ids).list();
        carriers.forEach(l -> {
            l.setIsPrint(1);
        });
        return toAjax(carriers.isEmpty() || iBizCarrierService.updateBatchById(carriers));
    }
    /**
     * 取消废弃
     *
     * @param id 载具id
     * @return ajax结果
     */
//    @PreAuthorize("@ss.hasPermi('business:carrier:unAbandoned')")
    @Log(title = "载具取消废弃", businessType = BusinessType.DELETE)
    @GetMapping("/unAbandoned/{id}")
    public AjaxResult unAbandoned(@PathVariable Long id) {
        QueryWrapper<BizCarrier> findWrapper = new QueryWrapper<>();
        findWrapper.eq("id", id);
        BizCarrier bizCarrier = iBizCarrierService.getOne(findWrapper);
        if (bizCarrier == null) {
            return AjaxResult.error("该载具不存在");
        } else {
            QueryWrapper<BizCarrier> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", bizCarrier.getCode());
            queryWrapper.eq("is_abandoned", 0);
            queryWrapper.ne("id", id);

            List<BizCarrier> carriers = iBizCarrierService.list(queryWrapper);

            if (carriers.size() > 0) {
                return AjaxResult.warn("该载具编码已存在");
            }
        }
        return toAjax(iBizCarrierService.unAbandoned(id));
    }

    @Log(title="导出载具码pdf", businessType = BusinessType.EXPORT)
    @PostMapping("/printQrcodePdf")
    public void printQrcodePdf(@RequestBody List<Long> ids, HttpServletResponse response) throws IOException {
        List<BizCarrier> carriers = iBizCarrierService.query().in("id", ids).list();
        String htmlContent = "<html><body></body></html>";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ConverterProperties converterProperties = new ConverterProperties();
        PageSize pageSize = new PageSize(100, 100);
        // 创建一个Document对象，并设置页面大小为100mm * 100mm
        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdf = new PdfDocument(writer);
        //设置纸张的大小，并且设置默认的pdf大小
        pdf.setDefaultPageSize(pageSize);
        List<Image> images = new ArrayList<>();
        pdf.addNewPage();
        for (int i = 0; i < carriers.size();i++) {
            BizCarrier l = carriers.get(i);
            pdf.addNewPage();
            File file = new File(filePath + StringUtils.substringAfter(l.getQcCode(), Constants.RESOURCE_PREFIX + "/upload"));
            try {
                Image image = new Image(ImageDataFactory.create(file.getPath()));
                image.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
                images.add(image);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        }
//        images.forEach(image -> pdf.addNewPage(new PageSize(new Rectangle(image.getImageScaledWidth(), image.getImageScaledHeight()))));
        pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PdfImages(images));
        HtmlConverter.convertToPdf(htmlContent, pdf, converterProperties);
        byte [] resources = outputStream.toByteArray();
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(resources);
        servletOutputStream.close();
    }
}
