package cn.ezhizao.project.business.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.PdfUtil;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.common.utils.uuid.SnowflakeIdWorker;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.qrCode.BarCodeDemo;
import cn.ezhizao.framework.qrCode.QrCodeDemo;
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.domain.*;
import cn.ezhizao.project.business.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.hutool.core.date.DateTime;
import cn.hutool.extra.template.TemplateException;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

/**
 * 合格证Controller
 *
 * @author ezhizao
 * @date 2024-09-02
 */
@RestController
@RequestMapping("/business/certificate")
public class BizCertificateController extends BaseController
{

    @Value("${file.upload.path}")
    private String uploadPath;
    @Value("${baseUrl}")
    private String baseUrl;
    @Resource
    private IBizCertificateService bizCertificateService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizPackageResourceGroupService bizPackageResourceGroupService;
    @Resource
    private IBizCertificateLotService bizCertificateLotService;
    @Resource
    private IBizCompanyProductPackageService bizCompanyProductPackageService;
    @Resource
    private ISysDeptService sysDeptService;
    /**
     * 生成pdf
     */
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 查询合格证列表
     */
    @PreAuthorize("@ss.hasPermi('business:certificate:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizCertificate bizCertificate) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(bizCertificate);
        startPage();
        List<BizCertificate> list = bizCertificateService.getList(bizCertificate);
        return getDataTable(list);
    }

    /**
     * 导出合格证列表
     */
    @PreAuthorize("@ss.hasPermi('business:certificate:export')")
    @Log(title = "合格证", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizCertificate bizCertificate) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(bizCertificate);
        List<BizCertificate> list = bizCertificateService.getList(bizCertificate);
        ExcelUtil<BizCertificate> util = new ExcelUtil<BizCertificate>(BizCertificate.class);
        util.exportExcel(response, list, "合格证数据");
    }

    /**
     * 获取合格证详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:certificate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizCertificateService.getById(id));
    }

    /**
     * 新增合格证
     */
    @PreAuthorize("@ss.hasPermi('business:certificate:add')")
    @Log(title = "合格证", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizCertificate bizCertificate) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(bizCertificate);
        return toAjax(bizCertificateService.save(bizCertificate));
    }

    /**
     * 修改合格证
     */
    @PreAuthorize("@ss.hasPermi('business:certificate:edit')")
    @Log(title = "合格证", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizCertificate bizCertificate) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(bizCertificate);
        return toAjax(bizCertificateService.updateById(bizCertificate));
    }

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

    @GetMapping("getDayworkList")
    public TableDataInfo getDayworkList(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(bizDaywork);
        startPage();
        List<BizDaywork> list = bizDayworkService.getCertificateList(bizDaywork);
        return getDataTable(list);
    }

    // 生成二维码和条形码
    @PostMapping("/generateSingle")
    @Log(title = "生成二维码和条形码", businessType = BusinessType.UPDATE)
    @Transactional()
    public AjaxResult generateSingle(@RequestBody BizCertificate bizCertificate) throws NoSuchFieldException, IllegalAccessException
    {
        String barcode = "2311199069";
        String qrcode = barcode + "!" + bizCertificate.getLotCode() + "!" + bizCertificate.getProductCode() +"!" + bizCertificate.getDrawingNumber() + "!" + bizCertificate.getSpecification() + "!" + bizCertificate.getLabelNumber() + "!" + bizCertificate.getPackageTypeCode() + "!" + (new DateTime()).toString("yyyy-MM-dd") + "!!";

        bizCertificate = generateQrCode(qrcode, barcode, bizCertificate);
        bizCertificate = generateBarCode(barcode, barcode, bizCertificate);
        return success(bizCertificateService.saveOrUpdate(bizCertificate));
    }

    @PostMapping("/generate")
    @Log(title = "生成二维码和条形码", businessType = BusinessType.UPDATE)
    @Transactional()
    public AjaxResult generate(@RequestBody BizCertificate bizCertificate)
    {
        BizPackageResourceGroup bizPackageResourceGroup = bizPackageResourceGroupService.getById(bizCertificate.getPackageResourceGroupId());
        int currentLineNumber = Integer.parseInt(bizPackageResourceGroup.getCode());
        List<BizCertificateLot> lots = new ArrayList<>();
        for (int i = 0; i < bizCertificate.getPrintPages(); i++) {
            String barcode = bizPackageResourceGroup.getYear() + bizCertificate.getDeptNo() + bizPackageResourceGroup.getPackageLineNo() + String.format("%06d", (++currentLineNumber));
            String qrcode = barcode + "!" + bizCertificate.getLotCode() + "!" + bizCertificate.getProductCode() +"!" + bizCertificate.getDrawingNumber() + "!" + bizCertificate.getSpecification() + "!" + bizCertificate.getLabelNumber() + "!" + bizCertificate.getPackageTypeCode() +"!" + (new DateTime()).toString("yyyy-MM-dd") + "!!";
            BizCertificateLot lot = new BizCertificateLot();
            lot.setCertificateId(bizCertificate.getId());
            lot.setBarcode(barcode);
            lot.setQrcode(qrcode);
            lot = generateQrCode(qrcode, barcode, lot, bizCertificate);
            lot = generateBarCode(barcode, barcode, lot, bizCertificate);
            if (i == 0) {
                bizCertificate.setStartCode(barcode);
            }
            if (i == (bizCertificate.getPrintPages() - 1)) {
                bizCertificate.setEndCode(barcode);
            }
            lots.add(lot);
        }
        bizCertificate.setGenerateTime(new Date());
        bizPackageResourceGroup.setCode(String.format("%06d", currentLineNumber));
        bizPackageResourceGroupService.updateById(bizPackageResourceGroup);
        bizCertificateService.saveOrUpdate(bizCertificate);
        bizCertificateLotService.saveBatch(lots);
        bizCertificate.setLots(lots);

        return success(bizCertificate);
    }


    BizCertificate generateQrCode(String content, String fileName, BizCertificate bizCertificate) {
        BufferedImage qrImage = QrCodeDemo.createQrCode(null, "二维码", content, "" );
        String dir = uploadPath + "qcCode/certificate/" + bizCertificate.getId() +
                "/qrcode/";
        // 判断文件夹是否存在，假设不存在创建你文件夹
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String path = uploadPath + "qcCode/certificate/" + bizCertificate.getId() +
                "/qrcode/" + fileName + ".png";
        bizCertificate.setQrcodeUrl("/profile/upload/qcCode/certificate/" + bizCertificate.getId() +
                "/qrcode/" + fileName + ".png");
        QrCodeDemo.createImage(qrImage, path);
        return bizCertificate;
    }
    BizCertificate generateBarCode(String content, String fileName, BizCertificate bizCertificate) {
        String dir = uploadPath + "qcCode/certificate/" + bizCertificate.getId() +
                "/barcode/";
        // 判断文件夹是否存在，假设不存在创建你文件夹
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String barPatch = uploadPath + "qcCode/certificate/" + bizCertificate.getId() + "/barcode/" + fileName + ".png";
        BufferedImage barImage = BarCodeDemo.createQrCode(null, "条形码", content, "");
        bizCertificate.setBarcodeUrl("/profile/upload/qcCode/certificate/" + bizCertificate.getId() +
                "/barcode/" + fileName + ".png");
        BarCodeDemo.createImage(barImage, barPatch);
        return bizCertificate;
    }

    BizCertificateLot generateQrCode(String content, String fileName, BizCertificateLot lot, BizCertificate bizCertificate) {
        BufferedImage qrImage = QrCodeDemo.createQrCode(null, "二维码", content, "" );
        String dir = uploadPath + "qcCode/certificate/" + bizCertificate.getId() +
                "/qrcode/";
        // 判断文件夹是否存在，假设不存在创建你文件夹
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String path = uploadPath + "qcCode/certificate/" + bizCertificate.getId() +
                "/qrcode/" + fileName + ".png";
        lot.setQrcodeUrl("/profile/upload/qcCode/certificate/" + bizCertificate.getId() +
                "/qrcode/" + fileName + ".png");
        QrCodeDemo.createImage(qrImage, path);
        return lot;
    }
    BizCertificateLot generateBarCode(String content, String fileName, BizCertificateLot lot, BizCertificate bizCertificate) {
        String dir = uploadPath + "qcCode/certificate/" + bizCertificate.getId() +
                "/barcode/";
        // 判断文件夹是否存在，假设不存在创建你文件夹
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String barPatch = uploadPath + "qcCode/certificate/" + bizCertificate.getId() + "/barcode/" + fileName + ".png";
        BufferedImage barImage = BarCodeDemo.createQrCode(null, "条形码", content, "");
        lot.setBarcodeUrl("/profile/upload/qcCode/certificate/" + bizCertificate.getId() +
                "/barcode/" + fileName + ".png");
        BarCodeDemo.createImage(barImage, barPatch);
        return lot;
    }
    @Log(title = "合格证打印", businessType = BusinessType.EXPORT)
    @PostMapping("/printPdfSingle")
    public void printPdfSingle(BizCertificate bizCertificate, HttpServletResponse response) throws IOException, TemplateException, freemarker.template.TemplateException {
        List<BizCertificate> lots = new ArrayList<>();
        Map<String, Object> paramMap = new HashMap<>();
        //cdms.bmp位图（黑白）  logo.png图片(彩)
        paramMap.put("logo", baseUrl + "/profile/logo/" + "cdms.bmp");
        paramMap.put("lots", lots);
        bizCertificate.setQrcodeUrl2Src(baseUrl + bizCertificate.getQrcodeUrl());
        bizCertificate.setBarcodeUrl2Src(baseUrl + bizCertificate.getBarcodeUrl());
        lots.add(bizCertificate);
        Writer out = new StringWriter();
        // 获取模板地址
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("certificate.html");
        template.process(paramMap, out);
        out.flush();
        out.close();
        String templateContent = out.toString();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        String fileName = "合格证";
        response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes()));
        byte[] resources = PdfUtil.html2Pdf(templateContent);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(resources);
        outputStream.close();
    }

    @Log(title = "合格证打印", businessType = BusinessType.EXPORT)
    @PostMapping("/printPdf")
    @Transactional
    public void printPdf(BizCertificate bizCertificate, HttpServletResponse response) throws IOException, TemplateException, freemarker.template.TemplateException {
        List<BizCertificateLot> lots = bizCertificateLotService.query().eq("certificate_id", bizCertificate.getId()).list();
        lots.forEach(l -> {
            l.setQrcodeUrl2Src(baseUrl + l.getQrcodeUrl());
            l.setBarcodeUrl2Src(baseUrl + l.getBarcodeUrl());
        });
        Map<String, Object> paramMap = new HashMap<>();
        //cdms.bmp位图（黑白）  logo.png图片(彩)
        paramMap.put("logo", baseUrl + "/profile/logo/" + "cdms.bmp");
        paramMap.put("lots", lots);
        paramMap.put("certificate", bizCertificate);
        bizCertificate.setQrcodeUrl2Src(baseUrl + bizCertificate.getQrcodeUrl());
        bizCertificate.setBarcodeUrl2Src(baseUrl + bizCertificate.getBarcodeUrl());
        bizCertificate.setPrintTime(new Date());
//        lots.add(bizCertificate);
        Writer out = new StringWriter();
        // 获取模板地址
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("certificate.html");
        template.process(paramMap, out);
        out.flush();
        out.close();
        String templateContent = out.toString();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        String fileName = "合格证";
        response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes()));
        byte[] resources = PdfUtil.html2Pdf(templateContent);
        bizCertificateService.updateById(bizCertificate);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(resources);
        outputStream.close();
    }

    @Log(title = "新建合格证", businessType = BusinessType.SELECT)
    @PostMapping("/newCertificate")
    public AjaxResult newCertificate(@RequestBody BizDaywork bizDaywork)
    {
        // 获取BizDaywork
        BizCertificate certificate = new BizCertificate();
        BizProductionPlanDetail bizProductionPlanDetail = bizProductionPlanDetailService.getById(bizDaywork.getProductionPlanDetailId());
        certificate.setId(snowflakeIdWorker.nextId());
        certificate.setCompanyId(bizProductionPlanDetail.getCompanyId());
        certificate.setCustomerName(bizProductionPlanDetail.getCompanyAlias());
        certificate.setDayworkId(bizDaywork.getId());
        certificate.setLotCode(bizDaywork.getLotCode());
        certificate.setProductCode(bizProductionPlanDetail.getProductCode());
        certificate.setLotId(bizDaywork.getLotId());
        certificate.setDrawingNumber(bizProductionPlanDetail.getDrawingNumber());
        certificate.setType("标准合格证");
        certificate.setSpecification(bizProductionPlanDetail.getSpecification());
        certificate.setProductDescription(bizProductionPlanDetail.getProductDescription());
        certificate.setProductionPlanDetailId(bizProductionPlanDetail.getId());
        certificate.setProductId(bizDaywork.getProductId());
        certificate.setNumber(bizDaywork.getTemporaryProcessQualifiedNum());
        certificate.setPackageNumber(bizDaywork.getTemporaryProcessQualifiedNum());
        certificate.setTenantId(getLoginUser().getTenantId());
        certificate.setPrintDate(new Date());
        certificate.setFactoryName("德迈仕");
        if (bizDaywork.getPackageResourceGroupId() != null && !bizDaywork.getPackageResourceGroupId().equals(0L)) {
            BizPackageResourceGroup bizPackageResourceGroup = bizPackageResourceGroupService.getById(bizDaywork.getPackageResourceGroupId());
            SysDept dept = sysDeptService.selectDeptById(bizPackageResourceGroup.getDeptId());
            certificate.setDeptName(dept.getDeptName());
            certificate.setDeptId(bizPackageResourceGroup.getDeptId());
            certificate.setPackageLineNo(bizPackageResourceGroup.getPackageLineNo().toString());
            certificate.setPackageResourceGroupId(bizPackageResourceGroup.getId());
            certificate.setPackageResourceGroupName(bizPackageResourceGroup.getName());
            certificate.setDeptNo(bizPackageResourceGroup.getDeptNo().toString());
            certificate.setYear(bizPackageResourceGroup.getYear());
        }
        BizCompanyProductPackage packageConditions = new BizCompanyProductPackage();
        packageConditions.setProductId(certificate.getProductId());
        packageConditions.setCompanyId(certificate.getCompanyId());
        List<BizCompanyProductPackage> bizCompanyProductPackages = bizCompanyProductPackageService.getList(packageConditions);
        if (bizCompanyProductPackages.size() == 1) {
            certificate.setPackageCode(bizCompanyProductPackages.get(0).getPackageCode());
            certificate.setPackageStandard(bizCompanyProductPackages.get(0).getPackageStandard());
            certificate.setPackageId(bizCompanyProductPackages.get(0).getAccessoriesId());
            certificate.setPackageTypeCode(bizCompanyProductPackages.get(0).getPackageTypeCode());
        }
        return success(certificate);
    }

    @Log(title="复制打印合格证", businessType = BusinessType.SELECT)
    @PostMapping("/copyCertificate")
    public AjaxResult copyCertificate(@RequestBody BizCertificate bizCertificate) {
        BizCertificate newCertificate = new BizCertificate(bizCertificate);
        newCertificate.setId(snowflakeIdWorker.nextId());
        return success(newCertificate);
    }

}
