package com.sifang.modules.smallprogram.stategrid.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dfhz.util.WebAppAESUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.esign.cn.tsign.hz.comm.EsignHttpCfgHelper;
import com.sifang.modules.esign.cn.tsign.hz.comm.EsignHttpResponse;
import com.sifang.modules.esign.cn.tsign.hz.enums.EsignRequestType;
import com.sifang.modules.smallprogram.stategrid.utils.StateGridConstants;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StateGridService {


    @Resource
    private CustomerEntryDao customerEntryDao;

    private Logger logger = LoggerFactory.getLogger(getClass());


    public void selectStatus(){
        List<Record> infoBySGStatus = customerEntryDao.findInfoBySGStatus();
        for (Record projectInfo : infoBySGStatus) {
            try {
//                logger.info("=====  电站编码 ： {}", projectInfo.getStr("power_station_code"));
                if (StringUtil.isNotBlank(projectInfo.getStr("generator_no"))){
                    if (findUserInfoFromStateGrid(projectInfo.getStr("province_code"), projectInfo.getStr("generator_no"))) {
                        logger.info("发电户号{}, >>>>  授权成功", projectInfo.getStr("generator_no"));
                    } else {
                        logger.info("发电户号{}, >>>>  授权失败", projectInfo.getStr("generator_no"));
                    }
                }
            } catch (Exception e) {
                    logger.error("同步失败======={}",e);
            }
        }

    }

    /**
     * 用户信息管理查询
     * @param areaCode
     * @param powerGenerationNo
     */

    public Object findUserInfo(String areaCode,String powerGenerationNo ){
        Gson gson=new Gson();
        JSONObject object = new JSONObject();
        Map proComMap = getProjectInfoByPowerGenerationNo(powerGenerationNo);
        try {
            object.put("channelType",  WebAppAESUtil.encrypt(StateGridConstants.CHANNEL_TYPE));
            object.put("h5SslSignData",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("H5SSL_SIGN_DATA"))));
            object.put("dataId",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("DATA_ID"))));
            object.put("areaCode", WebAppAESUtil.encrypt(areaCode));
            object.put("powerGenerationNo",  WebAppAESUtil.encrypt(powerGenerationNo));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
//        logger.info("queryListUser, msg:{}",object);
        EsignRequestType reqType = EsignRequestType.POST;
        try {
            EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType, StateGridConstants.HTTP_URL_USER_FIND, null, object.toString(), true);
            JSONObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JSONObject.class);
//            logger.info("queryListUser, return >>>>> msg:{}",jsonObject);
            if(jsonObject==null){
                return Result.fail("查询失败");
            }
            if (jsonObject.getString("rtnCode").equals("0")){
                return Result.fail("查询失败");
            }else {
                JSONArray dataList = jsonObject.getJSONArray("dataList");
                JSONObject dataObj = (JSONObject)dataList.get(0);
                if (dataObj.getString("authorisationStatus").equals("02") || dataObj.getString("authorisationStatus").equals("已授权")) {
                    customerEntryDao.updateStateGridStatus(powerGenerationNo,"2");
                    return Result.success(jsonObject);
                }
            }
            return Result.fail("查询失败");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }



    /**
     * 用户信息管理查询
     * @param areaCode
     * @param powerGenerationNo
     */

    public  boolean  findUserInfoFromStateGrid(String areaCode,String powerGenerationNo ){
        Gson gson=new Gson();
        JSONObject object = new JSONObject();
        Map proComMap = getProjectInfoByPowerGenerationNo(powerGenerationNo);
        try {
            object.put("channelType",  WebAppAESUtil.encrypt(StateGridConstants.CHANNEL_TYPE));
            object.put("h5SslSignData",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("H5SSL_SIGN_DATA"))));
            object.put("dataId",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("DATA_ID"))));
            object.put("areaCode", WebAppAESUtil.encrypt(areaCode));
            object.put("powerGenerationNo",  WebAppAESUtil.encrypt(powerGenerationNo));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
//        logger.info("queryListUser, msg:{}",object);
        EsignRequestType reqType = EsignRequestType.POST;
        try {
            EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType, StateGridConstants.HTTP_URL_USER_FIND, null, object.toString(), true);
            JSONObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JSONObject.class);
//            logger.info("queryListUser, return >>>>> msg:{}",jsonObject);
            if(jsonObject==null){
                return false;
            }
            if (jsonObject.getString("rtnCode").equals("0")){
                return false;
            }else {
                JSONArray dataList = jsonObject.getJSONArray("dataList");
                JSONObject dataObj = (JSONObject)dataList.get(0);
                if (dataObj.getString("authorisationStatus").equals("02") || dataObj.getString("authorisationStatus").equals("已授权")) {
                    customerEntryDao.updateStateGridStatus(powerGenerationNo,"2");
                    return true;
                }
            }
            return false;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }


    public boolean isAgency(String powerGenerationNo){
        CustomerEntry customerEntry = customerEntryDao.getInfoByPowerGenerationNo(powerGenerationNo);
        if(customerEntry != null){
            return findUserInfoFromStateGrid(customerEntry.getProjectCode(), customerEntry.getGeneratorNo());
        }
        return false;
    }



//    /**
//     * 查询用户还款计划
//     * @param areaCode
//     * @param powerGenerationNo
//     * @return
//     */
//
//    public static int findUserHKFromStateGrid(String areaCode,String powerGenerationNo){
//        Gson gson=new Gson();
//        JSONObject object = new JSONObject();
//        object.put("channelType", StateGridConstants.CHANNEL_TYPE);
//        object.put("h5SslSignData", StateGridConstants.H5SSL_SIGN_DATA);
//        object.put("dataId", StateGridConstants.DATA_ID);
//        object.put("areaCode", areaCode);
//        object.put("powerGenerationNo", powerGenerationNo);
//        EsignRequestType reqType = EsignRequestType.POST;
//        try {
//            String body = WebAppAESUtil.encrypt(object.toString());
//            EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType, StateGridConstants.HTTP_URL_HK_FIND, null, body, true);
//            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
//            System.out.println(jsonObject);
//            return 1;
//        }catch (Exception e){
//            throw new RuntimeException(e);
//        }
//    }



    /**
     * 添加用户信息到国网
     * @param powerGenerationNo
     * @return
     */

    public Result addUserInfoArriveStateGrid(String powerGenerationNo,CustomerEntry entry){
        if (StringUtil.isBlank(powerGenerationNo)){
            return Result.fail("505","请输入发电户号");
        }
        if (!"1".equals(entry.getFilingType())){
            return Result.fail("505","项目公司备案不需要国网授权");
        }
        Gson gson=new Gson();
        JSONObject object = new JSONObject();
        if(entry== null){
             entry = customerEntryDao.getInfoByPowerGenerationNo(powerGenerationNo);
        }
        if (StringUtil.isBlank(entry.getProvinceCode())){
            return Result.fail("505","请先维护好电力公司");
        }
        Map proComMap = getProjectInfoMap(entry);
        ArrayList arrayList = new ArrayList<>();
        try {
            object.put("channelType",  WebAppAESUtil.encrypt(StateGridConstants.CHANNEL_TYPE));
            object.put("h5SslSignData",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("H5SSL_SIGN_DATA"))));
            object.put("dataId",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("DATA_ID"))));
                JSONObject dataList = new JSONObject();
                dataList.put("powerGenerationNo", WebAppAESUtil.encrypt(entry.getGeneratorNo()));
                dataList.put("gcName", WebAppAESUtil.encrypt(entry.getTenantName()));
                dataList.put("areaCode", WebAppAESUtil.encrypt(entry.getProvinceCode()));
                dataList.put("idCard", WebAppAESUtil.encrypt(entry.getIdCode()));
                dataList.put("phone", WebAppAESUtil.encrypt(entry.getMobile()));
                dataList.put("bankNumber", WebAppAESUtil.encrypt(entry.getBankCode()));
                dataList.put("contractType", WebAppAESUtil.encrypt("04"));
                arrayList.add(dataList);

        }catch (Exception e){
            throw new RuntimeException(e);
        }
        //添加dataList
        object.put("dataList",arrayList);
//        logger.info("impUserInfo, msg:{}",object);
        EsignRequestType reqType = EsignRequestType.POST;
        try {
            EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType, StateGridConstants.HTTP_URL_USER_ADD, null, object.toString(), true);
            //  EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType, "http://47.100.121.41:8089/nenghui_uat/a/common/transit", null, object, true);
            JSONObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JSONObject.class);
//            logger.info("impUserInfo, return >>>>> msg:{}",jsonObject);
            if (StringUtil.checkParamsValid(jsonObject)){
                String rtnCode = jsonObject.getString("rtnCode");
                if (rtnCode.equals("1")){
                    JSONArray rtnlist = jsonObject.getJSONArray("rtnList");
                    JSONObject rtnObj =(JSONObject) rtnlist.get(0);
                    //为了流程能走下去 0 变成 1
                    if (rtnObj.getString("rtnCode").equals("0")) {
                        return Result.fail("505",rtnObj.getString("rtnMsg"));
                    }else {
                        Result result = addUserUserHKArriveStateGrid(powerGenerationNo);
                        return result;
                    }

                }
            }
            return Result.fail("505","添加失败，请联系管理员");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加还款计划
     * @param powerGenerationNo
     * @return
     */
    public Result addUserUserHKArriveStateGrid(String powerGenerationNo){
        Gson gson=new Gson();
        JSONObject object = new JSONObject();
        Map proComMap = getProjectInfoByPowerGenerationNo(powerGenerationNo);
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime futureDateTime = currentDateTime.plusYears(25).plusMonths(6);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startTime = currentDateTime.format(formatter);
        String endTime = futureDateTime.format(formatter);
        CustomerEntry infoDTO = customerEntryDao.getInfoByPowerGenerationNo(powerGenerationNo);
        ArrayList dataList = new ArrayList<>();
        try {
            object.put("channelType", WebAppAESUtil.encrypt(StateGridConstants.CHANNEL_TYPE));
            object.put("h5SslSignData",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("H5SSL_SIGN_DATA"))));
            object.put("dataId",  WebAppAESUtil.encrypt(String.valueOf(proComMap.get("DATA_ID"))));

                JSONObject dataJson = new JSONObject();
                dataJson.put("powerGenerationNo",WebAppAESUtil.encrypt(infoDTO.getGeneratorNo()));
                dataJson.put("areaCode",WebAppAESUtil.encrypt(infoDTO.getProvinceCode()));
                // 还款类型，固定 07.个人定期不补偿 02.
                dataJson.put("dudectType",WebAppAESUtil.encrypt("02"));
                dataJson.put("repayPlanSum",WebAppAESUtil.encrypt(""));
                dataJson.put("protocolStartTime",WebAppAESUtil.encrypt(startTime));
                dataJson.put("protocolEndTime",WebAppAESUtil.encrypt(endTime));
                dataJson.put("dueDate",WebAppAESUtil.encrypt("01"));
                dataJson.put("createTime",WebAppAESUtil.encrypt(startTime));
                ArrayList arrayList = new ArrayList<>();
                JSONObject detailList = new JSONObject();
                detailList.put("powerGenerationNo",WebAppAESUtil.encrypt(infoDTO.getGeneratorNo()));
                detailList.put("areaCode",WebAppAESUtil.encrypt(infoDTO.getProvinceCode()));
                detailList.put("repayPlanSum",WebAppAESUtil.encrypt(""));
                detailList.put("dueDate",WebAppAESUtil.encrypt("01"));
                arrayList.add(detailList);
                dataJson.put("detailList",arrayList);
                dataList.add(dataJson);

        }catch (Exception e){
            throw new RuntimeException(e);
        }
        object.put("dataList",dataList);
//        logger.info("impRepayPlan, msg:{}",object);
        EsignRequestType reqType = EsignRequestType.POST;
        try {
            EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType, StateGridConstants.HTTP_URL_HK_ADD, null, object.toString(), true);
            JSONObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JSONObject.class);
            if (StringUtil.checkParamsValid(jsonObject)){
                String rtnCode = jsonObject.getString("rtnCode");
                if (rtnCode.equals("1")){
//                    logger.info("impRepayPlan, return >>>> msg:{}",jsonObject);
                    customerEntryDao.updateStateGridStatus(powerGenerationNo,"1");
//                    logger.info("发电户号：powerGenerationNo:{},修改国网授权状态为 >>>> 授权中",powerGenerationNo);
                    return Result.success("授权成功");
                }else {
                    JSONArray rtnList = jsonObject.getJSONArray("rtnList");
                    JSONObject rtnObj =(JSONObject) rtnList.get(0);
//                    logger.error("impRepayPlan, return >>>> msg:{}",jsonObject);
                    return Result.fail(rtnObj.getString("rtnMsg"));
                }
            }
            return Result.fail("505","添加失败，请联系管理员");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }


    public Map getProjectInfoByPowerGenerationNo(String powerGenerationNo){
        Map proComMap = customerEntryDao.getProjectInfoByPowerGenerationNo(powerGenerationNo);
        if (proComMap.containsKey("err")) {
            logger.info("发电户号{}, >>>>  授权失败  -- errInfo{}",powerGenerationNo,proComMap.get("err"));
            throw new IllegalArgumentException(String.valueOf(proComMap.get("err")));
        }
        return proComMap;
    }

    public Map getProjectInfoMap(CustomerEntry entry){
        Map proComMap = customerEntryDao.getProjectInfoMap(entry);
        if (proComMap.containsKey("err")) {
            logger.info("发电户号{}, >>>>  授权失败  -- errInfo{}",entry.getGeneratorNo(),proComMap.get("err"));
            throw new IllegalArgumentException(String.valueOf(proComMap.get("err")));
        }
        return proComMap;
    }

}
