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

import cn.hutool.core.date.DateUtil;
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.SecurityUtils;
import org.nl.common.utils.FileUtil;
import org.nl.acs.utils.PageUtil;
import org.nl.acs.address.domain.Address;
import org.nl.acs.address.service.AddressService;
import org.nl.acs.address.service.dto.AddressDto;
import org.nl.acs.address.service.dto.AddressQueryParam;
import org.nl.acs.address.service.mapper.AddressMapper;
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-10
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = SysInterfaceMethodsAddressService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AddressServiceImpl extends CommonServiceImpl<AddressMapper, Address> implements AddressService {

    // private final RedisUtils redisUtils;
    private final AddressMapper sysInterfaceMethodsAddressMapper;

    @Override
    public PageInfo<AddressDto> queryAll(AddressQueryParam query, Pageable pageable) {
        IPage<Address> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<Address> page = sysInterfaceMethodsAddressMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, AddressDto.class);
    }

    @Override
    public List<AddressDto> queryAll(AddressQueryParam query){
        return ConvertUtil.convertList(sysInterfaceMethodsAddressMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), AddressDto.class);
    }

    @Override
    public Address getById(String id) {
        return sysInterfaceMethodsAddressMapper.selectById(id);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(AddressDto resources) {
        Address entity = ConvertUtil.convert(resources, Address.class);
        return sysInterfaceMethodsAddressMapper.insert(entity);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<String> ids){
        // delCaches(ids);
        return sysInterfaceMethodsAddressMapper.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<SysInterfaceMethodsAddressDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (SysInterfaceMethodsAddressDto sysInterfaceMethodsAddress : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("方法编码", sysInterfaceMethodsAddress.getMethodsCode());
              map.put("方法名称", sysInterfaceMethodsAddress.getMethodsName());
              map.put("请求地址", sysInterfaceMethodsAddress.getMethodsUrl());
              map.put("备注", sysInterfaceMethodsAddress.getRemark());
              map.put("创建人", sysInterfaceMethodsAddress.getCreateId());
              map.put("创建人姓名", sysInterfaceMethodsAddress.getCreateName());
              map.put("创建时间", sysInterfaceMethodsAddress.getCreateTime());
              map.put("修改人", sysInterfaceMethodsAddress.getUpdateOptid());
              map.put("修改人姓名", sysInterfaceMethodsAddress.getUpdateOptname());
              map.put("修改时间", sysInterfaceMethodsAddress.getUpdateTime());
              map.put("是否删除", sysInterfaceMethodsAddress.getIsDelete());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/


    @Override
    public Map<String, Object> queryAll(Map whereJson, Pageable page) {
//        String blurry = "";
//        if (whereJson.get("blurry") != null) {
//            blurry = (String) whereJson.get("blurry");
//        }
//        JSONObject jo = WQL.getWO("Qdevice_query_002").addParam("flag", "3").addParam("blurry", blurry).pageQuery(WqlUtil.getHttpContext(page), "update_time desc");
//        return jo;

        IPage<Address> queryPage = PageUtil.toMybatisPage(page);
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(StringUtils.isNotBlank((String) whereJson.get("blurry")),i -> i.like(Address::getMethods_code, whereJson.get("blurry")).or().like(Address::getMethods_name, whereJson.get("blurry"))) ;

        IPage<Address> addressPage = sysInterfaceMethodsAddressMapper.selectPage(queryPage,wrapper);
        final JSONObject json = (JSONObject) JSON.toJSON(ConvertUtil.convertPage(addressPage, Address.class));
        return json;
    }

    @Override
    public List<AddressDto> queryAll(Map whereJson) {
//        WQLObject wo = WQLObject.getWQLObject("sys_interface_methods_address");
//        JSONArray arr = wo.query().getResultJSONArray(0);
//        List<AddressDto> list = arr.toJavaList(AddressDto.class);
//        return list;
        List<Address> addressList= new LambdaQueryChainWrapper<>(sysInterfaceMethodsAddressMapper)
                .list();
        return ConvertUtil.convertList(addressList, AddressDto.class);
    }

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

    @Override
    public AddressDto findByCode(String code) {
        Address address= new LambdaQueryChainWrapper<>(sysInterfaceMethodsAddressMapper)
                .eq(Address::getMethods_code, code)
                .one();
        if (ObjectUtil.isNotEmpty(address)){
            final AddressDto obj = ConvertUtil.convert(address, AddressDto.class);
            return obj;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(AddressDto dto) {
        String Methods_code = dto.getMethods_code();
        AddressDto methodsDto = this.findByCode(Methods_code);
        if (methodsDto != null && methodsDto.getIs_delete().equals("0") && dto.getMethods_code().equals(methodsDto.getMethods_code())) {
            throw new BadRequestException("存在相同的方法编码");
        }
        Long userId = Long.valueOf(SecurityUtils.getCurrentUserId());
        String currentUsername = SecurityUtils.getCurrentUsername();
        String now = DateUtil.now();

        dto.setMethods_id(IdUtil.simpleUUID());
        dto.setCreate_id(userId);
        dto.setCreate_name(currentUsername);
//        dto.setCreate_by(userId);
//        dto.setUpdate_by(userId);
        dto.setUpdate_optid(userId);
        dto.setUpdate_time(now);
        dto.setCreate_time(now);

//        WQLObject wo = WQLObject.getWQLObject("sys_interface_methods_address");
//        JSONObject json = (JSONObject) JSONObject.toJSON(dto);
//
//        wo.insert(json);

        Address entity = ConvertUtil.convert(dto, Address.class);
        sysInterfaceMethodsAddressMapper.insert(entity);
    }

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

        Long userId = Long.valueOf(SecurityUtils.getCurrentUserId());
        String currentUsername = SecurityUtils.getCurrentUsername();
        String now = DateUtil.now();
        dto.setUpdate_optid(userId);
        dto.setUpdate_optname(currentUsername);
        dto.setUpdate_time(now);
//        dto.setUpdate_by(userId);
        dto.setUpdate_optid(userId);

        Address address = ConvertUtil.convert(dto, Address.class);
        sysInterfaceMethodsAddressMapper.updateById(address);
    }

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

    @Override
    public void download(List<AddressDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AddressDto Address : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("方法编码", Address.getMethods_code());
            map.put("方法名称", Address.getMethods_name());
            map.put("请求地址", Address.getMethods_url());
            map.put("备注", Address.getRemark());
            map.put("创建人", Address.getCreate_name());
            map.put("创建时间", Address.getCreate_time());
            map.put("修改人", Address.getUpdate_optname());
            map.put("修改时间", Address.getUpdate_time());
            map.put("是否删除", Address.getIs_delete());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
