package com.zehong.web.controller.externaldocking.lpggas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.domain.Encryption;
import com.zehong.system.domain.TLpgGasBottleFiles;
import com.zehong.system.service.ITLpgGasBottleFilesService;
import com.zehong.web.controller.tool.DESEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 液化气-外部对接controller
 */
@RestController
@RequestMapping("/api/externaldocking")
public class lpgGasController {

    /**
     * 气瓶档案
     */
    @Autowired
    private ITLpgGasBottleFilesService tLpgGasBottleFilesService;

    @Value("${externalDockingLpgGas}")
    private String externalDockingLpgGas;

    /**
     * 创建 气瓶档案接口
     * @return r
     */
    @PostMapping("/createLpgGasBottleFiles")
    public AjaxResult createLpgGasBottleFiles(@RequestBody Encryption encryption){

        DESEncoder desEncoder=new DESEncoder();

        String data = encryption.getData();

        String decrypt = desEncoder.decrypt(data, externalDockingLpgGas);

        int successNum = 0;
        int errorNum = 0;

        if (StringUtils.isNotBlank(decrypt)) {

            JSONArray jsonArray = JSON.parseArray(decrypt);

            String js= JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);

            List<JSONObject> list = JSONObject.parseArray(js,JSONObject.class);

            List<TLpgGasBottleFiles> lpgGasBottleFiles = new ArrayList<>();
            for (int i=0;i<list.size();i++){
                TLpgGasBottleFiles lpgGasBottleFiles1 = new TLpgGasBottleFiles();

                String dateFormat = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

                System.out.println(list.get(i));
                JSONObject jsonObject = list.get(i);

                // 气瓶条码
                String qrcode = jsonObject.getString("qrcode");
                if(StringUtils.isBlank(qrcode)) {
                    errorNum++;
                    continue;
                }
                // 生产日期
                String makeDate = jsonObject.getString("makeDate") == null ? "" : jsonObject.getString("makeDate");
                if(StringUtils.isNotBlank(makeDate) && !isValidDate(sdf,makeDate)) {
                    errorNum++;
                    continue;
                }
                // 上检日期
                String pchkDate = jsonObject.getString("pchkDate") == null ? "" : jsonObject.getString("pchkDate");
                if(StringUtils.isNotBlank(pchkDate) && !isValidDate(sdf,pchkDate)) {
                    errorNum++;
                    continue;
                }
                // 下检日期
                String nchkDate = jsonObject.getString("nchkDate") == null ? "" : jsonObject.getString("nchkDate");
                if(StringUtils.isNotBlank(nchkDate) && !isValidDate(sdf,nchkDate)) {
                    errorNum++;
                    continue;
                }
                // 生产日期
                String productDate = jsonObject.getString("productDate") == null ? "" : jsonObject.getString("productDate");
                if(StringUtils.isNotBlank(productDate) && !isValidDate(sdf,productDate)) {
                    errorNum++;
                    continue;
                }
                // 报废日期
                String discardDate = jsonObject.getString("discardDate") == null ? "" : jsonObject.getString("discardDate");
                if(StringUtils.isNotBlank(discardDate) && !isValidDate(sdf,discardDate)) {
                    errorNum++;
                    continue;
                }
                // 安全评价日期
                String safeJudgeDate = jsonObject.getString("safeJudgeDate") == null ? "" : jsonObject.getString("safeJudgeDate");
                if(StringUtils.isNotBlank(safeJudgeDate) && !isValidDate(sdf,safeJudgeDate)) {
                    errorNum++;
                    continue;
                }
                lpgGasBottleFiles1.setQrcode(qrcode);
                try {
                    lpgGasBottleFiles1.setMakeDate(sdf.parse(makeDate));
                    lpgGasBottleFiles1.setPchkDate(sdf.parse(pchkDate));
                    lpgGasBottleFiles1.setNchkDate(sdf.parse(nchkDate));
                    lpgGasBottleFiles1.setProductDate(sdf.parse(productDate));
                    lpgGasBottleFiles1.setDiscardDate(sdf.parse(discardDate));
                    lpgGasBottleFiles1.setSafeJudgeDate(sdf.parse(safeJudgeDate));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                // 生产(制造单位)
                String makeInfo = jsonObject.getString("makeInfo") == null ? "" : jsonObject.getString("makeInfo");
                lpgGasBottleFiles1.setMakeInfo(makeInfo);
                // 登记证号
                String regCode = jsonObject.getString("regCode") == null ? "" : jsonObject.getString("regCode");
                lpgGasBottleFiles1.setRegCode(regCode);
                // 产品编号
                String equNo = jsonObject.getString("equNo") == null ? "" : jsonObject.getString("equNo");
                lpgGasBottleFiles1.setEquNo(equNo);
                // 设备类型
                String equType = jsonObject.getString("equType") == null ? "" : jsonObject.getString("equType");
                lpgGasBottleFiles1.setEquType(equType);
                // 充装介质
                String medium = jsonObject.getString("medium") == null ? "" : jsonObject.getString("medium");
                lpgGasBottleFiles1.setMedium(medium);

                // 单位内编号
                String selfId = jsonObject.getString("selfId") == null ? "" : jsonObject.getString("selfId");
                lpgGasBottleFiles1.setSelfId(selfId);
                // 压力
                String pressure = jsonObject.getString("pressure") == null ? "" : jsonObject.getString("pressure");

                if (StringUtils.isNotBlank(pressure)) {
                    try {
                        BigDecimal bigDecimal = new BigDecimal(pressure);
                        lpgGasBottleFiles1.setPressure(bigDecimal);
                    } catch (NumberFormatException  e) {
                        lpgGasBottleFiles1.setPressure(BigDecimal.ZERO);
                    }
                }

                // 体积
                String volume = jsonObject.getString("volume") == null ? "" : jsonObject.getString("volume");
                if (StringUtils.isNotBlank(volume)) {
                    try {
                        BigDecimal bigDecimal = new BigDecimal(volume);
                        lpgGasBottleFiles1.setVolume(bigDecimal);
                    } catch (NumberFormatException  e) {
                        lpgGasBottleFiles1.setVolume(BigDecimal.ZERO);
                    }
                }

                // 电子标签
                String appId = jsonObject.getString("appId") == null ? "" : jsonObject.getString("appId");
                lpgGasBottleFiles1.setAppId(appId);
                // 使用单位
                String buildUser = jsonObject.getString("buildUser") == null ? "" : jsonObject.getString("buildUser");
                lpgGasBottleFiles1.setBuildUser(buildUser);

                // 公称压力Mpa
                String gpressure = jsonObject.getString("gpressure") == null ? "" : jsonObject.getString("gpressure");
                if (StringUtils.isNotBlank(gpressure)) {
                    try {
                        BigDecimal bigDecimal = new BigDecimal(gpressure);
                        lpgGasBottleFiles1.setGpressure(bigDecimal);
                    } catch (NumberFormatException e) {
                        lpgGasBottleFiles1.setGpressure(BigDecimal.ZERO);
                    }
                }

                // 水试验压力Mpa
                String wpressure = jsonObject.getString("wpressure") == null ? "" : jsonObject.getString("wpressure");

                if (StringUtils.isNotBlank(wpressure)) {

                    try {
                        BigDecimal bigDecimal = new BigDecimal(wpressure);
                        lpgGasBottleFiles1.setWpressure(bigDecimal);
                    } catch (NumberFormatException e) {
                        lpgGasBottleFiles1.setWpressure(BigDecimal.ZERO);
                    }
                }

                // 标准重量KG
                String selfWeight = jsonObject.getString("selfWeight") == null ? "" : jsonObject.getString("selfWeight");
                if (StringUtils.isNotBlank(selfWeight)) {
                    try {
                        BigDecimal bigDecimal = new BigDecimal(selfWeight);
                        lpgGasBottleFiles1.setSelfWeight(bigDecimal);
                    }catch (NumberFormatException e) {
                        lpgGasBottleFiles1.setSelfWeight(BigDecimal.ZERO);
                    }
                }
                // 壁厚mm
                String thickness = jsonObject.getString("thickness") == null ? "" : jsonObject.getString("thickness");

                if (StringUtils.isNotBlank(thickness)) {
                    try {
                        BigDecimal bigDecimal = new BigDecimal(thickness);
                        lpgGasBottleFiles1.setThickness(bigDecimal);
                    } catch (NumberFormatException e) {
                        lpgGasBottleFiles1.setThickness(BigDecimal.ZERO);
                    }
                }

                // 气瓶许可证号
                String permitNo = jsonObject.getString("permitNo") == null ? "" : jsonObject.getString("permitNo");
                lpgGasBottleFiles1.setPermitNo(permitNo);
                // 阀类型名称
                String valveName = jsonObject.getString("valveName") == null ? "" : jsonObject.getString("valveName");
                lpgGasBottleFiles1.setValveName(valveName);
                // 钢瓶规格名称
                String botSpecName = jsonObject.getString("botSpecName") == null ? "" : jsonObject.getString("botSpecName");
                lpgGasBottleFiles1.setBotSpecName(botSpecName);
                //  钢瓶型号
                String bottleType = jsonObject.getString("bottleType") == null ? "" : jsonObject.getString("bottleType");
                lpgGasBottleFiles1.setBottleType(bottleType);
                //  已检验次数
                String inspectedTimes = jsonObject.getString("inspectedTimes") == null ? "" : jsonObject.getString("inspectedTimes");

                if (StringUtils.isNotBlank(inspectedTimes)) {
                    try {
                        long l = Long.parseLong(inspectedTimes);
                        lpgGasBottleFiles1.setInspectedTimes(l);
                    } catch (NumberFormatException e) {
                        lpgGasBottleFiles1.setInspectedTimes(0L);
                    }
                }

                //  阀厂家
                String valveManuFacturer = jsonObject.getString("valveManuFacturer") == null ? "" : jsonObject.getString("valveManuFacturer");
                lpgGasBottleFiles1.setValveManuFacturer(valveManuFacturer);

                // 检验标牌(有/无)
                String inspectionLabel = jsonObject.getString("inspectionLabel") == null ? "" : jsonObject.getString("inspectionLabel");
                lpgGasBottleFiles1.setInspectionLabel(inspectionLabel);
                // 第三方标签
                String thirdPartyLabel = jsonObject.getString("thirdPartyLabel") == null ? "" : jsonObject.getString("thirdPartyLabel");
                lpgGasBottleFiles1.setThirdPartyLabel(thirdPartyLabel);
                //  孔洞码
                String holeCode = jsonObject.getString("holeCode") == null ? "" : jsonObject.getString("holeCode");
                lpgGasBottleFiles1.setHoleCode(holeCode);
                //  存储类型(气相/液相)
                String bottleStorageType = jsonObject.getString("bottleStorageType") == null ? "" : jsonObject.getString("bottleStorageType");
                lpgGasBottleFiles1.setBottleStorageType(bottleStorageType);

                //  钢瓶交付文件照片
                String payImage = jsonObject.getString("payImage") == null ? "" : jsonObject.getString("payImage");
                if(StringUtils.isNotBlank(payImage) && isBase64Image(payImage)) {
                    lpgGasBottleFiles1.setPayImage(payImage);
                }

                //  检验质量证明书照片
                String batchImage = jsonObject.getString("batchImage") == null ? "" : jsonObject.getString("batchImage");

                if (StringUtils.isNotBlank(batchImage) && isBase64Image(batchImage)) {
                    lpgGasBottleFiles1.setBatchImage(batchImage);
                }

                //  制造监督检验证书照片
                String deviceImage = jsonObject.getString("deviceImage") == null ? "" : jsonObject.getString("deviceImage");

                if (StringUtils.isNotBlank(deviceImage) && isBase64Image(deviceImage)) {
                    lpgGasBottleFiles1.setDeviceImage(deviceImage);
                }

                //  检验报告照片
                String checkImage = jsonObject.getString("checkImage") == null ? "" : jsonObject.getString("checkImage");

                if (StringUtils.isNotBlank(checkImage) && isBase64Image(checkImage)) {
                    lpgGasBottleFiles1.setCheckImage(checkImage);
                }

                //  钢瓶信息照片
                String botImage = jsonObject.getString("botImage") == null ? "" : jsonObject.getString("botImage");
                if (StringUtils.isNotBlank(botImage) && isBase64Image(botImage)) {
                    lpgGasBottleFiles1.setBotImage(botImage);
                }

                successNum++;
                lpgGasBottleFiles.add(lpgGasBottleFiles1);
            }

            if (lpgGasBottleFiles.size() > 0) {
                int i = tLpgGasBottleFilesService.externalDockingCreateLpgGasBottleFiles(lpgGasBottleFiles);
                if (i < 1) {
                    return AjaxResult.error("入库异常！！！");
                }
            }

        } else {
            return AjaxResult.error("数据异常");
        }

        StringBuilder sb = new StringBuilder();
        if (errorNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条");
            return AjaxResult.success(sb.toString());
        }
        sb.append("成功：").append(successNum).append("条");
        return AjaxResult.success(sb.toString());
    }

    /**
     * 判断是否是正确日期
     * @param dateString  d
     * @return r
     */
    public static boolean isValidDate(SimpleDateFormat sdf,String dateString) {
        sdf.setLenient(false); // 设置为不宽松模式，严格按照指定的格式解析
        try {
            Date date = sdf.parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    /**
     * 判断给定的字符串是否是Base64编码的图片
     *
     * @param base64String 要检查的字符串
     * @return 如果是Base64编码的，则返回true；否则返回false。
     */
    public static boolean isBase64Image(String base64String) {
        try {
            // 解码Base64字符串为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64String);

            // 尝试从字节数组读取图片
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));

            // 如果成功读取到图片，则返回true
            return image != null;
        } catch (IOException e) {
            // 如果在解码或读取图片时发生异常，则认为不是有效的图片文件
            return false;
        }
    }


}
