package com.usky.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.*;
import com.usky.fire.mapper.PatrolInspectionAbnormalMapper;
import com.usky.fire.mapper.PatrolInspectionPlanMapper;
import com.usky.fire.mapper.PatrolInspectionPlanSonMapper;
import com.usky.fire.service.*;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.fire.service.vo.ContentOptionVo;
import com.usky.fire.service.vo.PatrolInspectionAbnormalExportVo;
import com.usky.fire.service.vo.PatrolInspectionAbnormalVo;
import com.usky.fire.service.vo.PatrolInspectionContentVo;
import com.usky.fire.service.vo.PatrolInspectionRecordVo;
import com.usky.system.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 巡检异常记录表 服务实现类
 * </p>
 *
 * @author fu
 * @since 2024-06-13
 */
@Service
public class PatrolInspectionAbnormalServiceImpl extends AbstractCrudService<PatrolInspectionAbnormalMapper, PatrolInspectionAbnormal> implements PatrolInspectionAbnormalService {

    @Autowired
    private PatrolInspectionPlanSonMapper patrolInspectionPlanSonMapper;

    @Autowired
    private PatrolInspectionPlanMapper patrolInspectionPlanMapper;

    @Autowired
    private PatrolInspectionAreaService patrolInspectionAreaService;

    @Autowired
    private PatrolInspectionAbnormalPictureService patrolInspectionAbnormalPictureService;

    @Autowired
    private PatrolInspectionAbnormalOptionService patrolInspectionAbnormalOptionService;

    @Autowired
    private PatrolInspectionSiteContentService siteContentService;

    @Autowired
    private PatrolInspectionContentService patrolInspectionContentService;

    @Autowired
    private PatrolInspectionContentOptionService contentOptionService;

    @Autowired
    private PatrolInspectionPersonnelService patrolInspectionPersonnelService;

    @Override
    public void addAbnormal(PatrolInspectionAbnormal patrolInspectionAbnormal) {
        DateTimeFormatter df1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LambdaQueryWrapper<PatrolInspectionPlanSon> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionPlanSon::getId, patrolInspectionAbnormal.getPlanSonId());
        List<PatrolInspectionPlanSon> planSonList = patrolInspectionPlanSonMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(planSonList)){
            throw new BusinessException("子计划记录不存在");
        }

        LambdaQueryWrapper<PatrolInspectionArea> queryWrapperOne = Wrappers.lambdaQuery();
        queryWrapperOne.select(PatrolInspectionArea::getId, PatrolInspectionArea::getAreaName)
                .eq(PatrolInspectionArea::getId, planSonList.get(0).getAreaId());
        List<PatrolInspectionArea> areaList = patrolInspectionAreaService.list(queryWrapperOne);
        if(areaList.size() <= 0){
            throw new BusinessException("巡检区域不存在");
        }

        LambdaQueryWrapper<PatrolInspectionPersonnel> personnelQueryWrapper = Wrappers.lambdaQuery();
        personnelQueryWrapper.eq(PatrolInspectionPersonnel::getId,planSonList.get(0).getPersonnelId())
                .eq(PatrolInspectionPersonnel::getEnable,1);
        List<PatrolInspectionPersonnel> inspectionPersonnelList = patrolInspectionPersonnelService.list(personnelQueryWrapper);
        if(inspectionPersonnelList.size() <= 0){
            throw new BusinessException("巡检人员信息不存在");
        }

        PatrolInspectionAbnormal insertAbnormal = new PatrolInspectionAbnormal();
        insertAbnormal.setSiteNubmber(patrolInspectionAbnormal.getSiteNubmber());
        insertAbnormal.setSiteType(patrolInspectionAbnormal.getSiteType());
        insertAbnormal.setAreaName(areaList.get(0).getAreaName());
        insertAbnormal.setSiteName(patrolInspectionAbnormal.getSiteName());
        insertAbnormal.setName(inspectionPersonnelList.get(0).getFullName());
        insertAbnormal.setPhone(inspectionPersonnelList.get(0).getPhoneNumber());
        insertAbnormal.setPlanType(planSonList.get(0).getPlanType());
        insertAbnormal.setSiteStatus(patrolInspectionAbnormal.getSiteStatus());
        insertAbnormal.setLongitude(patrolInspectionAbnormal.getLongitude());
        insertAbnormal.setLatitude(patrolInspectionAbnormal.getLatitude());

        String startDate = null;
        String endDate = null;
        if (planSonList.get(0).getPlanType() == 1) {
            startDate = df1.format(planSonList.get(0).getInspectionDate()) + "T" + planSonList.get(0).getStartTime();
            endDate = df1.format(planSonList.get(0).getInspectionDate()) + "T" + planSonList.get(0).getEndTime();
        } else {
            startDate = df1.format(planSonList.get(0).getStartDate()) + "T" + planSonList.get(0).getStartTime();
            endDate = df1.format(planSonList.get(0).getEndDate()) + "T" + planSonList.get(0).getEndTime();
        }

        insertAbnormal.setStartDate(LocalDateTime.parse(startDate));
        insertAbnormal.setEndDate(LocalDateTime.parse(endDate));
        insertAbnormal.setCreateTime(LocalDateTime.now());
        insertAbnormal.setPlanId(planSonList.get(0).getPlanId());
        insertAbnormal.setPlanSonId(patrolInspectionAbnormal.getPlanSonId());
        insertAbnormal.setSiteId(patrolInspectionAbnormal.getSiteId());
        insertAbnormal.setTenantId(SecurityUtils.getTenantId());
        insertAbnormal.setCompanyId(patrolInspectionAbnormal.getCompanyId());
        insertAbnormal.setCreator(SecurityUtils.getUsername());
        insertAbnormal.setRemarks(patrolInspectionAbnormal.getRemarks());
        insertAbnormal.setAbnormalStatus(patrolInspectionAbnormal.getAbnormalStatus());
        //从主计划表中查找路线id放入表中
        LambdaQueryWrapper<PatrolInspectionPlan> planLambdaQueryWrapper = Wrappers.lambdaQuery();
        planLambdaQueryWrapper.select(PatrolInspectionPlan::getRouteId)
                .eq(PatrolInspectionPlan::getId, patrolInspectionAbnormal.getPlanId());
        Integer routeId = patrolInspectionPlanMapper.selectOne(planLambdaQueryWrapper).getRouteId();
        insertAbnormal.setRouteId(routeId);
        this.save(insertAbnormal);
    }

    @Override
    public CommonPage<PatrolInspectionAbnormal> recordList(String areaName, String siteName, String name,
                                                                         Integer planType, Integer routeId,
                                                                         String startDateTime, String endDateTime,
                                                                         Integer pageNum, Integer pageSize) {
        IPage<PatrolInspectionAbnormal> page = new Page<>(pageNum, pageSize);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionAbnormal> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionAbnormal::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(areaName), PatrolInspectionAbnormal::getAreaName, areaName)
                .like(StringUtils.isNotBlank(siteName), PatrolInspectionAbnormal::getSiteName, siteName)
                .like(StringUtils.isNotBlank(name), PatrolInspectionAbnormal::getName, name)
                .eq(planType != null && planType != 0, PatrolInspectionAbnormal::getPlanType, planType)
                .eq(routeId != null, PatrolInspectionAbnormal::getRouteId, routeId)
                .between(StringUtils.isNotBlank(startDateTime) && StringUtils.isNotBlank(endDateTime), PatrolInspectionAbnormal::getCreateTime, startDateTime, endDateTime)
                .eq("00".equals(userType), PatrolInspectionAbnormal::getCreator, SecurityUtils.getUsername());
        queryWrapper.orderByDesc(PatrolInspectionAbnormal::getId);
        page = this.page(page, queryWrapper);
        return new CommonPage<>(page.getRecords(), page.getTotal(), pageSize, pageNum);
    }

    @Override
    public List<PatrolInspectionAbnormalVo> recordDetails(Integer id) {
        //记录查询
        LambdaQueryWrapper<PatrolInspectionAbnormal> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionAbnormal::getTenantId, SecurityUtils.getTenantId())
                .eq(PatrolInspectionAbnormal::getId, id);
        List<PatrolInspectionAbnormal> patrolInspectionRecordList = this.list(queryWrapper);
        if (patrolInspectionRecordList.isEmpty()) {
            throw new BusinessException("巡检记录不存在");
        }
        //上传图片查询
        LambdaQueryWrapper<PatrolInspectionAbnormalPicture> queryWrapperOne = Wrappers.lambdaQuery();
        queryWrapperOne.eq(PatrolInspectionAbnormalPicture::getRecordId, id);
        List<PatrolInspectionAbnormalPicture> patrolInspectionRecordPictureList = patrolInspectionAbnormalPictureService.list(queryWrapperOne);

        //内容选中项查询
        List<Integer> contentOptionIdList = new ArrayList<>();
        LambdaQueryWrapper<PatrolInspectionAbnormalOption> queryWrapperTwo = Wrappers.lambdaQuery();
        queryWrapperTwo.eq(PatrolInspectionAbnormalOption::getRecordId, id);
        List<PatrolInspectionAbnormalOption> patrolInspectionRecordOptionList = patrolInspectionAbnormalOptionService.list(queryWrapperTwo);
        for (int i = 0; i < patrolInspectionRecordOptionList.size(); i++) {
            if (patrolInspectionRecordOptionList.get(i).getContentOptionId() != null) {
                contentOptionIdList.add(patrolInspectionRecordOptionList.get(i).getContentOptionId());
            }
        }

        //地点内容ID查询
        LambdaQueryWrapper<PatrolInspectionSiteContent> queryWrapperThree = Wrappers.lambdaQuery();
        queryWrapperThree.in(PatrolInspectionSiteContent::getSiteId, patrolInspectionRecordList.get(0).getSiteId());
        List<PatrolInspectionSiteContent> siteContentList = siteContentService.list(queryWrapperThree);

        //内容ID重组
        List<Integer> contentIdList = new ArrayList<>();
        for (int i = 0; i < siteContentList.size(); i++) {
            contentIdList.add(siteContentList.get(i).getContentId());
        }

        //内容查询
        LambdaQueryWrapper<PatrolInspectionContent> queryWrapperFour = Wrappers.lambdaQuery();
        queryWrapperFour.in(PatrolInspectionContent::getId, contentIdList)
                .eq(PatrolInspectionContent::getEnable, 1);
        List<PatrolInspectionContent> patrolInspectionContentList = patrolInspectionContentService.list(queryWrapperFour);

        //内容选择项查询
        LambdaQueryWrapper<PatrolInspectionContentOption> queryWrapperFive = Wrappers.lambdaQuery();
        queryWrapperFive.in(PatrolInspectionContentOption::getContentId, contentIdList)
                .eq(PatrolInspectionContentOption::getEnable, 1);
        List<PatrolInspectionContentOption> contentOptionList = contentOptionService.list(queryWrapperFive);

        //重组内容选项
        List<ContentOptionVo> contentOptionVoList = new ArrayList<>();
        for (int i = 0; i < contentOptionList.size(); i++) {
            ContentOptionVo contentOptionVo = new ContentOptionVo();
            contentOptionVo.setId(contentOptionList.get(i).getId());
            contentOptionVo.setContentId(contentOptionList.get(i).getContentId());
            contentOptionVo.setOptionName(contentOptionList.get(i).getOptionName());
            contentOptionVo.setEnable(contentOptionList.get(i).getEnable());
            contentOptionVo.setCreator(contentOptionList.get(i).getCreator());
            contentOptionVo.setCreateTime(contentOptionList.get(i).getCreateTime());
            contentOptionVo.setSelectStatus(false);
            for (int j = 0; j < patrolInspectionRecordOptionList.size(); j++) {
                if (contentOptionList.get(i).getContentId() == patrolInspectionContentList.get(j).getId()) {
                    contentOptionVo.setRemarks(patrolInspectionRecordOptionList.get(j).getRemarks());
                }
                if (contentOptionList.get(i).getId() == patrolInspectionRecordOptionList.get(j).getContentOptionId()) {
                    contentOptionVo.setSelectStatus(true);
                }
            }
            contentOptionVoList.add(contentOptionVo);
        }

        //重组内容
        List<PatrolInspectionContentVo> patrolInspectionContentVoList = new ArrayList<>();
        for (int i = 0; i < patrolInspectionContentList.size(); i++) {
            PatrolInspectionContentVo patrolInspectionContentVo = new PatrolInspectionContentVo();
            patrolInspectionContentVo.setId(patrolInspectionContentList.get(i).getId());
            patrolInspectionContentVo.setContentTitle(patrolInspectionContentList.get(i).getContentTitle());
            patrolInspectionContentVo.setContentDescribe(patrolInspectionContentList.get(i).getContentDescribe());
            patrolInspectionContentVo.setSubmissionMethod(patrolInspectionContentList.get(i).getSubmissionMethod());
            patrolInspectionContentVo.setTenantId(patrolInspectionContentList.get(i).getTenantId());
            patrolInspectionContentVo.setCreateTime(patrolInspectionContentList.get(i).getCreateTime());
            patrolInspectionContentVo.setCreator(patrolInspectionContentList.get(i).getCreator());
            patrolInspectionContentVo.setEnable(patrolInspectionContentList.get(i).getEnable());
            patrolInspectionContentVo.setCompanyId(patrolInspectionContentList.get(i).getCompanyId());
            List<ContentOptionVo> contentOptionVoListOne = new ArrayList<>();

            if (patrolInspectionContentList.get(i).getSubmissionMethod() == 3) {
                for (int j = 0; j < patrolInspectionRecordOptionList.size(); j++) {
                    if (patrolInspectionRecordOptionList.get(j).getContentOptionId() == null || patrolInspectionRecordOptionList.get(j).getContentOptionId() == 0) {
                        int id11 = patrolInspectionContentList.get(i).getId();
                        int id22 = patrolInspectionRecordOptionList.get(j).getContentId();
                        if (id11 == id22) {
                            if (patrolInspectionRecordOptionList.get(j).getRemarks() != null && !"".equals(patrolInspectionRecordOptionList.get(j).getRemarks())) {
                                patrolInspectionContentVo.setRemarks(patrolInspectionRecordOptionList.get(j).getRemarks());
                            }
                            patrolInspectionContentVo.setContent(patrolInspectionRecordOptionList.get(j).getContent());
                        }
                    }
                }
            } else {
                for (int j = 0; j < contentOptionVoList.size(); j++) {
                    int id1 = patrolInspectionContentList.get(i).getId();
                    int id2 = contentOptionVoList.get(j).getContentId();
                    if (id1 == id2) {
                        if (contentOptionVoList.get(j).getRemarks() != null && !"".equals(contentOptionVoList.get(j).getRemarks())) {
                            patrolInspectionContentVo.setRemarks(contentOptionVoList.get(j).getRemarks());
                        }
                        contentOptionVoListOne.add(contentOptionVoList.get(j));
                        patrolInspectionContentVo.setContentOptionVoList(contentOptionVoListOne);
                    }
                }
            }

            patrolInspectionContentVo.setContentOptionValue(contentOptionIdList);
            patrolInspectionContentVoList.add(patrolInspectionContentVo);
        }

        //重组巡检记录
        List<PatrolInspectionAbnormalVo> list = new ArrayList<>();
        for (int i = 0; i < patrolInspectionRecordList.size(); i++) {
            PatrolInspectionAbnormalVo patrolInspectionAbnormalVo = new PatrolInspectionAbnormalVo();
            patrolInspectionAbnormalVo.setId(patrolInspectionRecordList.get(i).getId());
            patrolInspectionAbnormalVo.setSiteNubmber(patrolInspectionRecordList.get(i).getSiteNubmber());
            patrolInspectionAbnormalVo.setSiteType(patrolInspectionRecordList.get(i).getSiteType());
            patrolInspectionAbnormalVo.setAreaName(patrolInspectionRecordList.get(i).getAreaName());
            patrolInspectionAbnormalVo.setSiteName(patrolInspectionRecordList.get(i).getSiteName());
            patrolInspectionAbnormalVo.setName(patrolInspectionRecordList.get(i).getName());
            patrolInspectionAbnormalVo.setPhone(patrolInspectionRecordList.get(i).getPhone());
            patrolInspectionAbnormalVo.setPlanType(patrolInspectionRecordList.get(i).getPlanType());
            patrolInspectionAbnormalVo.setSiteStatus(patrolInspectionRecordList.get(i).getSiteStatus());
            patrolInspectionAbnormalVo.setLongitude(patrolInspectionRecordList.get(i).getLongitude());
            patrolInspectionAbnormalVo.setLatitude(patrolInspectionRecordList.get(i).getLatitude());
            patrolInspectionAbnormalVo.setStartDate(patrolInspectionRecordList.get(i).getStartDate());
            patrolInspectionAbnormalVo.setEndDate(patrolInspectionRecordList.get(i).getEndDate());
            patrolInspectionAbnormalVo.setCreateTime(patrolInspectionRecordList.get(i).getCreateTime());
            patrolInspectionAbnormalVo.setPlanId(patrolInspectionRecordList.get(i).getPlanId());
            patrolInspectionAbnormalVo.setPlanSonId(patrolInspectionRecordList.get(i).getPlanSonId());
            patrolInspectionAbnormalVo.setSiteId(patrolInspectionRecordList.get(i).getSiteId());
            patrolInspectionAbnormalVo.setTenantId(patrolInspectionRecordList.get(i).getTenantId());
            patrolInspectionAbnormalVo.setCompanyId(patrolInspectionRecordList.get(i).getCompanyId());
            patrolInspectionAbnormalVo.setCreator(patrolInspectionRecordList.get(i).getCreator());
            patrolInspectionAbnormalVo.setRemarks(patrolInspectionRecordList.get(i).getRemarks());
            patrolInspectionAbnormalVo.setRecordPictureList(patrolInspectionRecordPictureList);
            patrolInspectionAbnormalVo.setContentVoList(patrolInspectionContentVoList);
            list.add(patrolInspectionAbnormalVo);
        }
        return list;
    }

    @Override
    public List<PatrolInspectionAbnormalExportVo> abnormalListExport(String areaName, String siteName, String name,
                                                                     Integer planType, Integer routeId,
                                                                     String startDateTime, String endDateTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionAbnormal> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionAbnormal::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(areaName), PatrolInspectionAbnormal::getAreaName, areaName)
                .like(StringUtils.isNotBlank(siteName), PatrolInspectionAbnormal::getSiteName, siteName)
                .like(StringUtils.isNotBlank(name), PatrolInspectionAbnormal::getName, name)
                .eq(planType != null && planType != 0, PatrolInspectionAbnormal::getPlanType, planType)
                .eq(routeId != null, PatrolInspectionAbnormal::getRouteId, routeId)
                .between(StringUtils.isNotBlank(startDateTime) && StringUtils.isNotBlank(endDateTime), PatrolInspectionAbnormal::getCreateTime, startDateTime, endDateTime)
                .eq("00".equals(userType), PatrolInspectionAbnormal::getCreator, SecurityUtils.getUsername());
        queryWrapper.orderByDesc(PatrolInspectionAbnormal::getId);
        List<PatrolInspectionAbnormal> recordList = this.list(queryWrapper);

        List<PatrolInspectionAbnormalExportVo> list = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            PatrolInspectionAbnormalExportVo vo = new PatrolInspectionAbnormalExportVo();
            vo.setXh(i + 1);
            vo.setSiteNubmber(recordList.get(i).getSiteNubmber());
            vo.setSiteType(recordList.get(i).getSiteType());
            vo.setAreaName(recordList.get(i).getAreaName());
            vo.setSiteName(recordList.get(i).getSiteName());
            vo.setName(recordList.get(i).getName());
            vo.setPhone(recordList.get(i).getPhone());
            vo.setPlanType(recordList.get(i).getPlanType());
            vo.setLongitude(recordList.get(i).getLongitude());
            vo.setLatitude(recordList.get(i).getLatitude());
            vo.setStartDate(recordList.get(i).getStartDate() != null ? recordList.get(i).getStartDate().format(df) : "");
            vo.setEndDate(recordList.get(i).getEndDate() != null ? recordList.get(i).getEndDate().format(df) : "");
            vo.setCreateTime(recordList.get(i).getCreateTime() != null ? recordList.get(i).getCreateTime().format(df) : "");
            vo.setAbnormalStatus(recordList.get(i).getAbnormalStatus());
            vo.setRemarks(recordList.get(i).getRemarks());
            vo.setCreator(recordList.get(i).getCreator());
            list.add(vo);
        }
        return list;
    }
}
