package com.mx.cneeds.server.device.web;

import java.util.*;

import com.mx.cneeds.common.dto.*;
import com.mx.cneeds.common.pager.PageUtils;
import com.mx.cneeds.common.result.R;
import com.mx.cneeds.common.validator.ValidatorUtils;
import com.mx.cneeds.server.device.service.*;
import com.mx.cneeds.server.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;



/**
 * 设备信息
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-03-18 14:44:30
 */
@RestController
@RequestMapping("device/info")
public class DeviceInfoController {
    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private DeviceChannelService deviceChannelService;

    @Autowired
    private DeviceInfoChannelService deviceInfoChannelService;

    @Autowired
    private ProductSeriesService productSeriesService;

    @Autowired
    private DeviceInfoExportService deviceInfoExportService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params){
        PageUtils page = deviceInfoService.queryPage(params);
        List<DeviceInfoDto> list = new ArrayList<DeviceInfoDto>();
        for (Object entity : page.getList()){
            DeviceInfoDto dto = new DeviceInfoDto();
            DeviceInfoEntity deviceInfoEntity = (DeviceInfoEntity) entity;
            BeanUtils.copyProperties(deviceInfoEntity,dto);

            List<DeviceInfoChannelEntity> deviceInfoChannelEntities =
                    deviceInfoChannelService
                            .queryDeviceInfoChannelByDeviceId(deviceInfoEntity.getDeviceId());
            List<Long> deviceChannelArray = new LinkedList<>();

            deviceInfoChannelEntities.forEach( entities -> {
                deviceChannelArray.add(entities.getChannelId());
            });
            if (deviceChannelArray != null && deviceChannelArray.size() != 0){
                List<DeviceChannelEntity> deviceChannelEntities = deviceChannelService.queryDeviceChannelByids(deviceChannelArray);
                StringBuffer sb = new StringBuffer();

                deviceChannelEntities.forEach(entities -> {
                    sb.append(entities.getChannelNum()+",");
                });

                if (sb.length() != 0){
                    dto.setChannelNums(sb.substring(0,sb.length()-1));
                }

            }
            list.add(dto);
        }
        page.setList(list);

        return page;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{deviceId}")
    public R info(@PathVariable("deviceId") Long deviceId){
        DeviceInfoEntity deviceInfo = deviceInfoService.getById(deviceId);

        return R.ok().put("deviceInfo", deviceInfo);
    }

    /**
     * 信息
     * 会查出设备信息渠道号信息
     */
    @RequestMapping("/infoByImei")
    public DeviceInfoDto infoByimei(@RequestBody String imei){
        DeviceInfoEntity deviceInfoEntity = deviceInfoService.queryDeviceByImei(imei);
        DeviceInfoDto deviceInfoDto = new DeviceInfoDto();
        if (deviceInfoEntity != null){
            BeanUtils.copyProperties(deviceInfoEntity,deviceInfoDto);

            if (deviceInfoEntity.getSeriesId()!=null){
                ProductSeriesEntity seriesEntity = productSeriesService.queryOne(deviceInfoEntity.getSeriesId());
                deviceInfoDto.setSeriesNum(seriesEntity.getSeriesNum());
            }

            List<DeviceInfoChannelEntity> deviceInfoChannelEntities =
                    deviceInfoChannelService
                            .queryDeviceInfoChannelByDeviceId(deviceInfoEntity.getDeviceId());
            List<Long> deviceChannelArray = new LinkedList<>();

            deviceInfoChannelEntities.forEach( entities -> {
                deviceChannelArray.add(entities.getChannelId());
            });
            if (deviceChannelArray != null && deviceChannelArray.size() != 0){
                List<DeviceChannelEntity> deviceChannelEntities = deviceChannelService.queryDeviceChannelByids(deviceChannelArray);
                StringBuffer sb = new StringBuffer();

                deviceChannelEntities.forEach(entities -> {
                    sb.append(entities.getChannelNum()+",");
                });
                if (sb.length() != 0) {
                    deviceInfoDto.setChannelNums(sb.substring(0, sb.length() - 1));
                }
            }
            return deviceInfoDto;
        }else{
            return null;
        }
    }

    /**
     * 批量查询设备信息，
     * 但是不查出设备渠道号信息
     * @param imeis
     * @return
     */
    @RequestMapping("/infoByImeis")
    public List<DeviceInfoDto> infoByimeis(@RequestBody List<String> imeis){
        List<DeviceInfoEntity> deviceInfoEntities = deviceInfoService.queryDeviceByImeis(imeis);
        List<DeviceInfoDto> deviceInfoDtos = new ArrayList<>();
        for (DeviceInfoEntity deviceInfoEntity : deviceInfoEntities) {
            DeviceInfoDto dto = new DeviceInfoDto();
            BeanUtils.copyProperties(deviceInfoEntity,dto);
            deviceInfoDtos.add(dto);
        }

        return deviceInfoDtos;
    }

    @RequestMapping("/infoByIds")
    public List<DeviceInfoDto> infoByIds(@RequestBody Set<Long> ids){
        List<DeviceInfoEntity> deviceInfoEntitys = deviceInfoService.queryDeviceByIds(ids);

        List<DeviceInfoDto> deviceInfoDtos = new ArrayList<>();
        deviceInfoEntitys.forEach(deviceInfoEntity -> {
            DeviceInfoDto deviceInfoDto = new DeviceInfoDto();
            BeanUtils.copyProperties(deviceInfoEntity,deviceInfoDto);
            deviceInfoDtos.add(deviceInfoDto);
        });
        return deviceInfoDtos;
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody DeviceInfoEntity deviceInfo){
        deviceInfoService.save(deviceInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody DeviceInfoEntity deviceInfo){
        ValidatorUtils.validateEntity(deviceInfo);
        deviceInfoService.updateById(deviceInfo);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/updateByImei")
    public R updateByImei(@RequestBody DeviceInfoDto dto){
        DeviceInfoEntity deviceInfo = new DeviceInfoEntity();

        BeanUtils.copyProperties(dto,deviceInfo);

        ValidatorUtils.validateEntity(deviceInfo);
        deviceInfoService.updateByImei(deviceInfo);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] deviceIds){
        deviceInfoService.removeByIds(Arrays.asList(deviceIds));

        return R.ok();
    }

    /**
     * 保存
     */
    @RequestMapping("/importDevice")
    public R importDevice(@RequestBody DevicesDto devicesDto){
        List<DeviceInfoEntity> deviceInfoEntityList = new LinkedList<>();
        if (devicesDto.getImeis() != null && devicesDto.getImeis().size() != 0) {
            devicesDto.getImeis().forEach(str -> {
                DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
                deviceInfoEntity.setImei(str);
                deviceInfoEntity.setSeriesId(devicesDto.getSeriesId());
                deviceInfoEntity.setDeptId(devicesDto.getDeptId());
                deviceInfoEntity.setCreateTime(new Date());
                deviceInfoEntityList.add(deviceInfoEntity);
            });
        }
        deviceInfoService.saveBatch(deviceInfoEntityList);
        return R.ok();
    }


    /**
     * 保存
     */
    @RequestMapping("/updateDeviceSeriesBatch")
    public R updateDeviceSeriesBatch(@RequestBody DevicesDto devicesDto){
        List<DeviceInfoEntity> deviceInfoEntityList = new LinkedList<>();
        if (devicesDto.getImeis() != null && devicesDto.getImeis().size() != 0) {
            devicesDto.getImeis().forEach(str -> {
                DeviceInfoEntity queryDeviceByImei = deviceInfoService.queryDeviceByImei(str);
                if (queryDeviceByImei != null){
                    DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
                    deviceInfoEntity.setImei(str);
                    deviceInfoEntity.setSeriesId(devicesDto.getSeriesId());
                    deviceInfoEntity.setDeptId(devicesDto.getDeptId());
                    deviceInfoEntityList.add(deviceInfoEntity);
                }
            });
        }
        deviceInfoService.updateBatchByImei(deviceInfoEntityList);

        return R.ok();
    }


    @RequestMapping("/queryDeviceChannelSetting")
    public List<String> queryDeviceChannelSetting(@RequestBody List<String> imeis){
        Set<Long> deviceIds = new HashSet<>();
        Set<String> ChannelSettingImeis = new HashSet<>();

        List<DeviceInfoEntity> entities =
                deviceInfoService.queryDeviceByImeis(imeis);

        entities.forEach(deviceInfoEntity -> {
            deviceIds.add(deviceInfoEntity.getDeviceId());
            if (deviceInfoEntity.getChannelRules() == null || deviceInfoEntity.getChannelRules() == 1){
                ChannelSettingImeis.add(deviceInfoEntity.getImei());
            }
        });

        List<DeviceInfoChannelEntity> deviceInfoChannelEntities =
                deviceInfoChannelService.queryDeviceInfoChannelByDeviceIds(new LinkedList<>(deviceIds));

        deviceInfoChannelEntities.forEach(deviceInfoChannelEntity -> {
            entities.forEach(deviceInfoEntity -> {
                if (deviceInfoEntity.getDeviceId().equals(deviceInfoChannelEntity.getDeviceId())){
                    ChannelSettingImeis.add(deviceInfoEntity.getImei());
                }
            });
        });
        return new LinkedList<>(ChannelSettingImeis);
    }

    /**
     * 批量保存渠道号
     * 保存
     */
    @RequestMapping("/updateDeviceChannelBatch")
    @Transactional(rollbackFor = Exception.class)
    public R updateDeviceChannelBatch(@RequestBody DevicesDto devicesDto){
        List<DeviceInfoEntity> deviceInfoEntityList = new LinkedList<>();
        List<DeviceInfoChannelEntity> deviceChannelEntities = new LinkedList<>();

        List<Long> deviceIds = new ArrayList<>();

        if (devicesDto.getImeis() != null && devicesDto.getImeis().size() != 0) {

            List<DeviceInfoEntity> entities =
                    deviceInfoService.queryDeviceByImeis(devicesDto.getImeis());

            devicesDto.getImeis().forEach(str -> {
                DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
                deviceInfoEntity.setImei(str);
                deviceInfoEntity.setChannelNumsMessage(devicesDto.getChannelNumsMessage());
                deviceInfoEntity.setChannelRules(devicesDto.getChannelRules());
                deviceInfoEntityList.add(deviceInfoEntity);

                devicesDto.getChannelNums().forEach(channelNum -> {
                    DeviceInfoChannelEntity infoChannel = new DeviceInfoChannelEntity();
                    entities.forEach(entity -> {
                        if (entity.getImei().equals(str)){
                            infoChannel.setDeviceId(entity.getDeviceId());
                            deviceIds.add(entity.getDeviceId());
                        }
                    });
                    infoChannel.setChannelId(channelNum);
                    deviceChannelEntities.add(infoChannel);

                });

            });
        }

        deviceInfoService.updateBatchByImei(deviceInfoEntityList);

        // 删除原来的
        deviceInfoChannelService.removeDeivceInfoChannelByDeviceIds(deviceIds);

        deviceInfoChannelService.saveBatch(deviceChannelEntities);
        return R.ok();
    }

    /**
     * 批量上传 渠道号和设备
     * @param dto
     */
    @RequestMapping("/uploadDeivceChannelExcel")
    @Transactional(rollbackFor = Exception.class)
    public void uploadDeivceChannelExcel(@RequestBody UploadDeviceChannelExcelDto dto){

        Set<String> imeiSet = new HashSet<>();

        List<DeviceInfoEntity> list = new LinkedList<>();

        List<DeviceInfoChannelEntity> deviceInfoChannelEntityList = new LinkedList<>();

        dto.getInfos().forEach(info -> {
            DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
            if (info.getImei() != null) {
                deviceInfoEntity.setImei(info.getImei());

                // 用来统一查询所有deviceId
                imeiSet.add(info.getImei());

                // 可有可无iccid
                if (info.getIccid() != null) {
                    deviceInfoEntity.setIccid(info.getIccid());
                }

                deviceInfoEntity.setCreateTime(new Date());
                deviceInfoEntity.setChannelNumsMessage(dto.getChannelNumsMessage());
                deviceInfoEntity.setChannelRules(dto.getChannelRules());
                deviceInfoEntity.setDeptId(dto.getDeptId());
                deviceInfoEntity.setSeriesId(dto.getSeriesId());
            }
            list.add(deviceInfoEntity);
        });

        // 先新增设备数据 以及 渠道部分数据
        deviceInfoService.saveBatch(list);

        // 查询新增加的设备号
        List<DeviceInfoEntity> deviceInfoEntities = deviceInfoService.queryDeviceByImeis(new LinkedList<>(imeiSet));

        // 增加渠道号
        deviceInfoEntities.forEach(deviceInfoEntity -> {
            dto.getChannelNums().forEach(channelId -> {
                DeviceInfoChannelEntity deviceInfoChannelEntity = new DeviceInfoChannelEntity();
                deviceInfoChannelEntity.setDeviceId(deviceInfoEntity.getDeviceId());
                deviceInfoChannelEntity.setChannelId(channelId);
                deviceInfoChannelEntityList.add(deviceInfoChannelEntity);
            });
        });
        deviceInfoChannelService.saveBatch(deviceInfoChannelEntityList);
    }

    /**
     * 批量上传设备
     * @param dto
     */
    @RequestMapping("/uploadDeivceExcel")
    public void uploadDeivceExcel(@RequestBody UploadDeviceChannelExcelDto dto){


        dto.getInfos().forEach(info -> {
            DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
            if (info.getImei() != null && deviceInfoService.queryDeviceByImei(info.getImei()) == null) {

                deviceInfoEntity.setImei(info.getImei());

                // 可有可无iccid
                if (info.getIccid() != null) {
                    deviceInfoEntity.setIccid(info.getIccid());
                }

                deviceInfoEntity.setCreateTime(new Date());
                deviceInfoEntity.setChannelNumsMessage(dto.getChannelNumsMessage());
                deviceInfoEntity.setChannelRules(dto.getChannelRules());
                deviceInfoEntity.setDeptId(dto.getDeptId());
                deviceInfoEntity.setSeriesId(dto.getSeriesId());
                deviceInfoService.save(deviceInfoEntity);
            }

        });

    }

    /**
     * 设备信息导出表的查询
     * @param params
     * @return
     */
    @RequestMapping("/deviceInfoExportList")
    public PageUtils deviceInfoExportList(@RequestParam Map<String, Object> params){
        PageUtils page = deviceInfoExportService.queryPage(params);
        List<DeviceInfoExportDto> list = new ArrayList<DeviceInfoExportDto>();
        for (Object entity : page.getList()){
            DeviceInfoExportDto dto = new DeviceInfoExportDto();
            DeviceInfoExportEntity deviceChannelEntity = (DeviceInfoExportEntity) entity;
            BeanUtils.copyProperties(deviceChannelEntity,dto);
            list.add(dto);
        }
        page.setList(list);
        return page;
    }

    @RequestMapping("/addDeviceInfoExport")
    public void addDeviceInfoExport(@RequestBody DeviceInfoExportDto deviceInfoExportDto){

        DeviceInfoExportEntity entity = new DeviceInfoExportEntity();
        BeanUtils.copyProperties(deviceInfoExportDto,entity);
        deviceInfoExportService.save(entity);
    }

    @RequestMapping("/deleteDeviceInfoExport")
    public void deleteDeviceInfoExport(@RequestBody Long deviceInfoExportId){

        deviceInfoExportService.removeById(deviceInfoExportId);
    }

    @RequestMapping("/deleteDeviceInfoExportByName")
    public void deleteDeviceInfoExportByName(@RequestBody String fileName){
        Map<String,Object> map = new HashMap<>();
        map.put("name",fileName);
        deviceInfoExportService.removeByMap(map);
    }

    @RequestMapping("updateDeviceInfoExport")
    public void updateDeviceInfoExport(@RequestBody DeviceInfoExportDto deviceInfoExportDto){
        DeviceInfoExportEntity entity = new DeviceInfoExportEntity();
        BeanUtils.copyProperties(deviceInfoExportDto,entity);
        deviceInfoExportService.saveOrUpdate(entity);
    }

}
