package com.mortals.xhx.daemon.task;

import cn.hutool.core.util.StrUtil;
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.pdu.skin.SkinBasePdu;
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.feign.skin.ISkinBaseFeign;
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 com.mortals.xhx.module.skin.model.SkinEntity;
import com.mortals.xhx.module.skin.model.SkinQuery;
import com.mortals.xhx.module.skin.service.SkinService;
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.sql.Struct;
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;
    @Autowired
    private SkinService skinService;
    @Autowired
    private ISkinBaseFeign skinBaseFeign;

    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("开始同步设备列表！");
        syncDevice();
        log.info("结束同步设备列表！");

        log.info("开始同步皮肤列表！");
        syncSkin();
        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("ybj");
                devicePdu.setProductId(10L);
                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.setDeviceId(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));
        }
    }

    private void syncSkin() {

        SkinBasePdu skinBasePdu = new SkinBasePdu();
        skinBasePdu.setProductName("样表机");
        skinBasePdu.setSize(-1);

        Rest<RespData<List<SkinBasePdu>>> skinBaseRest = skinBaseFeign.list(skinBasePdu);
        if (skinBaseRest.getCode() == YesNoEnum.YES.getValue()) {
            List<SkinBasePdu> skinBasePduList = skinBaseRest.getData().getData();
            log.info("样表机皮肤总数量：{}", skinBasePduList.size());
            if (!ObjectUtils.isEmpty(skinBasePduList)) {
                List<SkinEntity> newSkinList = skinBasePduList.stream().map(newSkin -> {
                    SkinEntity skinEntity = new SkinEntity();
                    skinEntity.initAttrValue();
                    //存相对地址
                    newSkin.setCssFilePath("/"+StrUtil.subAfter(newSkin.getCssFilePath(), "/", true));
                    newSkin.setPreviewImagePath("/"+StrUtil.subAfter(newSkin.getPreviewImagePath(), "/", true));
                    BeanUtils.copyProperties(newSkin, skinEntity, BeanUtil.getNullPropertyNames(newSkin));
                    return skinEntity;
                }).collect(Collectors.toList());

                List<SkinEntity> oldSkinList = skinService.find(new SkinQuery());
                Map<Long, SkinEntity> oldSkinMap = oldSkinList.stream().collect(Collectors.toMap(x -> x.getId(), y -> y, (o, n) -> n));
                Map<Long, SkinEntity> newSkinMap = newSkinList.stream().collect(Collectors.toMap(x -> x.getId(), y -> y, (o, n) -> n));

                List<SkinEntity> updateSkinLsit = newSkinList.stream().map(item -> {
                    if (oldSkinMap.containsKey(item.getId())) {
                        item.setUsed(oldSkinMap.get(item.getId()).getUsed());
                        item.setUpdateTime(new Date());
                        return item;
                    }
                    return null;
                }).filter(f -> f != null).collect(Collectors.toList());

                List<SkinEntity> saveSkinList = newSkinList.stream().map(item -> {
                    if (!oldSkinMap.containsKey(item.getId())) {
                        item.setCreateUserId(1L);
                        item.setCreateUserName("系统管理员");
                        item.setCreateTime(new Date());
                        return item;
                    }
                    return null;
                }).filter(f -> f != null).collect(Collectors.toList());


                //做差集
                List<Long> delSkinList = oldSkinList.stream().map(item -> {
                    if (!newSkinMap.containsKey(item.getId())) {
                        return item.getId();
                    }
                    return null;
                }).filter(f -> f != null).collect(Collectors.toList());


//                if (!ObjectUtils.isEmpty(updateSkinLsit)) {
//                    log.info("皮肤更新，size:{}", updateSkinLsit.size());
//                    skinService.update(updateSkinLsit);
//                }

                if (!ObjectUtils.isEmpty(saveSkinList)) {
                    log.info("皮肤新增，size:{}", saveSkinList.size());
                    skinService.save(saveSkinList);
                }

                if (!ObjectUtils.isEmpty(delSkinList)) {
                    log.info("皮肤删除，size:{}", delSkinList.size());
                    skinService.remove(delSkinList, null);
                }

            }
        }
    }

    @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));

    }
}
