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.JSONArray;
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.RoutePlan;
import org.nl.acs.route.service.RoutePlanService;
import org.nl.acs.route.service.dto.RoutePlanDto;
import org.nl.acs.route.service.dto.RoutePlanQueryParam;
import org.nl.acs.route.service.mapper.RoutePlanMapper;
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 = RoutePlanService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoutePlanServiceImpl extends CommonServiceImpl<RoutePlanMapper, RoutePlan> implements RoutePlanService {

    // private final RedisUtils redisUtils;
    private final RoutePlanMapper routePlanMapper;

    @Override
    public PageInfo<RoutePlanDto> queryAll(RoutePlanQueryParam query, Pageable pageable) {
        IPage<RoutePlan> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<RoutePlan> page = routePlanMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, RoutePlanDto.class);
    }

    @Override
    public List<RoutePlanDto> queryAll(RoutePlanQueryParam query){
        return ConvertUtil.convertList(routePlanMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), RoutePlanDto.class);
    }

    @Override
    public RoutePlan getById(String id) {
        return routePlanMapper.selectById(id);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(RoutePlanDto resources) {
        RoutePlan entity = ConvertUtil.convert(resources, RoutePlan.class);
        return routePlanMapper.insert(entity);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<String> ids){
        // delCaches(ids);
        return routePlanMapper.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<RoutePlanDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (RoutePlanDto routePlan : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("方案编码", routePlan.getPlanCode());
              map.put("方案名称", routePlan.getPlanName());
              map.put("备注", routePlan.getRemark());
              map.put("是否启用", routePlan.getIsActive());
              map.put("是否删除", routePlan.getIsDelete());
              map.put("创建者", routePlan.getCreateBy());
              map.put("创建时间", routePlan.getCreateTime());
              map.put("修改者", routePlan.getUpdateBy());
              map.put("修改时间", routePlan.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/

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

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

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

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

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

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

        RoutePlan entity = ConvertUtil.convert(dto, RoutePlan.class);
        routePlanMapper.insert(entity);
    }

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

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

        RoutePlan routePlan = ConvertUtil.convert(dto, RoutePlan.class);
        routePlanMapper.updateById(routePlan);
    }

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

    @Override
    public void download(List<RoutePlanDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RoutePlanDto routePlan : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("方案编码", routePlan.getPlan_code());
            map.put("方案名称", routePlan.getPlan_name());
            map.put("备注", routePlan.getRemark());
            map.put("是否启用", routePlan.getIs_active());
            map.put("是否删除", routePlan.getIs_delete());
            map.put("创建者", routePlan.getCreate_by());
            map.put("创建时间", routePlan.getCreate_time());
            map.put("修改者", routePlan.getUpdate_by());
            map.put("修改时间", routePlan.getUpdate_time());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public JSONArray selectList() {
        //路由计划表【acs_route_plan】
        List<RoutePlan> routePlanList= new LambdaQueryChainWrapper<>(routePlanMapper)
                .eq(RoutePlan::getIs_delete,"0")
                .eq(RoutePlan::getIs_active,"1")
                .list();
        JSONArray arr = JSONArray.parseArray(JSON.toJSONString(routePlanList));

        JSONArray result = new JSONArray();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject obj = arr.getJSONObject(i);
            JSONObject json = new JSONObject();
            json.put("plan_uuid", obj.getString("plan_uuid"));
            json.put("plan_code", obj.getString("plan_code"));
            json.put("plan_name", obj.getString("plan_name"));
            result.add(json);
        }
        return result;
    }
}
