package com.njcn.supervision.service.problem.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.common.DealStateEnum;
import com.njcn.supervision.enums.LeafletTypeEnum;
import com.njcn.supervision.enums.ProblemTypeEnum;
import com.njcn.supervision.mapper.problem.SupervisionUserComplaintPOMapper;
import com.njcn.supervision.pojo.param.leaflet.WarningAddParam;
import com.njcn.supervision.pojo.param.problem.SupervisionUserComplaintParam;
import com.njcn.supervision.pojo.po.problem.SupervisionUserComplaintPO;
import com.njcn.supervision.pojo.vo.problem.SupervisionUserComplaintVO;
import com.njcn.supervision.service.leaflet.IWarningLeafletService;
import com.njcn.supervision.service.problem.SupervisionUserComplaintPOService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2024/5/22  16:25【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class SupervisionUserComplaintPOServiceImpl extends ServiceImpl<SupervisionUserComplaintPOMapper, SupervisionUserComplaintPO> implements SupervisionUserComplaintPOService{

    private final IWarningLeafletService warningLeafletService;
    private final DeptFeignClient deptFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSupervisionUserComplaint(SupervisionUserComplaintParam supervisionUserComplaintParam) {
        SupervisionUserComplaintPO supervisionUserComplaintPO = new SupervisionUserComplaintPO();
        BeanUtil.copyProperties(supervisionUserComplaintParam,supervisionUserComplaintPO);
        supervisionUserComplaintPO.setInitiateWarningFlag(0);
        supervisionUserComplaintPO.setState(DataStateEnum.ENABLE.getCode());
        supervisionUserComplaintPO.setDealState(DealStateEnum.UNSOLVED.getCode());
        this.save(supervisionUserComplaintPO);
        return supervisionUserComplaintPO.getId();
    }

    @Override
    public Page<SupervisionUserComplaintVO> getSupervisionUserComplaint(SupervisionUserComplaintParam.SupervisionUserComplaintQueryParam supervisionUserComplaintQueryParam) {
        QueryWrapper<SupervisionUserComplaintParam> supervisionUserComplaintQueryWrapper = new QueryWrapper<>();
        //如果不是只查询已处理的，时间无效
        if (Objects.nonNull(supervisionUserComplaintQueryParam.getSearchBeginTime())&& StringUtils.equals(supervisionUserComplaintQueryParam.getDealState(),"1")){
            //添加上时间范围
            supervisionUserComplaintQueryWrapper.between("supervision_user_complaint.Create_Time",
                    DateUtil.beginOfDay(DateUtil.parse(supervisionUserComplaintQueryParam.getSearchBeginTime())),
                    DateUtil.endOfDay(DateUtil.parse(supervisionUserComplaintQueryParam.getSearchEndTime())));
        }
        //筛选普测负责单位
        if (StrUtil.isNotBlank(supervisionUserComplaintQueryParam.getDeptIndex())) {
            List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(supervisionUserComplaintQueryParam.getDeptIndex()).getData();
            supervisionUserComplaintQueryWrapper.in("supervision_user_complaint.duty_Org_Id", deptIds);
        }

        supervisionUserComplaintQueryWrapper
                .eq("supervision_user_complaint.state",DataStateEnum.ENABLE.getCode())
                //未解决查未解决，已解决查未解决+已解决，反正未解决的都要查
                .eq(StringUtils.equals(supervisionUserComplaintQueryParam.getDealState(),"0"),"supervision_user_complaint.deal_state",0)
                .orderByDesc("supervision_user_complaint.Update_Time");
        Page<SupervisionUserComplaintVO> page = this.baseMapper.getPage(new Page<>(PageFactory.getPageNum(supervisionUserComplaintQueryParam), PageFactory.getPageSize(supervisionUserComplaintQueryParam)), supervisionUserComplaintQueryWrapper);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<String> deptIds = page.getRecords().stream().distinct().map(SupervisionUserComplaintVO::getDutyOrgId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(deptIds)) {
                List<Dept> data = deptFeignClient.getDeptInfoListByIds(deptIds).getData();
                Map<String, String> deptMap = data.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
                page.getRecords().forEach(x -> {
                    if (deptMap.containsKey(x.getDutyOrgId())) {
                        x.setDutyOrgName(deptMap.get(x.getDutyOrgId()));
                    }
                });
            }
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initiateWarningLeaflet(WarningAddParam warningAddParam) {
        SupervisionUserComplaintPO supervisionUserComplaintPO = this.getById(warningAddParam.getId());
        /*
         * 1、预告警单名称，此处暂时用用户名+投诉
         * 2、预告警编号暂时随机by yxb
         * 3、问题类型：1：技术监督管理；2：在线监测超标问题；3：用户投诉；4：现场测试超标，此处是现场测试超标
         * 4、对应问题源id，用于查询详细数据
         * 5、单子类型：1：预警单；2：告警单
         * 6、问题详细描述
         * */
        warningLeafletService.createLeaflet(
                supervisionUserComplaintPO.getUserName().concat("投诉"),
                supervisionUserComplaintPO.getDutyOrgId(),
                IdWorker.get32UUID(),
                warningAddParam.getId(),
                ProblemTypeEnum.USER.getCode(),
                LeafletTypeEnum.ALARM.getCode(),
                supervisionUserComplaintPO.getComplaintText(),
                warningAddParam.getReformAdvice(),
                null
        );
        this.lambdaUpdate().eq(SupervisionUserComplaintPO::getId,warningAddParam.getId()).set(SupervisionUserComplaintPO::getInitiateWarningFlag,1).update();
    }

}
