package com.sifang.modules.task;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.youkua.constants.YWConstants;
import com.sifang.modules.youkua.entity.NhDevice;
import com.sifang.modules.youkua.entity.NhPowerStation;
import com.sifang.modules.youkua.service.NhPowerStationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class NHTask {
    private static final Logger logger = LoggerFactory.getLogger(NHTask.class);

    @Autowired
    private NhPowerStationService nhPowerStationService;

    public NhPowerStation initNhPowerStation(Record record) {
        NhPowerStation nhPowerStation = new NhPowerStation();
        nhPowerStation.setId(IdGen.uuid());
        nhPowerStation.setInnerStationId(record.getStr("innerStationId"));
        nhPowerStation.setOutStationId(record.getStr("outStationId"));
        nhPowerStation.setStationCode(record.getStr("stationCode"));
        nhPowerStation.setStationName(record.getStr("stationName"));
        nhPowerStation.setImages(record.getStr("images"));
        nhPowerStation.setCapitalCode(record.getStr("capitalCode"));
        nhPowerStation.setCapitalName(record.getStr("capitalName"));
        nhPowerStation.setProjectId(record.getStr("projectId"));
        nhPowerStation.setProjectCode(record.getStr("projectCode"));
        nhPowerStation.setProjectName(record.getStr("projectName"));
        nhPowerStation.setProjectCompanyId(record.getStr("projectCompanyId"));
        nhPowerStation.setProjectCompanyName(record.getStr("projectCompanyName"));
        nhPowerStation.setInstallType(record.getStr("installType"));
        nhPowerStation.setAgentId(record.getStr("agentId"));
        nhPowerStation.setAgentName(record.getStr("agentName"));
        nhPowerStation.setAgentPhone(record.getStr("agentPhone"));
        nhPowerStation.setOwnerId(record.getStr("ownerId"));
        nhPowerStation.setOwnerName(record.getStr("ownerName"));
        nhPowerStation.setOwnerPhone(record.getStr("ownerPhone"));
        nhPowerStation.setSn(record.getStr("sn"));
        nhPowerStation.setProvince(record.getStr("province"));
        nhPowerStation.setCity(record.getStr("city"));
        nhPowerStation.setDistrict(record.getStr("district"));
        nhPowerStation.setAddress(record.getStr("address"));
        if (record.getBigDecimal("latitude") != null) {
            nhPowerStation.setLatitude(record.getBigDecimal("latitude").stripTrailingZeros().toPlainString());
        }
        if (record.getBigDecimal("longitude") != null) {
            nhPowerStation.setLongitude(record.getBigDecimal("longitude").stripTrailingZeros().toPlainString());
        }
        nhPowerStation.setActualCapacity(record.getBigDecimal("actualCapacity"));
        nhPowerStation.setInstallAcceptTime(record.getDate("installAcceptTime"));
        nhPowerStation.setStartGenDate(record.getDate("startGenDate"));
        nhPowerStation.setApplyNo(record.getStr("applyNo"));
        nhPowerStation.setIsFollow(record.getInt("isFollow"));
        nhPowerStation.setStatus(record.getInt("staus"));
        nhPowerStation.setOmProviderId(record.getStr("omProviderId"));
        nhPowerStation.setOmProviderName(record.getStr("omProviderName"));
        nhPowerStation.setMergeTime(record.getDate("mergeTime"));
        nhPowerStation.setFilingType(record.getStr("filingType"));
        nhPowerStation.setCustomerType(record.getStr("customerType"));
        return nhPowerStation;
    }
    public static NhDevice initNhDevice(Record record){
        NhDevice nhDevice = new NhDevice();
        nhDevice.setInnerStationId(record.getStr("innerStationId"));
        nhDevice.setOutStationId(record.getStr("outStationId"));
        nhDevice.setInnerDeviceId(record.getStr("innerDeviceId"));
        nhDevice.setOutDeviceId(record.getStr("outDeviceId"));
        String brand = record.getStr("brand");
        String brandType = "0";
        if (StringUtil.equalsAny(brand,"爱仕惟","爱士惟")){
            brandType = "1";
        }else if ("固德威".equals(brand)){
            brandType = "2";
        }
        nhDevice.setBrand(brandType);
        nhDevice.setType(record.getInt("type"));
        nhDevice.setName(record.getStr("name"));
        nhDevice.setMods(record.getStr("mods"));
        nhDevice.setSn(record.getStr("sn"));
        nhDevice.setBarCode(record.getStr("barCode"));
        nhDevice.setWarrantyFlag(record.getInt("warrantyFlag"));
        nhDevice.setWarrantyExpires(record.getDate("warrantyExpires"));
        nhDevice.setStatus(Integer.valueOf(record.getStr("status")));
        return nhDevice;
    }

//    同步能辉数据到监控运维平台
    @Scheduled(cron = "0 05 01 * * ?")//每天凌晨1点05分执行
    public void  syncFirstNHData(){
        List<Record> records = Db.find(" SELECT e.id as  innerStationId ,e.id as outStationId ,e.power_station_code as stationCode, " +
                " concat(e.province,e.area,e.tenant_name,e.design_capacity/1000,'KW光伏电站') as stationName,e.partner_id as capitalCode, " +
                " e.partner_name as capitalName ,e.project_id as projectId,e.project_code as projectCode,e.project_name as projectName, " +
                " e.project_company_id as projectCompanyId,e.project_company_name as projectCompanyName,e.distributor_id as agentId , " +
                " e.trader_name as agentName, e.trader_tel as agentPhone ,e.tenant_name as ownerName,e.mobile as ownerPhone, " +
                " e.sn as sn,e.province as province,e.city as city,e.area as district, e.address as address, e.latitude as latitude, " +
                " e.longitude as longitude,e.actual_capacity/1000 as actualCapacity,e.first_generation_time  as startGenDate, " +
                " i.partners_contract_number  as applyNo ,e.`status` as status, e.merge_time as mergeTime ,e.scheme_type_name as installType ,e.filing_type as filingType, " +
                " e.tenant_type as customerType  "+
                " FROM `crm_customer_entry` e " +
                " LEFT JOIN `crm_customer_incoming_application` i on i.entry_id=e.id and i.if_delete<>'1' " +
                " where e.status in('6','7','10','a') and  e.id not in ( select  p.station_id from  nh_yw_interface_process p " +
                " LEFT JOIN  nh_yw_interface_process a on a.station_id = p.station_id " +
                " where p.`status` = '0' and p.type ='1' and p.add_type = '0' and a.`status` = '0' and a.type ='1' and a.add_type = '1' ) ");
        logger.info(">>>>>>>>syncNHData  同步能辉电站  数据量:[" + records.size() + "]条");
        long begin = System.currentTimeMillis();
        for (Record record : records) {
            try {

                String entryId = record.getStr("innerStationId");
                //添加电站成功标识
                boolean addStationFlag = Db.queryLong(" select count(1) from  nh_yw_interface_process where status = '0' and type = '1' and add_type = '0' and  station_id = ?", entryId) > 0;
                //添加设备成功标识
                boolean addDeviceFlag = Db.queryLong(" select count(1) from  nh_yw_interface_process where status = '0' and type = '1'  and add_type = '1' and  station_id = ?", entryId) > 0;
                String code = "";
                if (!addStationFlag){
                    NhPowerStation nhPowerStation = initNhPowerStation(record);
                    //添加电站
                    code = nhPowerStationService.addPowerStation(nhPowerStation, "0", "1");
                }
                if ("501".equals(code)){
                    Db.update("  INSERT INTO nh_yw_interface_process(id,station_id,url,create_time,request_param, response_param, status ,type,add_type ) " +
                            "  VALUES (MD5(UUID()),?,?,NOW(),?,?,?,?,?)",entryId, YWConstants.url+YWConstants.batchAddInverterStatUrl,"","","0","1","1");
                }else {
                    if (!addDeviceFlag){
                        List<Record> recordList = Db.find(" SELECT  m.entry_id as innerStationId , m.entry_id as outStationId,m.id as innerDeviceId ,m.id as outDeviceId ,s.material_brand as brand , " +
                                " m.`name` as name,m.spec as mods,m.sn as sn  ,m.nbq_sn as nbqSn,m.barcode as barCode,m.`status` as status " +
                                " from  crm_plan_material_entry m " +
                                " LEFT JOIN crm_customer_entry e on e.id = m.entry_id " +
                                " LEFT JOIN crm_supply_material s on s.id = m.material_id " +
                                " where m.entry_id = ? and  m.type = '逆变器' ", entryId);
                        List<NhDevice> nhDeviceList = new ArrayList<>();
                        for (Record record1 : recordList) {
                            //采集器
                            NhDevice nhDevice = initNhDevice(record1);
                            nhDevice.setType(2);
                            nhDevice.setName("通讯棒");
                            nhDeviceList.add(nhDevice);
                            //逆变器
                            NhDevice nhDevice2 = initNhDevice(record1);
                            nhDevice2.setType(1);
                            String nbqSn = record1.getStr("nbqSn");
                            String sn = record1.getStr("sn");
                            String deviceId = nbqSn+sn;
                            if (deviceId.length() > 32){
                                deviceId = deviceId.substring(0,32);
                            }
                            nhDevice2.setInnerDeviceId(deviceId);
                            nhDevice2.setOutDeviceId(deviceId);
                            nhDevice2.setSn(nbqSn);
                            nhDeviceList.add(nhDevice2);
                        }
                        //添加设备
                        nhPowerStationService.batchAddInverterSta(nhDeviceList,entryId,"1");
                    }
                }
            }catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        long end = System.currentTimeMillis();
        logger.info("  syncNHData  定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }

    // 同步电站已并网验收通过
//    @Scheduled(cron = "0 0/10 * * * ? ")
    @Scheduled(cron = "0 45 01 * * ?")//每天凌晨1点45分执行
    public void  syncYBWNHData(){
        List<Record> records = Db.find(" SELECT e.id AS  innerStationId ,e.id AS outStationId ,e.power_station_code AS stationCode, " +
                " e.first_generation_time  AS startGenDate, e.merge_time AS mergeTime "+
                " FROM `crm_customer_entry` e " +
                " INNER JOIN nh_yw_interface_process p " +
                " ON p.`station_id` = e.`id` AND p.`add_type` = '0' AND p.type ='1' AND p.`status` = '0' " +
                " LEFT JOIN nh_yw_interface_process bp " +
                " ON bp.`station_id` = e.`id` AND bp.`add_type` = '2' AND bp.type ='1' AND bp.`status` = '0' " +
                " WHERE e.status IN('7','a') AND e.merge_flag IN('3','4') AND bp.id IS NULL ");
        logger.info(">>>>>>>>syncNHData  同步已并网的能辉电站  数据量:[" + records.size() + "]条");
        long begin = System.currentTimeMillis();
        for (Record record : records) {
            try {
                String entryId = record.getStr("innerStationId");
                //0.添加电站 1.添加设备 2.同步已并网验收通过
                NhPowerStation nhPowerStation = initNhPowerStation(record);
                //添加电站
                String code = nhPowerStationService.sysYbwPowerStation(nhPowerStation);
                if ("501".equals(code)){
                    Db.update("  INSERT INTO nh_yw_interface_process(id,station_id,url,create_time,request_param, response_param, status ,type,add_type ) " +
                            "  VALUES (MD5(UUID()),?,?,NOW(),?,?,?,?,?)",entryId, YWConstants.url+YWConstants.sysYbwPowerStation,"","","1","1","2");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        long end = System.currentTimeMillis();
        logger.info("  syncYBWNHData  定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }


    public void pushEntryTime(){
        List<Record> list = Db.find("select * from nh_power_station where capital_name='广州越秀融资租赁有限公司' and station_code like 'D%' and merge_time  is not null ");
        List<Map<String,Object>> listsd=new ArrayList<>();
        for(Record rd :list){
            Map<String,Object> body=new HashMap<>();
            body.put("innerStationId",rd.getStr("inner_station_id"));
            body.put("startGenDate",rd.getDate("merge_time"));
            listsd.add(body);
        }
        nhPowerStationService.pushEntryTime(listsd);
    }


}
