package com.sifang.modules.task;

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.DbKey;
import com.sifang.modules.sys.common.utils.IdGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

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

    //获取友夸数据
    @Scheduled(cron = "0 30 0 * * ?")//每天凌晨0点30分执行
    public void getYKRecords() {
        logger.info("开始获取友跨数据----------》");
        logger.info(">>>>>>>>YouKuaGetRecords  定时任务开始");
        long begin = System.currentTimeMillis();
        List<Record> records = Db.use(DbKey.DB_YOUKUA).find(" select  a.id as innerStationId ,a.id as outStationId ,a.archive_no as stationCode,a.station_name as stationName " +
                ",case r.fund_type when '1' then '广州越秀融资租赁有限公司' else '其他' end as capitalName ,s.bus_sales_id as projectId  " +
                ",s.sales_name as projectName ,d.company_code as projectCompanyId ,d.company_name as projectCompanyName  " +
                ",b.office_code as agentId ,b.office_name as agentName ,b.phone as agentPhone ,r.id as ownerId, r.`name` as ownerName  " +
                ",r.mobile as ownerPhone ,a.rpovince_name AS province,a.city_name AS city ,a.county_name AS district  " +
                ",a.address as address ,e.latitude as latitude ,e.image_url as images ,e.longitude as longitude ,a.capacity as actualCapacity  " +
                ",a.`status` as status , DATE_FORMAT(DATE_ADD( a.grid_time, INTERVAL 13 HOUR ), '%Y-%m-%d %H:%i:%s') as mergeTime  " +
                " ,su.install_type as installType , r.filing_subject as  filingType , mc.partners_contract_number as applyNo "+
                "from bus_archive a  " +
                "LEFT JOIN m_power_station e ON e.archive_id = a.id " +
                "LEFT JOIN bus_archive_sales s ON s.archive_id  = a.id  " +
                "LEFT JOIN js_sys_office AS b ON a.office_code = b.office_code " +
                "LEFT JOIN bus_archive_survey_apply AS c ON a.survey_apply_id = c.id " +
                "LEFT JOIN `bus_intent_user` `r` ON `c`.`intent_user_id` = `r`.`id`  " +
                "LEFT JOIN js_sys_company AS d ON r.company_code = d.company_code  " +
                "LEFT JOIN bus_archive_survey su on su.archive_id = a.id "+
                " LEFT JOIN js_yx_materia_config mc on mc.archive_no = a.archive_no and mc.del_flg='0' "+
                "where a.`del_flg` = '0' ");//当前查询所有电站
        logger.info("获取到友跨数据条数：{}", records.size());
        for (Record record : records) {
            boolean flag = Db.queryLong(" select count(1) from  nh_power_station where out_station_id = ? ", record.getLong("outStationId")) > 0;
            String outStationId = "";
            if (record.getLong("outStationId") != null){
                outStationId = record.getLong("outStationId").toString();
            }
            String stationCode = record.getStr("stationCode");
            String stationName = record.getStr("stationName");
            String images = record.getStr("images");
            String capitalName = record.getStr("capitalName");
            String projectId = "";
            if (record.getInt("projectId") != null){
                projectId = record.getInt("projectId").toString();
            }
            String projectName = record.getStr("projectName");
            String projectCompanyId = record.getStr("projectCompanyId");
            String projectCompanyName = record.getStr("projectCompanyName");
            String agentId = record.getStr("agentId");
            String agentName = record.getStr("agentName");
            String agentPhone = record.getStr("agentPhone");
            String ownerId = "";
            if (record.getLong("ownerId") != null){
                ownerId = record.getLong("ownerId").toString();
            }
            String ownerName = record.getStr("ownerName");
            String ownerPhone = record.getStr("ownerPhone");
            String province = record.getStr("province");
            String city = record.getStr("city");
            String district = record.getStr("district");
            String address = record.getStr("address");
            String latitude = record.getStr("latitude");
            String longitude = record.getStr("longitude");
            String actualCapacity = record.getStr("actualCapacity");
            String status = record.getStr("status");
            String mergeTime = record.getStr("mergeTime");
            String installType = record.getStr("installType");
            String filingType = record.getStr("filingType");
            String applyNo = record.getStr("applyNo");
            String customerType = "1";//TODO 暂时只查客户类型都是个人

            // 资方是其他 需要进行逻辑处理
            if ("其他".equals(capitalName)) {
                if (StringUtil.equalsAny(agentName, "广州穗发能辉新能源有限公司", "罗山县穗发能辉新能源发展有限公司")){
                    capitalName = "广州发展新能源集团股份有限公司";
                }
                else if ("唐河能辉清洁能源开发有限公司".equals(agentName)) {
                    capitalName = "自持";
                }
                else if (StringUtil.isNotBlank(agentName) && agentName.contains("广发广东")) {
                    capitalName = "广州发展新能源集团股份有限公司";
                }
                else {
                    // 国电投
                    capitalName = "广西贵港赣辉新能源有限公司";
                }
            }

            String installTypeName = "";
            //0-常规阵列式，1-阳光棚，2-人字坡，3-院落式 4-两面坡
            if ("0".equals(installType)){
                installTypeName = "常规阵列式";
            }else if ("1".equals(installType)){
                installTypeName = "阳光棚";
            }else if ("2".equals(installType)){
                installTypeName = "人字坡";
            }else if ("3".equals(installType)){
                installTypeName = "庭院";
            } else if ("4".equals(installType)) {
                installTypeName = "两面坡";
            }
            String uuid = IdGen.uuid();
            if (!flag){
                Db.update(" insert into nh_power_station (id,inner_station_id,out_station_id,station_code,station_name,capital_name,project_id," +
                                "project_name,project_company_id,project_company_name,agent_id,agent_name,agent_phone,owner_name,owner_phone," +
                                "province,city,district,address,latitude,longitude,actual_capacity,status,merge_time,images ,owner_id,install_type,filing_type,customer_type,apply_no)" +
                                "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",uuid ,outStationId,outStationId,stationCode,stationName,capitalName,
                        projectId,projectName,projectCompanyId,projectCompanyName,agentId,agentName,agentPhone,ownerName,ownerPhone,province,city,district,
                        address,latitude,longitude,actualCapacity,status,mergeTime,images,ownerId,installTypeName,filingType,customerType,applyNo);
            }

            // 获取逆变器信息
            List<Record> inverterList = Db.use(DbKey.DB_YOUKUA).find(" select  i.id as outDeviceId  ,i.brand as brand ,i.model as mods ,i.sn as sn ,i.w_status as status ,i.status as isDeleted" +
                    " from m_power_inverter i  LEFT JOIN m_power_station e on e.id = i.station_id  where i.status = '0' and  e.station_no =? ", stationCode);
            for (Record inverter : inverterList) {
                //逆变器的设备id取主键id，和采集器的设备id区分开
                String id = IdGen.uuid();
                String brand = inverter.getStr("brand");
                int brandType = 0;
                if ("爱仕惟".equals(brand)){
                    brandType = 1;
                }else if ("固德威".equals(brand)){
                    brandType = 2;
                }
                String mods = inverter.getStr("mods");
                String sn = inverter.getStr("sn");
                String wStatus = inverter.getInt("status").toString();
                String isDeleted = inverter.getStr("isDeleted");
                //判断是否添加过逆变器
                boolean nbqFlag = Db.queryLong(" select count(1) from  nh_device where  type = '1' and  inner_station_id = ? and sn = ?  ", outStationId, sn) > 0;
                if (!nbqFlag){
                    Db.update(" insert into nh_device (id,station_id,inner_station_id,inner_device_id,out_station_id,out_device_id,brand,mods,sn,status,type,name,is_deleted) " +
                            "values (?,?,?,?,?,?,?,?,?,?,?,?,?)", id,uuid,outStationId,id,outStationId,id,brandType,mods,sn,wStatus,1,"逆变器",isDeleted);
                }
            }

            // 获取采集器信息
            List<Record> collectorList = Db.use(DbKey.DB_YOUKUA).find(" select  c.id as outDeviceId  ,c.brand as brand ,c.model as mods ,c.sn as sn ,c.state as isDeleted " +
                    "  from m_power_collector c LEFT JOIN m_power_station e on e.id = c.station_id  where c.state = '0' and  e.station_no =? ", stationCode);
            for (Record collector : collectorList) {
                String outDeviceId = collector.getLong("outDeviceId").toString();
                String brand = collector.getStr("brand");
                int brandType = 0;
                if ("爱仕惟".equals(brand)){
                    brandType = 1;
                }else if ("固德威".equals(brand)){
                    brandType = 2;
                }
                String mods = collector.getStr("mods");
                String sn = collector.getStr("sn");
                String isDeleted = collector.getStr("isDeleted");
                //判断是否添加过采集器
                boolean cjqFlag = Db.queryLong(" select count(1) from  nh_device where  type = '2' and  inner_station_id = ? and sn = ?  ", outStationId, sn) > 0;
                if(!cjqFlag){
                    Db.update(" insert into nh_device (id, station_id ,inner_station_id,inner_device_id,out_station_id,out_device_id,brand,mods,sn,is_deleted,type,name) " +
                            "values (?,?,?,?,?,?,?,?,?,?,?,?)", IdGen.uuid(),uuid,outStationId,outDeviceId,outStationId,outDeviceId,brandType,mods,sn,isDeleted,2,"通讯棒");
                }
            }
        }
        long end = System.currentTimeMillis();
        logger.info("YouKuaGetRecords 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }
}
