package com.mortals.xhx.daemon.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
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.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.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
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("开始同步设备列表！");
        syncDevice();
        log.info("结束同步设备列表！");

        log.info("开始同步皮肤列表！");
    }

    private void syncDevice() {
        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("xxgk");
                devicePdu.setProductId(23L);
                devicePdu.setSiteId(site.getId());
                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()));
                        log.info("siteId:{} oldDeviceList size：{}", site.getId(), oldDeviceList.size());

                        Map<String, DeviceEntity> oldDeviceMap = oldDeviceList.stream().collect(Collectors.toMap(x -> x.getDeviceCode(), y -> y, (o, n) -> n));
                        Map<String, DeviceEntity> newDeviceMap = newDeviceList.stream().collect(Collectors.toMap(x -> x.getDeviceCode(), y -> y, (o, n) -> n));

                        //log.info("oldDeviceMap：{}", JSON.toJSONString(oldDeviceMap));

                        List<DeviceEntity> updateDeviceLsit = newDeviceList.stream().map(item -> {
                            if (oldDeviceMap.containsKey(item.getDeviceCode())) {
                                item.setId(oldDeviceMap.get(item.getDeviceCode()).getId());
                               // item.setDeviceId(item.getId());
                                item.setProductCode(oldDeviceMap.get(item.getDeviceCode()).getProductCode());
                                item.setProductName(oldDeviceMap.get(item.getDeviceCode()).getProductName());
                                item.setUpdateTime(new Date());
                                return item;
                            }
                            return null;
                        }).filter(f -> f != null).collect(Collectors.toList());

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

                        //做差集
                        List<Long> delDeviceList = oldDeviceList.stream().map(item -> {
                            if (!newDeviceMap.containsKey(item.getDeviceCode())) {
                                return item.getId();
                            }
                            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);
                        }

                        if (!ObjectUtils.isEmpty(delDeviceList)) {
                            log.info("设备删除，size:{}", delDeviceList.size());
                            deviceService.remove(delDeviceList, null);
                        }
                    }
                } else {
                    log.info("设备列表查询异常，{}", JSON.toJSONString(deviceRest));
                }
            });
        } else {
            log.info("站点列表查询异常，{}", JSON.toJSONString(siteRest));
        }
    }



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

    }

    public static void main(String[] args) {
        String str = "http://10.12.185.213:11071/file%2Ffileupload%2F1682068396920.css";

        System.out.println(StrUtil.subAfter(str, "/", true));

    }
}
