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

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.*;
import com.zehong.system.mapper.*;
import com.zehong.system.service.DecryptService;
import com.zehong.system.service.ITLpgThirdPartyDockingInterfaceRecordService;
import com.zehong.web.controller.externaldocking.lpggas.lpgGasController;
import com.zehong.web.controller.tool.DESEncoder;
import org.springframework.beans.factory.annotation.Autowired;
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.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 入户安检-外部对接controller
 */
@RestController
@RequestMapping("/api/detection")
public class RhajController {

    @Resource
    DecryptService decryptService;

    @Resource
    private TEnterpriseInfoMapper tEnterpriseInfoMapper;

    @Resource
    private ITLpgThirdPartyDockingInterfaceRecordService lpgThirdPartyDockingInterfaceRecordService;

    @Resource
    private lpgGasController lpgGasService;
    @Autowired
    private TSpecialUserMapper specialUserMapper;
    @Autowired
    private TDetectorUserMapper detectorUserMapper;
    @Autowired
    private THiddenDangerStandingBookMapper hiddenDangerStandingBookMapper;
    @Autowired
    private TInspectReportMapper inspectReportMapper;

    /**
     * 验证编码以及格式
     * @param encryption
     * @return
     */
    public AjaxResult isFormatVerification(Encryption encryption,keyInformation selectkey){
        if(selectkey == null) {

            return  AjaxResult.error("企业编码不存在！！！");
        }
        TEnterpriseInfo tEnterpriseInfo = tEnterpriseInfoMapper.selectTEnterpriseInfoById(selectkey.getEnterpriseId());

        if (tEnterpriseInfo == null) {
            return  AjaxResult.error("监管平台配置企业信息不存在！！！");
        }

        DESEncoder desEncoder = new DESEncoder();

        List<JSONObject> list = new ArrayList<>();

        String decrypt = desEncoder.decrypt(encryption.getData(), selectkey.getSecretKey());
        if (StringUtils.isNotBlank(decrypt)) {
            JSONArray jsonArray = JSON.parseArray(decrypt);

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

            list = JSONObject.parseArray(js, JSONObject.class);

            if(list.size() > 500) {
                return  AjaxResult.error("每次最多处理500条数据");
            }
        }
        return  AjaxResult.success(list);
    }

    /**
     * 创建 隐患跟踪接口
     * @return r
     */
    @PostMapping("/createHiddenTrack")
    public AjaxResult createHiddenTrack(@RequestBody Encryption encryption) {
        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());
        AjaxResult result = isFormatVerification(encryption,selectkey);
        if((int)result.get("code")!=200){
            return result;
        }

        int successNum = 0;
        int errorNum = 0;

        List<JSONObject> list = (List<JSONObject>) result.get("data");

        List<THiddenDangerStandingBook> hiddenlist = new ArrayList<>();
        // 需要更新的数据
        THiddenDangerStandingBook hidden;

        // 接口保存记录
        List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
        TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
        for (int i = 0; i < list.size(); i++) {
            hidden = new THiddenDangerStandingBook();

            JSONObject jsonObject = list.get(i);
            //判断数据是否合格
            String resultstr = isqualifiedHidden(jsonObject);
            if (!resultstr.equals("success")) {
                lpgThirdPartyDockingInterfaceRecord = lpgGasService.errorRecord("createHiddenTrack", jsonObject.toJSONString(),
                        resultstr, encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                errorNum++;
                continue;
            }
            try{
                hidden.setHiddenTitle(jsonObject.getString("hiddenTitle"));
                hidden.setHiddenContent(jsonObject.getString("hiddenContent"));
                hidden.setHiddenLocation(jsonObject.getString("hiddenLocation"));
                hidden.setSource(jsonObject.getString("source"));
                hidden.setLongitude(new BigDecimal(jsonObject.getString("longitude")));
                hidden.setLatitude(new BigDecimal(jsonObject.getString("latitude")));
                hidden.setHiddenType(jsonObject.getString("hiddenLevel"));
                hidden.setHiddenTroubleType(jsonObject.getString("hiddenTroubleType"));
                hidden.setHiddenFindPeople(jsonObject.getString("hiddenFindPeople"));
                hidden.setHiddenFindDate(dateBystr(jsonObject.getString("hiddenFindDate"),"yyyy-MM-dd HH:mm:ss"));
                hidden.setDealPlan(jsonObject.getString("dealResult"));
                hidden.setBeyondEnterpriseId(selectkey.getEnterpriseId());
                hidden.setRemediation(jsonObject.getString("remediation"));
                hidden.setCreateTime(new Date());
                hidden.setRemarks(jsonObject.getString("remarks"));
            }catch (Exception e){
                throw new RuntimeException(e);
            }
            hiddenlist.add(hidden);
            lpgThirdPartyDockingInterfaceRecord = lpgGasService.successRecord("createLpgVehicleInfo", jsonObject.toJSONString(), encryption.getQybm());
            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
            successNum++;
        }

        if (hiddenlist.size() > 0) {
            // 新增的新增
            hiddenDangerStandingBookMapper.inserts(hiddenlist);
        }

        if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
            lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
        }
        return AjaxResult.success(returnstr(successNum,errorNum,0));
    }


    /**
     * 创建 特殊用户接口
     * @return r
     */
    @PostMapping("/createSpecailUser")
    public AjaxResult createSpecailUser(@RequestBody Encryption encryption) {
        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());
        AjaxResult result = isFormatVerification(encryption,selectkey);
        if((int)result.get("code")!=200){
            return result;
        }

        int successNum = 0;
        int errorNum = 0;
        int repeatNum = 0;

        List<JSONObject> list = (List<JSONObject>) result.get("data");

        List<TSpecialUser> specialUsers = new ArrayList<>();
        // 需要更新的数据
        TSpecialUser specialUser;

        // 接口保存记录
        List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
        TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
        for (int i = 0; i < list.size(); i++) {
            specialUser = new TSpecialUser();

            JSONObject jsonObject = list.get(i);
            //判断数据是否合格
            String resultstr = isqualified(jsonObject);
            if (!resultstr.equals("success")) {
                lpgThirdPartyDockingInterfaceRecord = lpgGasService.errorRecord("createSpecailUser", jsonObject.toJSONString(),
                        resultstr, encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                errorNum++;
                continue;
            }
            TDetectorUser user = detectorUserMapper.selectUserByOwnId(jsonObject.getString("userOwnId"));
            if(user==null){
                lpgThirdPartyDockingInterfaceRecord = lpgGasService.errorRecord("createSpecailUser", jsonObject.toJSONString(),
                        "用户不存在", encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                errorNum++;
                continue;
            }
            try{
                specialUser.setUserId(user.getUserId());
                specialUser.setUserType(jsonObject.getString("userType"));
                specialUser.setControlPlan(jsonObject.getString("controlPlan"));
                specialUser.setConStartTime(dateBystr(jsonObject.getString("conStartTime"),"yyyy-MM-dd"));
                specialUser.setConEndTime(dateBystr(jsonObject.getString("conEndTime"),"yyyy-MM-dd"));
                specialUser.setCreateTime(new Date());
                specialUser.setUpdateTime(dateBystr(jsonObject.getString("updateTime"),"yyyy-MM-dd HH:mm:ss"));
                specialUser.setRemark(jsonObject.getString("remark"));
                specialUser.setUserOwnId(jsonObject.getString("userOwnId"));
                specialUser.setEnterpriseId(selectkey.getEnterpriseId());
            }catch (Exception e){
                throw new RuntimeException(e);
            }
            specialUsers.add(specialUser);
            lpgThirdPartyDockingInterfaceRecord = lpgGasService.successRecord("createLpgVehicleInfo", jsonObject.toJSONString(), encryption.getQybm());
            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
            successNum++;
        }

        if (specialUsers.size() > 0) {
            // 新增的新增
            specialUserMapper.inserts(specialUsers);
        }

        if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
            lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
        }
        return AjaxResult.success(returnstr(successNum,errorNum,repeatNum));
    }

    /**
     * 入户安检结果上报接口
     * @return r
     */
    @PostMapping("/createInspectResult")
    public AjaxResult createInspectResult(@RequestBody Encryption encryption) {
        keyInformation selectkey = decryptService.selectkey(encryption.getQybm());
        AjaxResult result = isFormatVerification(encryption,selectkey);
        if((int)result.get("code")!=200){
            return result;
        }

        int successNum = 0;
        int errorNum = 0;

        List<JSONObject> list = (List<JSONObject>) result.get("data");

        List<TInspectReport> inspectReports = new ArrayList<>();
        // 需要更新的数据
        TInspectReport inspectReport;

        // 接口保存记录
        List<TLpgThirdPartyDockingInterfaceRecord> lpgThirdPartyDockingInterfaceRecords = new ArrayList<>();
        TLpgThirdPartyDockingInterfaceRecord lpgThirdPartyDockingInterfaceRecord;
        for (int i = 0; i < list.size(); i++) {
            inspectReport = new TInspectReport();

            JSONObject jsonObject = list.get(i);
            //判断数据是否合格
            String resultstr = isqualifiedInspect(jsonObject);
            if (!resultstr.equals("success")) {
                lpgThirdPartyDockingInterfaceRecord = lpgGasService.errorRecord("createInspectResult", jsonObject.toJSONString(),
                        resultstr, encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                errorNum++;
                continue;
            }
            TDetectorUser user = detectorUserMapper.selectUserByOwnId(jsonObject.getString("userOwnId"));
            if(user==null){
                lpgThirdPartyDockingInterfaceRecord = lpgGasService.errorRecord("createSpecailUser", jsonObject.toJSONString(),
                        "用户不存在", encryption.getQybm());
                lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
                errorNum++;
                continue;
            }
            try{
                inspectReport.setUserNo(user.getUserId());
                inspectReport.setAnnual(Integer.parseInt(jsonObject.getString("annual")));
                inspectReport.setSecurityCodeIn(jsonObject.getString("securityCodeIn"));
                inspectReport.setSecurityCode(jsonObject.getString("securityCode"));
                inspectReport.setUserName(jsonObject.getString("userName"));
                inspectReport.setIndoorTime(jsonObject.getString("indoorTime"));
                inspectReport.setIndoorStatus(jsonObject.getString("indoorStatus"));
                inspectReport.setIndoorStatus(jsonObject.getString("indoorStatus"));
                inspectReport.setVillage(user.getVillageId());
                inspectReport.setHouseNumber(jsonObject.getString("houseNumber"));
                inspectReport.setPhoneNumber(jsonObject.getString("phoneNumber"));
                inspectReport.setCreateTime(new Date());
                inspectReport.setUserOwnId(jsonObject.getString("userOwnId"));
                inspectReport.setCompanyInfoId(selectkey.getEnterpriseId());
            }catch (Exception e){
                throw new RuntimeException(e);
            }
            inspectReports.add(inspectReport);
            lpgThirdPartyDockingInterfaceRecord = lpgGasService.successRecord("createLpgVehicleInfo", jsonObject.toJSONString(), encryption.getQybm());
            lpgThirdPartyDockingInterfaceRecords.add(lpgThirdPartyDockingInterfaceRecord);
            successNum++;
        }

        if (inspectReports.size() > 0) {
            // 新增的新增
            inspectReportMapper.inserts(inspectReports);
        }

        if (lpgThirdPartyDockingInterfaceRecords.size() > 0) {
            lpgThirdPartyDockingInterfaceRecordService.insertBatch(lpgThirdPartyDockingInterfaceRecords);
        }
        return AjaxResult.success(returnstr(successNum,errorNum,0));
    }

    /**
     * 公共返回
     * @param successNum
     * @param errorNum
     * @return
     */
    public String returnstr(int successNum,int errorNum,int repeatNum) {
        StringBuilder sb = new StringBuilder();
        if (errorNum > 0) {
            sb.append("成功：").append(successNum).append("条;失败：").append(errorNum).append("条");
            if(repeatNum>0){
                sb.append(";重复").append(repeatNum).append("条");
            }
            return sb.toString();
        }
        sb.append("成功：").append(successNum).append("条");
        return sb.toString();
    }
    //格式转换
    public Date dateBystr(String datestr, String dateFormat)throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.parse(datestr);
    }
    //格式判断
    public static boolean isValidDate(String format,String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setLenient(false); // 设置为不宽松模式，严格按照指定的格式解析
        try {
            sdf.parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
    //经纬度验证
    public static boolean isValidCoordinate(String coordinate) {
        String regex = "^[0-9]+(\\.[0-9]+)?$"; // 正则表达式
        Pattern pattern = Pattern.compile(regex);
        return  pattern.matcher(coordinate).matches();
    }

    /**
     *  特殊用户数据验证
     * @return
     */
    public String isqualified(JSONObject jsonObject){
        if(jsonObject.getString("userType")==null||jsonObject.getString("userType").length() > 5)return "用户类型不合格！";
        if(jsonObject.getString("controlPlan")==null)return "管控方案不许为空！";
        if(isValidDate(jsonObject.getString("conStartTime"),"yyyy-MM-dd"))return "开始日期不合格！";
        if(isValidDate(jsonObject.getString("conEndTime"),"yyyy-MM-dd"))return "结束日期不合格！";
        if(isValidDate(jsonObject.getString("updateTime"),"yyyy-MM-dd HH:mm:ss"))return "最后修改时间不合格！";
        if(jsonObject.getString("userOwnId")==null)return "用户编号不可为空！";
        return "success";
    }

    /**
     * 隐患跟踪验证
     * @param jsonObject
     * @return
     */
    public String isqualifiedHidden(JSONObject jsonObject){
        if(jsonObject.getString("hiddenTitle")==null||jsonObject.getString("hiddenTitle").length() > 50)return "隐患名称不合格！";
        if(jsonObject.getString("hiddenContent")==null)return "隐患内容不许为空！";
        if(jsonObject.getString("hiddenLocation")==null||jsonObject.getString("hiddenLocation").length() > 100)return "隐患位置不合格！";
        if(jsonObject.getString("source")==null||jsonObject.getString("source").length() > 5)return "隐患来源不合格！";
        if(jsonObject.getString("longitude")==""||!isValidCoordinate(jsonObject.getString("longitude")))return "经度格式不合格！";
        if(jsonObject.getString("latitude")==""||!isValidCoordinate(jsonObject.getString("latitude")))return "纬度格式不合格！";
        if(jsonObject.getString("hiddenLevel")==null||jsonObject.getString("hiddenLevel").length()>5)return "隐患等级格式不合格！";
        if(jsonObject.getString("remediation")==null||jsonObject.getString("remediation").length()>2)return "整治情况格式不合格！";
        if(jsonObject.getString("hiddenFindDate")==null||isValidDate(jsonObject.getString("hiddenFindDate"),"yyyy-MM-dd HH:mm:ss"))return "发现时间格式不合格！";
        return "success";
    }

    public String isqualifiedInspect(JSONObject jsonObject){
        if(jsonObject.getString("annual")==null||!jsonObject.getString("annual").matches("\\d+")||jsonObject.getString("annual").length() > 5)return "年度格式不合格！";
        if(jsonObject.getString("securityCodeIn")==null||jsonObject.getString("securityCodeIn").length()>50)return "安检编码不合格！";
        if(jsonObject.getString("securityCode")==null||jsonObject.getString("securityCode").length()>50)return "外部编码不合格！";
        if(jsonObject.getString("userName")==null||jsonObject.getString("userName").length() > 20)return "用户名称不合格！";
        if(jsonObject.getString("indoorTime")==null||isValidDate(jsonObject.getString("indoorTime"),"yyyy-MM-dd"))return "上门日期格式不合格！";
        if(jsonObject.getString("indoorStatus")==null||jsonObject.getString("indoorStatus").length() > 10)return "状态式不合格！";
        if(jsonObject.getString("houseNumber")==null||jsonObject.getString("houseNumber").length()>100)return "门牌号格式不合格！";
        if(jsonObject.getString("phoneNumber")==null||jsonObject.getString("phoneNumber").length()>100)return "手机号格式不合格！";
        return "success";
    }



}
