package com.mortals.xhx.daemon.task;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.device.DevicePdu;
import com.mortals.xhx.common.pdu.site.SiteMatterPdu;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.feign.device.IDeviceFeign;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.feign.site.ISiteMatterFeign;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.sheet.model.SheetMatterEntity;
import com.mortals.xhx.module.sheet.model.SheetMatterQuery;
import com.mortals.xhx.module.sheet.service.SheetMatterService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

/**
 * 同步事项列表
 */
@Slf4j
@Service("SyncSiteDeviceTask")
public class SyncSiteDeviceTaskImpl implements ITaskExcuteService {

    @Autowired
    private ISiteFeign siteFeign;
    @Autowired
    private IDeviceFeign deviceFeign;
    @Autowired
    private DeviceService deviceService;

    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("开始同步设备列表！");
        SitePdu sitePdu = new SitePdu();
        sitePdu.setId(1L);
        Rest<List<SitePdu>> siteRest = siteFeign.getFlatSitesBySiteId(sitePdu);
        if (siteRest.getCode() == YesNoEnum.YES.getValue()) {
            log.info("站点总数量：{}", siteRest.getData().size());
            siteRest.getData().forEach(site -> {
                log.info("站点名称:{}",site.getSiteName());
                DevicePdu devicePdu = new DevicePdu();
                devicePdu.setProductCode("ybj");
                devicePdu.setSize(-1);
                Rest<RespData<List<DevicePdu>>> deviceRest = deviceFeign.list(devicePdu);
                log.info("deviceRest：{}",JSON.toJSONString(deviceRest));
                if (YesNoEnum.YES.getValue() == deviceRest.getCode()) {
                    List<DevicePdu> devicePduList = deviceRest.getData().getData();
                    log.info("样表机总数量：{}", devicePduList.size());
                    if (!ObjectUtils.isEmpty(devicePduList)) {
                        List<DeviceEntity> newDeviceList = devicePduList.stream().map(newDevice -> {
                            DeviceEntity deviceEntity = new DeviceEntity();
                            deviceEntity.initAttrValue();
                            BeanUtils.copyProperties(newDevice, deviceEntity, BeanUtil.getNullPropertyNames(newDevice));
                            return deviceEntity;
                        }).collect(Collectors.toList());

                        List<DeviceEntity> oldDeviceList = deviceService.find(new DeviceQuery().siteId(site.getId()));
                        Map<String, DeviceEntity> oldDeviceMap = oldDeviceList.stream().collect(Collectors.toMap(x -> x.getDeviceCode(), y -> y, (o, n) -> n));
                        List<DeviceEntity> updateDeviceLsit = newDeviceList.stream().map(item -> {
                            if (oldDeviceMap.containsKey(item.getDeviceCode())) {
                                item.setId(oldDeviceMap.get(item.getDeviceCode()).getId());
                                item.setDeviceId(item.getId());
                                item.setUpdateTime(new Date());
                                return item;
                            }
                            return null;
                        }).filter(f -> f != null).collect(Collectors.toList());


                        List<DeviceEntity> saveDeviceList = newDeviceList.stream().map(item -> {
                            if (!oldDeviceMap.containsKey(item.getDeviceCode())) {
                                item.setDeviceId(item.getId());
                                item.setCreateUserId(1L);
                                item.setCreateUserName("系统管理员");
                                item.setCreateTime(new Date());
                                return item;
                            }
                            return null;
                        }).filter(f -> f != null).collect(Collectors.toList());

                        if (!ObjectUtils.isEmpty(updateDeviceLsit)) {
                            log.info("设备更新，size:{}", updateDeviceLsit.size());
                            deviceService.update(updateDeviceLsit);
                        }

                        if (!ObjectUtils.isEmpty(saveDeviceList)) {
                            log.info("设备新增，size:{}", saveDeviceList.size());
                            deviceService.save(saveDeviceList);
                        }
                    }
                } else {
                    log.info("设备列表查询异常，{}", JSON.toJSONString(deviceRest));
                }
            });
        } else {
            log.info("站点列表查询异常，{}", JSON.toJSONString(siteRest));
        }
    }

    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
