package com.njcn.process.service.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.process.mapper.SupvAlarmMapper;
import com.njcn.process.pojo.param.SupvAlarmParam;
import com.njcn.process.pojo.po.SupvAlarm;
import com.njcn.process.service.ISupvAlarmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wr
 * @since 2023-09-01
 */
@Service
@RequiredArgsConstructor
public class SupvAlarmServiceImpl extends ServiceImpl<SupvAlarmMapper, SupvAlarm> implements ISupvAlarmService {

    private final DeptFeignClient deptFeignClient;
    private final DicDataFeignClient dicDataFeignClient;

    @Value("${gw.code}")
    private String code;
    @Override
    public boolean addAlarm(SupvAlarmParam.AlarmInsert param) {
        //获取省单位
        Dept data = deptFeignClient.getDeptByCode(code).getData();
        SupvAlarm supvAlarm = BeanUtil.copyProperties(param, SupvAlarm.class);
        supvAlarm.setProvinceId(data.getCode());
        supvAlarm.setProvinceName(data.getName());
        supvAlarm.setIsUploadHead(0);
        return this.save(supvAlarm);
    }

    @Override
    public boolean updateAlarm(SupvAlarmParam.AlarmUpdate param) {
        SupvAlarm supvAlarm = BeanUtil.copyProperties(param, SupvAlarm.class);
        SupvAlarm byId = this.getById(param.getAlarmId());
        if(1==byId.getIsUploadHead()){
            supvAlarm.setIsUploadHead(3);
        }
        return this.updateById(supvAlarm);
    }

    @Override
    public boolean delAlarm(List<String> planIds) {
        LambdaQueryWrapper<SupvAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(SupvAlarm::getIsUploadHead, 0).in(SupvAlarm::getAlarmId, planIds);
        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException("请选择未上送国网的删除");
        }
        return this.removeByIds(planIds);
    }

    @Override
    public Page<SupvAlarm> pageAlarm(SupvAlarmParam param) {
        List<String> deptIds = deptFeignClient.getDepSonSelfCodetByCode(param.getOrgId()).getData();
        Page<SupvAlarm> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()),
                new LambdaQueryWrapper<SupvAlarm>().in(SupvAlarm::getCreaterOrgId, deptIds)
                        .between(SupvAlarm::getCreaterTime,
                                DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())))

        );
        return page;
    }

    @Override
    public void downAlarm() {
        //单据类型
        List<DictData> billList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.BILL_TYPE.getCode()).getData();
        Map<String, DictData> mapBill = billList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        //所属专业
        List<DictData> specialityList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SPECIALITY_TYPE.getCode()).getData();
        Map<String, DictData> mapSpeciality = specialityList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<SupvAlarm> list = this.list();
        if(CollUtil.isNotEmpty(list)){
            for (SupvAlarm supvAlarm : list) {
                supvAlarm.setTime(supvAlarm.getCreaterTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
                if (mapBill.containsKey(supvAlarm.getBillType())) {
                    supvAlarm.setBillType(mapBill.get(supvAlarm.getBillType()).getName());
                }

                if (mapSpeciality.containsKey(supvAlarm.getSpecialityType())) {
                    supvAlarm.setSpecialityType(mapSpeciality.get(supvAlarm.getSpecialityType()).getName());
                }
            }
        }
        ExportParams exportParams = new ExportParams("预告警单模板（带*字段均是必填,请严格按照模板标准填入数据）", "预告警单信息");
        ExcelUtil.exportExcel(exportParams,"预告警单信息.xlsx",SupvAlarm.class, list);

    }
}
