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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.AllArgsConstructor;
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.acs.storage_cell.domain.StorageCell;
import org.nl.acs.storage_cell.service.StorageCellService;
import org.nl.acs.storage_cell.service.dto.StorageCellDto;
import org.nl.acs.storage_cell.service.dto.StorageCellQueryParam;
import org.nl.acs.storage_cell.service.mapper.StorageCellMapper;
import org.nl.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;

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

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

    // private final RedisUtils redisUtils;
    private final StorageCellMapper storageCellMapper;

    @Override
    public PageInfo<StorageCellDto> queryAll(StorageCellQueryParam query, Pageable pageable) {
        IPage<StorageCell> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<StorageCell> page = storageCellMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, StorageCellDto.class);
    }

    @Override
    public List<StorageCellDto> queryAll(StorageCellQueryParam query){
        return ConvertUtil.convertList(storageCellMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), StorageCellDto.class);
    }

    @Override
    public StorageCell getById(String id) {
        return storageCellMapper.selectById(id);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(StorageCellDto resources) {
        StorageCell entity = ConvertUtil.convert(resources, StorageCell.class);
        return storageCellMapper.insert(entity);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<String> ids){
        // delCaches(ids);
        return storageCellMapper.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<StorageCellDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (StorageCellDto storageCell : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("货位编码", storageCell.getStorageCode());
              map.put("排", storageCell.getX());
              map.put("列", storageCell.getY());
              map.put("层", storageCell.getZ());
              map.put("地址", storageCell.getAddress());
              map.put("备注", storageCell.getRemark());
              map.put("是否启用", storageCell.getIsActive());
              map.put("是否删除", storageCell.getIsDelete());
              map.put("创建者", storageCell.getCreateBy());
              map.put("创建时间", storageCell.getCreateTime());
              map.put("修改者", storageCell.getUpdateBy());
              map.put("修改时间", storageCell.getUpdateTime());
              map.put("父级货位编码", storageCell.getParentStorageCode());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/

    @Override
    public Map<String, Object> queryAll(Map whereJson, Pageable page) {
        String storage_code = MapUtil.getStr(whereJson, "storage_code");
        String parent_storage_code = MapUtil.getStr(whereJson, "parent_storage_code");
        String address = MapUtil.getStr(whereJson, "address");

        IPage<StorageCell> queryPage = PageUtil.toMybatisPage(page);
        LambdaQueryWrapper<StorageCell> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(storage_code), StorageCell::getStorage_code,storage_code);
        wrapper.like(StringUtils.isNotBlank(parent_storage_code), StorageCell::getParent_storage_code,parent_storage_code);
        wrapper.like(StringUtils.isNotBlank(address), StorageCell::getAddress,address);
        IPage<StorageCell> storageCellIPage = storageCellMapper.selectPage(queryPage,wrapper);
        final JSONObject json = (JSONObject) JSON.toJSON(ConvertUtil.convertPage(storageCellIPage, StorageCell.class));
        return json;
    }

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

    @Override
    public StorageCellDto findById(String storage_id) {

        StorageCell storageCell = storageCellMapper.selectById(storage_id);
        if (ObjectUtil.isNotEmpty(storageCell)){
            final StorageCellDto obj = ConvertUtil.convert(storageCell, StorageCellDto.class);
            return obj;
        }
        return null;
    }

//    @Override
//    public StorageCellDto findByCode(String code) {
//        WQLObject wo = WQLObject.getWQLObject("acs_storage_cell");
//        JSONObject json = wo.query("code ='" + code + "'").uniqueResult(0);
//        if (ObjectUtil.isNotEmpty(json)){
//            final StorageCellDto obj = json.toJavaObject(StorageCellDto.class);
//            return obj;
//        }
//        return null;
//    }

//    @Override
//    public StorageCellDto findByAddress(String address) {
//        WQLObject wo = WQLObject.getWQLObject("acs_storage_cell");
//        JSONObject json = wo.query("address ='" + address + "'").uniqueResult(0);
//        if (ObjectUtil.isNotEmpty(json)){
//            final StorageCellDto obj = json.toJavaObject(StorageCellDto.class);
//            return obj;
//        }
//        return null;
//    }

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

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

        StorageCell entity = ConvertUtil.convert(dto, StorageCell.class);
        storageCellMapper.insert(entity);
    }

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

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

        StorageCell storageCell = ConvertUtil.convert(dto, StorageCell.class);
        storageCellMapper.updateById(storageCell);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(String[] ids) {
        for (String storage_id : ids) {
            this.removeById(storage_id);
        }
    }

    @Override
    public void download(List<StorageCellDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StorageCellDto storageCell : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("货位编码", storageCell.getStorage_code());
            map.put("排", storageCell.getX());
            map.put("列", storageCell.getY());
            map.put("层", storageCell.getZ());
            map.put("地址", storageCell.getAddress());
            map.put("备注", storageCell.getRemark());
            map.put("是否启用", storageCell.getIs_active());
            map.put("是否删除", storageCell.getIs_delete());
            map.put("创建者", storageCell.getCreate_by());
            map.put("创建时间", storageCell.getCreate_time());
            map.put("修改者", storageCell.getUpdate_by());
            map.put("修改时间", storageCell.getUpdate_time());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
