package org.nl.acs.route.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.AllArgsConstructor;
import org.nl.acs.route.domain.RouteLoc;
import org.nl.acs.route.service.RouteLocService;
import org.nl.acs.route.service.dto.RouteLocDto;
import org.nl.acs.route.service.dto.RouteLocQueryParam;
import org.nl.acs.route.service.mapper.RouteLocMapper;
import org.nl.acs.common.base.PageInfo;
import org.nl.acs.common.base.QueryHelpMybatisPlus;
import org.nl.acs.common.base.impl.CommonServiceImpl;
import org.nl.common.exception.BadRequestException;
import org.nl.acs.utils.ConvertUtil;
import org.nl.common.utils.FileUtil;
import org.nl.acs.utils.PageUtil;
import org.nl.common.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @author jiaolm
* @date 2023-05-09
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = RouteLocService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RouteLocServiceImpl extends CommonServiceImpl<RouteLocMapper, RouteLoc> implements RouteLocService {

    // private final RedisUtils redisUtils;
    private final RouteLocMapper routeLocMapper;

    @Override
    public PageInfo<RouteLocDto> queryAll(RouteLocQueryParam query, Pageable pageable) {
        IPage<RouteLoc> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<RouteLoc> page = routeLocMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, RouteLocDto.class);
    }

    @Override
    public List<RouteLocDto> queryAll(RouteLocQueryParam query){
        return ConvertUtil.convertList(routeLocMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), RouteLocDto.class);
    }

    @Override
    public RouteLoc getById(String id) {
        return routeLocMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public RouteLocDto findById(String id) {
        return ConvertUtil.convert(getById(id), RouteLocDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(RouteLocDto resources) {
        RouteLoc entity = ConvertUtil.convert(resources, RouteLoc.class);
        return routeLocMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(RouteLocDto resources){
        RouteLoc entity = ConvertUtil.convert(resources, RouteLoc.class);
        int ret = routeLocMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<String> ids){
        // delCaches(ids);
        return routeLocMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(String id){
        Set<String> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(String id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<String> ids) {
        for (String id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<RouteLocDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (RouteLocDto routeLoc : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("设备编码", routeLoc.getDeviceCode());
              map.put("坐标值", routeLoc.getIocValue());
              map.put("路由方案标识", routeLoc.getRoutePlanId());
              map.put("备注", routeLoc.getRemark());
              map.put("是否启用", routeLoc.getIsActive());
              map.put("是否删除", routeLoc.getIsDelete());
              map.put("创建者", routeLoc.getCreateBy());
              map.put("创建时间", routeLoc.getCreateTime());
              map.put("修改者", routeLoc.getUpdateBy());
              map.put("修改时间", routeLoc.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/

    @Override
    public Map<String, Object> queryAll(Map whereJson, Pageable page) {
        IPage<RouteLoc> queryPage = PageUtil.toMybatisPage(page);
        LambdaQueryWrapper<RouteLoc> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(RouteLoc::getUpdate_time);
        IPage<RouteLoc> IPage = routeLocMapper.selectPage(queryPage,wrapper);
        final JSONObject json = (JSONObject) JSON.toJSON(ConvertUtil.convertPage(IPage, RouteLoc.class));
        return json;
    }

    @Override
    public List<RouteLocDto> queryAll(Map whereJson) {
        List<RouteLoc>  list= new LambdaQueryChainWrapper<>(routeLocMapper)
                .list();
        return ConvertUtil.convertList(list, RouteLocDto.class);
    }

//    @Override
//    public RouteLocDto findById(String ioc_uuid) {
//        WQLObject wo = WQLObject.getWQLObject("acs_route_loc");
//        JSONObject json = wo.query("ioc_uuid ='" + ioc_uuid + "'").uniqueResult(0);
//        final RouteLocDto obj = json.toJavaObject(RouteLocDto.class);
//        return obj;
//    }

//    @Override
//    public RouteLocDto findByCode(String code) {
//        WQLObject wo = WQLObject.getWQLObject("acs_route_loc");
//        JSONObject json = wo.query("code ='" + code + "'").uniqueResult(0);
//        final RouteLocDto obj = json.toJavaObject(RouteLocDto.class);
//        return obj;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(RouteLocDto dto) {
        String currentUsername = SecurityUtils.getCurrentUsername();
        String now = DateUtil.now();

        dto.setIoc_uuid(IdUtil.simpleUUID());
        dto.setCreate_by(currentUsername);
        dto.setUpdate_by(currentUsername);
        dto.setUpdate_time(now);
        dto.setCreate_time(now);

        RouteLoc entity = ConvertUtil.convert(dto, RouteLoc.class);
        routeLocMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(RouteLocDto dto) {
        RouteLocDto entity = this.findById(dto.getIoc_uuid());
        if (entity == null) throw new BadRequestException("被删除或无权限，操作失败!");

        String currentUsername = SecurityUtils.getCurrentUsername();
        String now = DateUtil.now();
        dto.setUpdate_time(now);
        dto.setUpdate_by(currentUsername);

        RouteLoc routeLoc = ConvertUtil.convert(dto, RouteLoc.class);
        routeLocMapper.updateById(routeLoc);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(String[] ids) {
        for (String ioc_uuid : ids) {
            routeLocMapper.deleteById(ioc_uuid);
        }
    }

    @Override
    public void download(List<RouteLocDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RouteLocDto routeLoc : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("设备编码", routeLoc.getDevice_code());
            map.put("坐标值", routeLoc.getIoc_value());
            map.put("路由方案标识", routeLoc.getRoute_plan_id());
            map.put("备注", routeLoc.getRemark());
            map.put("是否启用", routeLoc.getIs_active());
            map.put("是否删除", routeLoc.getIs_delete());
            map.put("创建者", routeLoc.getCreate_by());
            map.put("创建时间", routeLoc.getCreate_time());
            map.put("修改者", routeLoc.getUpdate_by());
            map.put("修改时间", routeLoc.getUpdate_time());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
