package com.yunfeiyun.agmp.fms.controller;

import com.alibaba.fastjson2.JSONObject;
import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.utils.ConfigUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.img.GraphicsCanvas;
import com.yunfeiyun.agmp.common.utils.img.entity.GraphicsCanvasItem;
import com.yunfeiyun.agmp.common.utils.img.enums.BusType;
import com.yunfeiyun.agmp.common.utils.poi.ExcelUtil;
import com.yunfeiyun.agmp.common.web.system.domain.SysConfig;
import com.yunfeiyun.agmp.common.web.system.service.ISysConfigService;
import com.yunfeiyun.agmp.fms.domain.FmsBlock;
import com.yunfeiyun.agmp.fms.domain.TssTracecodeapply;
import com.yunfeiyun.agmp.fms.domain.TssTracecodetpl;
import com.yunfeiyun.agmp.fms.domain.TssTracecodetplparam;
import com.yunfeiyun.agmp.fms.domain.reqvo.TssTraceCodeGenerateReqVo;
import com.yunfeiyun.agmp.fms.domain.reqvo.TssTracecodetplEditReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssTracecodeapplyExportResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssTracecodetplListPreviewResVo;
import com.yunfeiyun.agmp.fms.mapper.TssTracecodetplparamMapper;
import com.yunfeiyun.agmp.fms.service.ITssTracecodetplService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 溯源码模板Controller
 * 
 * @author 杨晓辉
 * @date 2023-07-04
 */
@RestController
@RequestMapping("/tss/tracecodetpl")
public class TssTracecodetplController extends BaseController
{
    @Autowired
    private ITssTracecodetplService tssTracecodetplService;
    @Resource
    private TssTracecodetplparamMapper tssTracecodetplparamMapper;

    @Resource
    private ISysConfigService sysConfigService;

    /**
     * 查询溯源码模板列表
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:list')")
    @GetMapping("/list")
    public AjaxResult list(TssTracecodetpl tssTracecodetpl)
    {

        List<TssTracecodetpl> list = tssTracecodetplService.selectTssTracecodetplList(tssTracecodetpl);
        List<TssTracecodetplListPreviewResVo> resVoList = new ArrayList<>();
        for(TssTracecodetpl item : list){
            TssTracecodetplListPreviewResVo tssTracecodetplListPreviewResVo = new TssTracecodetplListPreviewResVo();
            tssTracecodetplListPreviewResVo.setTracecodetplId(item.getTracecodetplId());
            tssTracecodetplListPreviewResVo.setPreviewImgBase64(tssTracecodetplService.drawTraceCode(item));
            tssTracecodetplListPreviewResVo.setTracecodetplMaxscan(item.getTracecodetplMaxscan());
            resVoList.add(tssTracecodetplListPreviewResVo);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",resVoList);
        jsonObject.put("defaultTplId",sysConfigService.selectConfigByKey(ConfigUtils.ConfigKeyEnum.TRACE_CODE_TPL_DEFAULT_ID.getKey(),1).getConfigValue());
        return AjaxResult.success(jsonObject);
    }

    /**
     * 查询溯源码模板列表
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:preview')")
    @PostMapping("/preview")
    public ResponseEntity<byte[]> preview(@RequestBody TssTracecodetplEditReqVo tssTracecodetplEditReqVo) throws Exception
    {
        TssTracecodetpl tssTracecodetpl = new TssTracecodetpl();
        tssTracecodetpl.setTracecodetplId(tssTracecodetplEditReqVo.getTracecodetplId());
        List<TssTracecodetpl> list = tssTracecodetplService.selectTssTracecodetplList(tssTracecodetpl);
        if(list.isEmpty()){
            throw new BizException(ErrorCode.TSS_TRACE_CODE_TPL_NOT_EXIST);
        }
        tssTracecodetpl = list.get(0);
        TssTracecodetplparam queryParam = new TssTracecodetplparam();
        queryParam.setTracecodetplId(tssTracecodetpl.getTracecodetplId());
        List<TssTracecodetplparam> params = tssTracecodetplparamMapper.selectTssTracecodetplparamList(queryParam);
        List<GraphicsCanvasItem> graphicsCanvasItemList = params.stream().map(item->{
            if(StringUtils.isNotEmpty(tssTracecodetplEditReqVo.getBackground())&&BusType.BACKGROUND.equal(item.getTplparamBustype())){
                item.setTplparamData(tssTracecodetplEditReqVo.getBackground());
            }else if(StringUtils.isNotEmpty(tssTracecodetplEditReqVo.getLogo())&&BusType.LOGO.equal(item.getTplparamBustype())){
                item.setTplparamData(tssTracecodetplEditReqVo.getLogo());
            }
            return item.transToGraphicsCanvasItem();
        }).collect(Collectors.toList());
        GraphicsCanvas graphicsCanvas = new GraphicsCanvas(tssTracecodetpl.getTracecodetplWidth(),tssTracecodetpl.getTracecodetplHeight(),tssTracecodetpl.getTracecodetplBitcolor(),graphicsCanvasItemList);
        graphicsCanvas.appendByGraphicsCanvasItems();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        graphicsCanvas.write( "png", baos);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentLength(baos.size());
        return new ResponseEntity<>(baos.toByteArray(), headers, 200);
    }



    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:test')")
    @GetMapping("/test")
    public ResponseEntity<byte[]> test() throws Exception
    {
        List<TssTracecodetpl> list = tssTracecodetplService.selectTssTracecodetplList(null);
        TssTracecodetpl tssTracecodetpl = list.get(0);
        TssTracecodetplparam queryParam = new TssTracecodetplparam();
        queryParam.setTracecodetplId(tssTracecodetpl.getTracecodetplId());
        List<TssTracecodetplparam> params = tssTracecodetplparamMapper.selectTssTracecodetplparamList(queryParam);
        List<GraphicsCanvasItem> graphicsCanvasItemList = params.stream().map(TssTracecodetplparam::transToGraphicsCanvasItem).collect(Collectors.toList());
        GraphicsCanvas graphicsCanvas = new GraphicsCanvas(tssTracecodetpl.getTracecodetplWidth(),tssTracecodetpl.getTracecodetplHeight(),tssTracecodetpl.getTracecodetplBitcolor(),graphicsCanvasItemList);
        graphicsCanvas.appendByGraphicsCanvasItems();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        graphicsCanvas.write( "png", baos);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentLength(baos.size());
        return new ResponseEntity<>(baos.toByteArray(), headers, 200);
    }


    /**
     * 查询溯源码模板编辑
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:edit')")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody TssTracecodetplEditReqVo tssTracecodetplEditReqVo)
    {
        tssTracecodetplService.updateTssTraceCodeTplBackgroundAndLogo(tssTracecodetplEditReqVo);
        return AjaxResult.success();
    }



    /**
     * 编辑默认溯源码目标标识
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:update:defaultTpl')")
    @PostMapping("/update/defaultTpl")
    public AjaxResult updateDefaultTpl(@RequestBody Map<String,String> map)
    {
        SysConfig sysConfig = sysConfigService.selectConfigByKey(ConfigUtils.ConfigKeyEnum.TRACE_CODE_TPL_DEFAULT_ID.getKey(),1);
        sysConfig.setConfigValue(map.get("tracecodetplId"));
        sysConfigService.updateConfig(sysConfig);
        return AjaxResult.success();
    }


    /**
     * 溯源码生成
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:generate')")
    @PostMapping("/generate")
    public AjaxResult generate(@Valid @RequestBody TssTraceCodeGenerateReqVo tssTracecodetplEditReqVo)
    {

        return AjaxResult.success(tssTracecodetplService.generate(tssTracecodetplEditReqVo));
    }
    /**
     * 下载
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:downland')")
    @GetMapping(value = "/downland",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<InputStreamResource> downland( String tarcecodeapplyBatchno) throws Exception {
        return tssTracecodetplService.downLand(tarcecodeapplyBatchno);
    }

    /**
     * 下载
     */
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:downland:tarcecodeapply')")
    @PostMapping(value = "/downland/tarcecodeapply",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<InputStreamResource> downlandBatch(@RequestBody String[] tarcecodeapplynos) throws Exception {
        return tssTracecodetplService.downLand(tarcecodeapplynos);
    }
    /**
     *  导出二维码
     * */
    @Log(title = "溯源码", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('tss:tracecodetpl:export:tarcecodeapply')")
    @GetMapping(value = "/export/tarcecodeapply",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void export(HttpServletResponse response, String tarcecodeapplyBatchno)
    {
        tssTracecodetplService.export(response,tarcecodeapplyBatchno);
    }

}
