package com.sifang.modules.task;

import cn.hutool.json.JSONUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
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.List;

@Component
public class YWTask {
    private static final Logger logger = LoggerFactory.getLogger(YWTask.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"));
        nhPowerStation.setLatitude(record.getStr("latitude"));
        nhPowerStation.setLongitude(record.getStr("longitude"));
        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 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"));
        nhDevice.setBrand(record.getStr("brand"));
        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(record.getInt("status"));
        return nhDevice;
    }

    //同步友夸数据到监控运维平台
    @Scheduled(cron = "0 45 1 * * ?")//每天凌晨0点45分执行
    public void syncYWData(){
        List<Record> records = Db.find(" SELECT e.inner_station_id as  innerStationId ,e.out_station_id as outStationId , " +
                " e.station_code as stationCode,e.station_name as stationName, e.images as  images , " +
                " e.capital_code as capitalCode,e.capital_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.install_type as installType,e.agent_id as agentId , " +
                " e.agent_name as agentName, e.agent_phone as agentPhone ,e.owner_id as ownerId, " +
                " e.owner_name as ownerName, e.owner_phone as ownerPhone,e.sn as sn ,e.province as province,e.city as city, " +
                " e.district as district, e.address as address, e.latitude as latitude, e.longitude as longitude, " +
                " e.actual_capacity as actualCapacity, e.install_accept_time  as installAcceptTime, " +
                " e.start_gen_date  as startGenDate,e.apply_no as applyNo,e.is_follow as isFollow,e.`status` as status, " +
                " e.om_provider_id as omProviderId,e.om_provider_name as omProviderName, e.merge_time as mergeTime ,e.filing_type as filingType , " +
                " e.customer_type as customerType "+
                " FROM `nh_power_station` e  where e.out_station_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 ='0' and p.add_type = '0' and a.`status` = '0' and a.type ='0' and a.add_type = '1' ) ");
        logger.info(">>>>>>>>  syncYWData 同步友夸电站   数据量:[" + records.size() + "]条");
        long begin = System.currentTimeMillis();
        for (Record record : records) {
            try{
                String outStationId = record.getStr("outStationId");
                //添加电站成功标识
                boolean addStationFlag = Db.queryLong(" select count(1) from  nh_yw_interface_process where status = '0' and type = '0' and add_type = '0' and  station_id = ?", outStationId) > 0;
                //添加设备成功标识
                boolean addDeviceFlag = Db.queryLong(" select count(1) from  nh_yw_interface_process where status = '0' and type = '0'  and add_type = '1' and  station_id = ?", outStationId) > 0;
                String code = "";
                if (!addStationFlag) {
                    NhPowerStation nhPowerStation = initNhPowerStation(record);
                    //添加电站
                    code = nhPowerStationService.addPowerStation(nhPowerStation, "1", "0");
                }
                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(),?,?,?,?,?)",outStationId,YWConstants.url+YWConstants.batchAddInverterStatUrl,"","","0","0","1");
                }else {
                    if (!addDeviceFlag){
                        List<Record> recordList = Db.find("  select  d.inner_station_id as innerStationId , d.out_station_id as outStationId ,d.inner_device_id  as innerDeviceId , " +
                                " d.out_device_id as outDeviceId , d.brand as brand ,d.type as type , d.name as name ,d.mods as  mods,d.sn as sn , " +
                                " d.bar_code as barCode ,d.warranty_flag as warrantyFlag ,d.warranty_expires as warrantyExpires ,d.`status` as staus  " +
                                " from nh_device  d where d.is_deleted = '0' and d.out_station_id = ?  ", outStationId);
                        List<NhDevice> nhDeviceList = new ArrayList<>();
                        for (Record record1 : recordList) {
                            NhDevice nhDevice = initNhDevice(record1);
                            nhDeviceList.add(nhDevice);
                        }
                        if (nhDeviceList.size()>0){
                            //添加设备
                            nhPowerStationService.batchAddInverterSta(nhDeviceList,outStationId,"0");
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.info("  syncYWData 同步友夸电站失败 stationId:{} 异常：{}",record.getStr("outStationId"),e.getMessage());
            }
        }
        long end = System.currentTimeMillis();
        logger.info("  syncYWData 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");

    }

}
