package com.ltgk.port.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltgk.common.core.domain.AjaxResult;
import com.ltgk.common.utils.SecurityUtils;
import com.ltgk.common.utils.StringUtils;
import com.ltgk.common.utils.bean.BeanUtils;
import com.ltgk.common.utils.poi.ExcelUtil;
import com.ltgk.port.domain.dto.WarnAreaInfoListReq;
import com.ltgk.port.domain.entity.WarnAreaInfo;
import com.ltgk.port.domain.vo.WarnAreaInfoVo;
import com.ltgk.port.mapper.WarnAreaInfoMapper;
import com.ltgk.port.service.WarnAreaInfoService;
import com.ltgk.system.domain.SysAreaInfo;
import com.ltgk.system.service.SysAreaInfoService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.github.pagehelper.page.PageMethod.startPage;

@Service
public class WarnAreaInfoServiceImpl extends ServiceImpl<WarnAreaInfoMapper, WarnAreaInfo> implements WarnAreaInfoService {

    @Resource
    private SysAreaInfoService sysAreaInfoService;

    @Override
    public AjaxResult saveWarnAreaInfo(WarnAreaInfo warnAreaInfo) {

        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date nowDate = new Date();

        if (StringUtils.isBlank(warnAreaInfo.getId())) {
            warnAreaInfo.setCreateBy(userName);
            warnAreaInfo.setCreateAt(nowDate);
        }
        warnAreaInfo.setUpdateBy(userName);
        warnAreaInfo.setUpdateAt(nowDate);

        if (this.saveOrUpdate(warnAreaInfo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public List<WarnAreaInfo> list(WarnAreaInfoListReq req) {
        req.queryCheck();
        WarnAreaInfo warnAreaInfo = new WarnAreaInfo();
        BeanUtils.copyProperties(req, warnAreaInfo);
        LambdaQueryWrapper<WarnAreaInfo> wrapper = new LambdaQueryWrapper<>(warnAreaInfo)
                .orderByDesc(WarnAreaInfo::getUpdateAt);
        startPage(req.getPageNum(), req.getPageSize());
        List<WarnAreaInfo> list = this.list(wrapper);
        list.forEach(entity -> {
            String points = entity.getPoints();
            int count = 0;
            if (StringUtils.isNotBlank(points)) {
                count = entity.getPoints().split(";").length;
            }
            entity.setCoordinateNum(count);
        });
        return list;
    }

    @Override
    public void export(HttpServletResponse response, WarnAreaInfo entity) {
        LambdaQueryWrapper<WarnAreaInfo> wrapper = new LambdaQueryWrapper<>(entity)
                .orderByDesc(WarnAreaInfo::getUpdateAt);

        List<WarnAreaInfo> list = this.list(wrapper);

        List<WarnAreaInfoVo> warnAreaInfoVoList = list.stream().map(m -> {
            WarnAreaInfoVo warnAreaInfoVo = new WarnAreaInfoVo();
            BeanUtils.copyProperties(m, warnAreaInfoVo);
            String points = m.getPoints();
            int count = 0;
            if (StringUtils.isNotBlank(points)) {
                count = points.split(";").length;
            }
            warnAreaInfoVo.setCoordinateNum(count);
            return warnAreaInfoVo;
        }).collect(Collectors.toList());

        ExcelUtil<WarnAreaInfoVo> util = new ExcelUtil<>(WarnAreaInfoVo.class);
        util.exportExcel(response, warnAreaInfoVoList, "电子围栏数据导出");
    }

    @Override
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<WarnAreaInfoVo> util = new ExcelUtil<>(WarnAreaInfoVo.class);
        util.importTemplateExcel(response, "电子围栏数据导入模板");
    }

    @Override
    public AjaxResult importData(MultipartFile file) throws IOException {
        // 校验是否为 Excel 格式
        ExcelUtil.checkExcelFile(file);
        ExcelUtil<WarnAreaInfoVo> util = new ExcelUtil<>(WarnAreaInfoVo.class);
        List<WarnAreaInfoVo> list = util.importExcel(file.getInputStream());
        if (CollectionUtils.isEmpty(list) || list.stream().allMatch(Objects::isNull)) {
            return AjaxResult.error("导入数据为空或模板格式有误！");
        }

        Set<String> areaCodeSet = list.stream().map(WarnAreaInfoVo::getAreaCode).collect(Collectors.toSet());

        List<SysAreaInfo> sysAreaInfoList = sysAreaInfoService.findAreaInfoByAreaCodeSet(areaCodeSet);

        Map<String, String> areaCodeMap = sysAreaInfoList.stream().collect(Collectors.toMap(SysAreaInfo::getAreaCode, SysAreaInfo::getAreaName));

        List<WarnAreaInfo> infoList = list.stream().map(m -> {
            WarnAreaInfo warnAreaInfo = new WarnAreaInfo();
            BeanUtils.copyProperties(m, warnAreaInfo);
            String userName = SecurityUtils.getLoginUser().getUser().getNickName();
            Date nowDate = new Date();
            if(StringUtils.isNotBlank(m.getAreaCode()) && areaCodeMap.containsKey(m.getAreaCode())) {
                warnAreaInfo.setAreaName(areaCodeMap.get(m.getAreaCode()));
            }
            if (StringUtils.isBlank(warnAreaInfo.getId())) {
                warnAreaInfo.setCreateBy(userName);
                warnAreaInfo.setCreateAt(nowDate);
            }
            warnAreaInfo.setUpdateBy(userName);
            warnAreaInfo.setUpdateAt(nowDate);
            // TODO:
//            if (StringUtils.isBlank(m.getBeginTime())) {
//                warnAreaInfo.setBeginTime(null);
//            }
//
//            if (StringUtils.isBlank(m.getEndTime())) {
//                warnAreaInfo.setEndTime(null);
//            }

            return warnAreaInfo;
        }).collect(Collectors.toList());
        return this.saveOrUpdateBatch(infoList) ? AjaxResult.success() : AjaxResult.error();
    }
}
