package com.sifang.modules.customer.Service;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.dao.PowerStationDao;
import com.sifang.modules.customer.dao.PowerStationDeviceDao;
import com.sifang.modules.customer.dao.PowerStationImgsDao;
import com.sifang.modules.customer.entity.PowerStation;
import com.sifang.modules.customer.entity.PowerStationDevice;
import com.sifang.modules.customer.entity.PowerStationImgs;
import com.sifang.modules.order.service.OrderService;
import com.sifang.modules.order.utils.GetDistance;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PowerStationService extends BaseService {
    @Autowired
    PowerStationDao powerStationDao;
    @Autowired
    private PowerStationDeviceDao powDeviceDao;

    @Autowired
    private PowerStationImgsDao powerImgsDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    private OrderService orderService;


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void getPsList(Map<String, String> map, String prefixUrl, String APPKR) {
        String userId = map.get("userId");
        String token = map.get("token");
        customerDao.saveCustomer(map);
        Gson gson = new Gson();
        //登录成功
        String senddev = GetDistance.sendGet(prefixUrl, "service=getPsList&user_id=" + userId + "&curPage=1&size=100&token=" + token + "&appkey=" + APPKR);
       // System.out.println("senddev: " + senddev);
        JsonObject decList = gson.fromJson(senddev, JsonObject.class);
        String state = decList.get("result_code").getAsString();
        if ("1".equals(state)) {
            JsonObject json2 = gson.fromJson(decList.get("result_data"), JsonObject.class);
            JsonArray array = gson.fromJson(json2.get("pageList"), JsonArray.class);
            if (array != null) {
              /*  for(JsonElement jsone:array){

                }*/
                JsonObject json4 = array.get(0).getAsJsonObject();
                String ps_id = json4.get("ps_id").getAsString();
                if (StringUtil.isNotBlank(ps_id)) {
                    String power = GetDistance.sendGet(prefixUrl, "service=getPowerStationForHousehold&user_id=" + userId + "&ps_id=" + ps_id + "&token=" + token + "&appkey=" + APPKR);
                    JsonObject details = gson.fromJson(power, JsonObject.class);
                    String detailsState = details.get("result_code").getAsString();
                    if ("1".equals(detailsState)) {
                        JsonObject detailsjson = gson.fromJson(details.get("result_data"), JsonObject.class);
                        //保存电站基本信息
                        String power_station_id = savePowerStation(detailsjson, json4, userId, ps_id);
                        //获取电站设备信息
                        String devlist = GetDistance.sendGet(prefixUrl, "service=getDeviceList&ps_id=" + ps_id + "&curPage=1&size=100&token=" + token + "&appkey=" + APPKR);
                        JsonObject device = gson.fromJson(devlist, JsonObject.class);
                        String devstate = device.get("result_code").getAsString();
                        if ("1".equals(devstate)) {
                            JsonObject devstate2 = gson.fromJson(device.get("result_data"), JsonObject.class);
                            savePowerStationDevice(devstate2, json4, userId, power_station_id);
                       /* JsonArray devstate3 = gson.fromJson(devstate2.get("pageList"),JsonArray.class);
                        for(int i =0;i<devstate3.size() ;i++){
                            JsonObject devstate4= array.get(i).getAsJsonObject();


                        }*/
                        }

                    }
                }


            } else {
                //清除之前绑定的电站信息
                //删除电站信息
                Db.update("DELETE FROM crm_power_station WHERE user_id = ? ", userId);
                //删除电站下设备信息
                Db.update("DELETE FROM crm_power_station_device WHERE user_id = ? ", userId);
                String powerId = Db.queryStr("select id from crm_power_station WHERE user_id = ?", userId);
                if (StringUtil.isNotEmpty(powerId)) {
                    //删除图片信息
                    Db.update("DELETE FROM crm_power_station_imgs WHERE power_station_id = ? ", powerId);

                }
            }

        }


    }


    /**
     * 新增电站信息
    */
    public String savePowerStation(JsonObject json, JsonObject json4, String userId, String psId) {

       // System.out.println("json :" + json);
        PowerStation pow = powerStationDao.getPowerStationByuserPsId(userId,psId);
        if (pow == null) {
            pow = new PowerStation();
            pow.setUserId(userId);
            pow.setPsId(psId);
            pow.setInstallDate(json.get("install_date").isJsonNull() ? null : json.get("install_date").getAsString());
            pow.setRecoreCreateTime(json.get("recore_create_time").isJsonNull() ? null : json.get("recore_create_time").getAsString());
            pow.setExpectInstallDate(json.get("expect_install_date").isJsonNull() ? "" : json.get("expect_install_date").getAsString()); //并网时间
        }
        //    LinkedTreeMap jsonb = (LinkedTreeMap) listData.get(0);

        Map<String, String> maps = new Gson().fromJson(json4.get("total_energy"), Map.class);
        Map<String, String> map1 = new Gson().fromJson(json4.get("today_energy"), Map.class);
        Map<String, String> map2 = new Gson().fromJson(json4.get("curr_power"), Map.class);
        Map<String, String> map3 = new Gson().fromJson(json4.get("today_income"), Map.class);
        Map<String, String> map4 = new Gson().fromJson(json4.get("total_income"), Map.class);
        Map<String, String> map5 = new Gson().fromJson(json4.get("co2_reduce"), Map.class);
        Map<String, String> map6 = new Gson().fromJson(json4.get("total_capcity"), Map.class);
        pow.setTotalEnergy(maps.get("value"));
        pow.setTotalEnergyUnit(maps.get("unit"));
        pow.setTodayEnergy(map1.get("value"));
        pow.setTodayEnergyUnit(map1.get("unit"));
        pow.setCurrPower(map2.get("value"));
        pow.setCurrPowerUnit(map2.get("unit"));
        pow.setTodayIncome(map3.get("value"));
        pow.setTodayIncomeUnit(map3.get("unit"));
        pow.setTotalIncome(map4.get("value"));
        pow.setTotalIncomeUnit(map4.get("unit"));
        pow.setCoReduce(map5.get("value"));
        pow.setCoReduceUnit(map5.get("unit"));
        pow.setTotalCapcity(map6.get("value"));
        pow.setTotalCapcityUnit(map6.get("unit"));

       // logger.info("json4 : {}", json4);
        pow.setPsPriceKwh(json.get("ps_price_kwh").isJsonNull() ? "" : json.get("ps_price_kwh").getAsString());
        if(!json4.get("ps_id").isJsonNull()){
            pow.setPsId(json4.get("ps_id").isJsonNull() ? "" : json4.get("ps_id").getAsString());
        }
        pow.setPsStatus(json4.get("ps_status").isJsonNull() ? "" : json4.get("ps_status").getAsString());
        pow.setPsFaultStatus(json4.get("ps_fault_status").isJsonNull() ? "" : json4.get("ps_fault_status").getAsString());
        pow.setDesignCapacity(json4.get("design_capacity").isJsonNull() ? "" : json4.get("design_capacity").getAsString());//装机功率
        pow.setDesignCapacityUnit(json4.get("design_capacity_unit").isJsonNull() ? "" : json4.get("design_capacity_unit").getAsString());//装机功率单位
        pow.setPsName(json4.get("ps_name").getAsString());
        String address = json4.get("location").isJsonNull() ? "" : json4.get("location").getAsString();
        Map<String, String> mapAddr = orderService.addressResolution(address);
        pow.setProvince(StringUtil.isNotBlank(mapAddr.get("province")) ? mapAddr.get("province") : "");
        pow.setCity(StringUtil.isNotBlank(mapAddr.get("city")) ? mapAddr.get("city") : "");
        pow.setArea(StringUtil.isNotBlank(mapAddr.get("area")) ? mapAddr.get("area") : "");
        pow.setLocation(StringUtil.isNotBlank(mapAddr.get("address")) ? mapAddr.get("address") : "");
        //   pow.setLocation(json4.get("location").getAsString());

        pow.setBuildDate(json4.get("build_date").isJsonNull() ? "" : json4.get("build_date").getAsString());//投建日期
       // System.out.println(json.get("component_area"));
        pow.setComponentArea(json.get("component_area").isJsonNull() ? "" : json.get("component_area").getAsString());
        pow.setConnectType(json.get("connect_type").isJsonNull() ? "" : json.get("connect_type").getAsString()); //并网类型
        pow.setContactName(json.get("contact_name").isJsonNull() ? "" : json.get("contact_name").getAsString()); //联系人姓名
        pow.setDescription(json.get("description").isJsonNull() ? "" : json.get("description").getAsString());  //电站简介
        pow.setEmail("");

        //    pow.setInstalledArea(json.get("installed_area").isJsonNull()?"": json.get("installed_area").getAsString());  //安装面积
        JsonArray inta = new Gson().fromJson(json.get("ps_org_info"), JsonArray.class);
       // System.out.println(inta);
        JsonObject jso = inta.get(0).getAsJsonObject();
        if (inta.size() > 1) {
            jso = inta.get(1).getAsJsonObject();
        }
        if (jso.get("installer") == null || jso.get("installer").isJsonNull()) {
            pow.setInstaller("");
        } else {
            pow.setInstaller(jso.get("installer").getAsString());
        }
        if (json.get("installer_contact") == null || json.get("installer_contact").isJsonNull()) {
            pow.setInstallerContact("");
        } else {
            pow.setInstallerContact(json.get("installer_contact").getAsString());
        }
        if (json.get("longitude") == null || json.get("longitude").isJsonNull()) {
            pow.setLatitude("");
        } else {
            pow.setLatitude(json.get("longitude").getAsString());
        }
        if (json.get("latitude") == null || json.get("latitude").isJsonNull()) {
            pow.setLongitude("");
        } else {
            pow.setLongitude(json.get("latitude").getAsString());
        }
        if (json.get("moble_tel") == null || json.get("moble_tel").isJsonNull()) {
            pow.setMobleTel("");
        } else {
            pow.setMobleTel(json.get("moble_tel").getAsString());
        }
        if (json.get("moble_tel_bak") == null || json.get("moble_tel_bak").isJsonNull()) {
            pow.setMobleTelBak("");
        } else {
            pow.setMobleTelBak(json.get("moble_tel_bak").getAsString());
        }
        if (json.get("operate_year") == null || json.get("operate_year").isJsonNull()) {
            pow.setOperateYear("");
        } else {
            pow.setOperateYear(json.get("operate_year").getAsString());
        }
        if (json.get("operation_bus_name") == null || json.get("operation_bus_name").isJsonNull()) {
            pow.setOperationBusName("");
        } else {
            pow.setOperationBusName(json.get("operation_bus_name").getAsString());
        }
        if (json.get("operator_contact") == null || json.get("operator_contact").isJsonNull()) {
            pow.setOperatorContact("");
        } else {
            pow.setOperatorContact(json.get("operator_contact").getAsString());
        }
        if (json.get("owner_contact") == null || json.get("owner_contact").isJsonNull()) {
            pow.setOwnerContact("");
        } else {
            pow.setOwnerContact(json.get("owner_contact").getAsString());
        }
        if (json.get("owner_organization") == null || json.get("owner_organization").isJsonNull()) {
            pow.setOwnerOrganization("");
        } else {
            pow.setOwnerOrganization(json.get("owner_organization").getAsString());
        }
        if (json.get("producer") == null || json.get("producer").isJsonNull()) {
            pow.setProducer("");
        } else {
            pow.setProducer(json.get("producer").getAsString());
        }
        if (json.get("ps_holder") == null || json.get("ps_holder").isJsonNull()) {
            pow.setPsHolder("");
        } else {
            pow.setPsHolder(json.get("ps_holder").getAsString());
        }
        if (json4.get("ps_short_name") == null || json4.get("ps_short_name").isJsonNull()) {
            pow.setPsShortName("");
        } else {
            pow.setPsShortName(json4.get("ps_short_name").getAsString());
        }
        if (json.get("ps_type_name") == null || json.get("ps_type_name").isJsonNull()) {
            pow.setPsTypeName("");
        } else {
            pow.setPsTypeName(json.get("ps_type_name").getAsString());
        }
        if (json.get("safe_start_date") == null || json.get("safe_start_date").isJsonNull()) {
            pow.setSafeStartDate("");
        } else {
            pow.setSafeStartDate(json.get("safe_start_date").getAsString());
        }
        if (json.get("sn") == null || json.get("sn").isJsonNull()) {
            pow.setSn("");
        } else {
            pow.setSn(json.get("sn").getAsString());
        }
        if (json.get("timezone") == null || json.get("timezone").isJsonNull()) {
            pow.setTimezone("");
        } else {
            pow.setTimezone(json.get("timezone").getAsString());
        }
        if (json.get("user_moble_tel") == null || json.get("user_moble_tel").isJsonNull()) {
            pow.setUserMobleTel("");
        } else {
            pow.setUserMobleTel(json.get("user_moble_tel").getAsString());
        }

        powerStationDao.save(pow);

        //保存图片信息
        if (json.get("images") != null) {
            List listData = new Gson().fromJson(json.get("images"), List.class);
          //  System.out.println("listData" + listData);
            List<PowerStationImgs> imgs = Lists.newArrayList();
            for (int i = 0; i < listData.size(); i++) {
                Map<String, String> map = (Map<String, String>) listData.get(i);
               // System.out.println(map);
                PowerStationImgs img = new PowerStationImgs();
                img.setPictureName(map.get("picture_name"));
                img.setPictureUrl(map.get("picture_url"));
                img.setPowerStationId(pow.getId());
                imgs.add(img);
            }
            powerImgsDao.save(imgs);
        }


        return pow.getId();
    }


    public Result savePowerStationDevice(JsonObject json, JsonObject json4, String userId, String power_station_id) {

        List listData = new Gson().fromJson(json.get("pageList"), List.class);
        if (listData==null || listData.size() == 0) {
            return Result.fail("202", "数据为空");
        }
        //删除以前电站设备信息
        SQLQuery sqlQuery = powDeviceDao.getSession().createSQLQuery("DELETE FROM crm_power_station_device WHERE power_station_id= :psId ");
        sqlQuery.setParameter("psId", power_station_id);
        sqlQuery.executeUpdate();
        //  Db.update("DELETE FROM crm_power_station_device WHERE power_station_id=? ",power_station_id);

        List<PowerStationDevice> list = Lists.newArrayList();
        for (int i = 0; i < listData.size(); i++) {
            Map<String, Object> map1 = (Map<String, Object>) listData.get(i);
            PowerStationDevice dev = new PowerStationDevice();
            dev.setDeviceCode(map1.get("device_code") != null ? convertDoubleToString(map1, "device_code") : "");
            dev.setDeviceType(map1.get("device_type") != null ? convertDoubleToString(map1, "device_type") : "");
            dev.setDeviceModel(map1.get("device_model") != null ? map1.get("device_model").toString() : "");
            dev.setDeviceModelId(map1.get("device_model_id") != null ? convertDoubleToString(map1, "device_model_id") : "");
            dev.setDeviceName(map1.get("device_name") != null ? map1.get("device_name").toString() : "");
            dev.setDeviceProSn(map1.get("device_pro_sn") != null ? map1.get("device_pro_sn").toString() : "");
            dev.setFactoryName(map1.get("factory_name") != null ? map1.get("factory_name").toString() : "");
            dev.setPowerStationId(power_station_id);
            dev.setRelState(map1.get("rel_state") != null ? convertDoubleToString(map1, "rel_state") : "");
            dev.setSn(map1.get("sn") != null ? map1.get("sn").toString() : "");
            dev.setSubTypeName(map1.get("sub_type_name") != null ? map1.get("sub_type_name").toString() : "");
            dev.setTypeName(map1.get("type_name") != null ? map1.get("type_name").toString() : "");
            dev.setUserId(userId);
            dev.setCreateTime(new Date());
            dev.setRatedPower(json4.get("design_capacity") != null ? json4.get("design_capacity").getAsString() : "");
            list.add(dev);
        }
        powDeviceDao.save(list);


        return Result.ok();
    }


    public PowerStation getPowerStationByuserId(String userId) {
        return powerStationDao.getPowerStationByuserId(userId);
    }

    public PowerStation getPowerStationById(String id) {
        return powerStationDao.getPowerStationById(id);
    }

    /**
     * 针对云接口获取的double型数据 转换成String型
     *
     * @param map
     * @param key
     * @return
     */
    public String convertDoubleToString(Map<String, Object> map, String key) {
        String str;
        try {
            Double value = Double.valueOf(map.get(key).toString());
            if (value != null) {
                str = String.valueOf(value.longValue());
            } else {
                str = map.get(key).toString();
            }
        } catch (Exception e) {
            str = map.get(key).toString();
        }
        return str;
    }

    /**
     * 获取电站设备信息列表
     */
    public List<Record> getDeviceList(String userId, String id) {
        SqlBuilder sb = new SqlBuilder()
                .line("SELECT * ")
                .line("FROM crm_power_station_device a")
                .line("WHERE a.`power_station_id` = ? AND a.`user_id` = ? ")
                .line("ORDER BY a.id ASC");
        List<Record> list = Db.find(sb.build(), id, userId);
        return list;
    }

    public List<PowerStationDevice> getListByPowerStationId(String id, String userId) {
        return powDeviceDao.getListByPowerStationId(id, userId);
    }

    /**
     * 删除设备信息
     */
    public void updateStatus(String id) {
        powDeviceDao.updateStatus(id);
    }

    /**
     * 新增设备信息
     */
    public void savePowerStationDevice(PowerStationDevice device) {
        powDeviceDao.save(device);
    }

    public void updateStationDevice(Map<String, String> map) {
        PowerStationDevice device = powDeviceDao.get(map.get("id"));
        device.setDeviceName(map.get("deviceName"));
        device.setDeviceModel(map.get("deviceModel"));
        device.setFactoryName(map.get("factoryName"));
        device.setRatedPower(map.get("ratedPower"));
        device.setDeviceProSn(map.get("deviceProSn"));
        device.setDeviceType(map.get("deviceType"));
        device.setTypeName(map.get("typeName"));
        device.setSn(map.get("sn"));
        powDeviceDao.save(device);
    }

    /**
     * 修改电站信息
     */
    public void updatePowerStation(Map<String, String> map) {
        PowerStation pow = powerStationDao.get(map.get("id"));
        pow.setProvince(map.get("province"));
        pow.setCity(map.get("city"));
        pow.setArea(map.get("area"));
        pow.setLocation(map.get("location"));
        pow.setPsName(map.get("psName"));
        pow.setDesignCapacity(map.get("designCapacity"));
        pow.setDescription(map.get("description"));
        pow.setExpectInstallDate(map.get("expectInstallDate"));
        powerStationDao.save(pow);
    }

}
