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

import com.mx.cneeds.common.dto.DeviceChannelDto;
import com.mx.cneeds.common.dto.DeviceChannelStatisticsDto;
import com.mx.cneeds.common.dto.DeviceInfoDto;
import com.mx.cneeds.common.dto.SeriesDto;
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.DeviceChannelService;
import com.mx.cneeds.server.device.service.DeviceInfoChannelService;
import com.mx.cneeds.server.device.service.DeviceInfoService;
import com.mx.cneeds.server.entity.DeviceChannelEntity;
import com.mx.cneeds.server.entity.DeviceInfoChannelEntity;
import com.mx.cneeds.server.entity.DeviceInfoEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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;

import java.util.*;

/**
 * @ClassName DeviceChannelController
 * @Author zzrdark
 * @Date 2020-05-11 17:51
 * @Description TODO
 **/

@RestController
@RequestMapping("device/devicechannel")
public class DeviceChannelController {

    @Autowired
    private DeviceChannelService deviceChannelService;

    @Autowired
    private DeviceInfoChannelService deviceInfoChannelService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params){
        PageUtils page = deviceChannelService.queryPage(params);
        List<DeviceChannelDto> list = new ArrayList<DeviceChannelDto>();
        for (Object entity : page.getList()){
            DeviceChannelDto dto = new DeviceChannelDto();
            DeviceChannelEntity deviceChannelEntity = (DeviceChannelEntity) entity;
            BeanUtils.copyProperties(deviceChannelEntity,dto);
            list.add(dto);
        }
        page.setList(list);
        return page;
    }


    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody DeviceChannelDto deviceChannelDto){
        DeviceChannelEntity deviceChannelEntity = new DeviceChannelEntity();
        BeanUtils.copyProperties(deviceChannelDto,deviceChannelEntity);


        deviceChannelEntity.setUpdateTime(new Date());
        deviceChannelService.save(deviceChannelEntity);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody DeviceChannelDto deviceChannelDto){
        ValidatorUtils.validateEntity(deviceChannelDto);
        DeviceChannelEntity deviceChannelEntity = new DeviceChannelEntity();
        BeanUtils.copyProperties(deviceChannelDto,deviceChannelEntity);

        deviceChannelEntity.setUpdateTime(new Date());
        deviceChannelService.updateById(deviceChannelEntity);

        return R.ok();
    }

    /**
     * 删除渠道号
     */
    @RequestMapping("/delete")
    @Transactional
    public R delete(@RequestBody Long[] deviceIds){
        deviceChannelService.removeByIds(Arrays.asList(deviceIds));
        deviceInfoChannelService.removeDeivceInfoChannelByChannelId(Arrays.asList(deviceIds));
        return R.ok();
    }


    @RequestMapping("/queryDeviceChannel")
    public DeviceChannelDto queryDeviceChannel(String channelNum){
        DeviceChannelEntity deviceChannelEntity = deviceChannelService.queryDeviceChannel(channelNum);
        DeviceChannelDto dto = new DeviceChannelDto();
        if (deviceChannelEntity == null) {
            return null;
        }
        BeanUtils.copyProperties(deviceChannelEntity,dto);

        return dto;
    }


    @RequestMapping("/queryDeviceChannelAll")
    public List<DeviceChannelDto> queryDeviceChannelAll(){
        List<DeviceChannelEntity> deviceChannelEntities = deviceChannelService.list();
        List<DeviceChannelDto> deviceChannelDtos = new ArrayList<>();
        deviceChannelEntities.forEach(e -> {
            DeviceChannelDto dto = new DeviceChannelDto();
            BeanUtils.copyProperties(e,dto);
            deviceChannelDtos.add(dto);
        });

        return deviceChannelDtos;
    }

    /**
     * 删除(还原)设置的渠道号
     */
    @RequestMapping("/deleteSettingDeviceChannel")
    @Transactional(rollbackFor = Exception.class)
    public void deleteSettingDeviceChannel(@RequestBody Long deviceId){
        DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
        deviceInfoEntity.setDeviceId(deviceId);
        deviceInfoEntity.setChannelRules(1);
        deviceInfoService.updateById(deviceInfoEntity);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device_id",deviceId);
        deviceInfoChannelService.removeByMap(stringObjectHashMap);
    }

    @RequestMapping("/updateSettingDeviceChannel")
    @Transactional(rollbackFor = Exception.class)
    public void updateSettingDeviceChannel(@RequestBody DeviceInfoDto deviceInfoDto){
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device_id",deviceInfoDto.getDeviceId());
        deviceInfoChannelService.removeByMap(stringObjectHashMap);

        List<DeviceInfoChannelEntity> deviceInfoChannelEntities = new LinkedList<>();
        for (Long channelId : deviceInfoDto.getChannelIds()){
            DeviceInfoChannelEntity deviceInfoChannelEntity = new DeviceInfoChannelEntity();
            deviceInfoChannelEntity.setChannelId(channelId);
            deviceInfoChannelEntity.setDeviceId(deviceInfoDto.getDeviceId());
            deviceInfoChannelEntities.add(deviceInfoChannelEntity);
        }
        deviceInfoChannelService.saveBatch(deviceInfoChannelEntities);

        DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
        deviceInfoEntity.setDeviceId(deviceInfoDto.getDeviceId());
        deviceInfoEntity.setChannelRules(deviceInfoDto.getChannelRules());
        deviceInfoEntity.setChannelNumsMessage(deviceInfoDto.getChannelNumsMessage());
        deviceInfoService.updateById(deviceInfoEntity);
    }

    @RequestMapping("/queryTotalStatisticsDeviceChannel")
    public List<DeviceChannelStatisticsDto> queryTotalStatisticsDeviceChannel(@RequestBody(required = false) List<Long> channelIds){
        List<DeviceInfoChannelEntity> deviceInfoChannelEntities = null;
        if (channelIds == null || channelIds.size() == 0) {
            deviceInfoChannelEntities = deviceInfoChannelService.list();
        }else {
            deviceInfoChannelEntities = deviceInfoChannelService.queryDeviceInfoChannelByChannelIds(channelIds);
        }

        Set<Long> deviceIds = new HashSet<>();
        Map<Long,List<Long>> deviceIdChannelMap = new HashMap<Long,List<Long>>();
        deviceInfoChannelEntities.forEach(deviceInfoChannel -> {
            deviceIds.add(deviceInfoChannel.getDeviceId());
            if (deviceIdChannelMap.get(deviceInfoChannel.getChannelId()) == null) {
                deviceIdChannelMap.put(deviceInfoChannel.getChannelId(),new ArrayList<Long>());
            }
            List<Long> deviceList = deviceIdChannelMap.get(deviceInfoChannel.getChannelId());
            deviceList.add(deviceInfoChannel.getDeviceId());
            deviceIdChannelMap.put(deviceInfoChannel.getChannelId(),deviceList);
        });
        

        List<DeviceInfoEntity> deviceInfoEntities = deviceInfoService.queryDeviceByIds(deviceIds);

        Map<Long,DeviceInfoEntity> deviceInfoEntityMapBykeyId = new HashMap<>();

        deviceInfoEntities.forEach(deviceInfoEntity -> {
            deviceInfoEntityMapBykeyId.put(deviceInfoEntity.getDeviceId(),deviceInfoEntity);
        });

        Map<String,List<DeviceInfoDto>> map = new HashMap<String,List<DeviceInfoDto>>();
        /**
         * 根据渠道号, 客户 ，渠道规则，禁用提示问题 进行统计
         */

        // TODO  无参数的统计 无法筛选  channelIds 因为这个空
        channelIds.forEach(channelId -> {
            List<Long> deviceIdList = deviceIdChannelMap.get(channelId);
            deviceIdList.forEach(deviceId -> {
                DeviceInfoEntity deviceInfoEntity = deviceInfoEntityMapBykeyId.get(deviceId);
                DeviceInfoDto dto = new DeviceInfoDto();
                BeanUtils.copyProperties(deviceInfoEntity,dto);

                StringBuffer sb = new StringBuffer();
                sb.append(channelId+"__");
                sb.append(dto.getDeptId()+"__");
                sb.append(dto.getChannelRules()+"__");
                sb.append(dto.getChannelNumsMessage());


                if (map.get(sb.toString()) == null) {
                    map.put(sb.toString(),new ArrayList<DeviceInfoDto>());
                }

                List<DeviceInfoDto> deviceInfoList = map.get(sb.toString());
                deviceInfoList.add(dto);
                map.put(sb.toString(),deviceInfoList);
            });
        });




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

        map.forEach((key,value) -> {
            String[] s = key.split("__");
            DeviceChannelStatisticsDto dto = new DeviceChannelStatisticsDto();

            dto.setChannelNum(s[0]);
            dto.setDeptId(Long.valueOf(s[1]));
            dto.setChannelRules(Integer.valueOf(s[2]));
            dto.setChannelNumsMessage(s[3]);

            dto.setDeviceInfoDtos(value);

            list.add(dto);
        });

        return list;

    }


}
