package com.project.zcustom.service.service.post.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.zcustom.controller.core.PageParamVo;
import com.project.zcustom.controller.core.StringUtils;
import com.project.zcustom.domain.access.PlatAccess;
import com.project.zcustom.domain.post.PlatPostStation;
import com.project.zcustom.domain.post.PlatPostStationChart;

import com.project.zcustom.mapper.post.PlatPostStationMapper;
import com.project.zcustom.service.access.IPlatAccessService;
import com.project.zcustom.service.service.post.IPlatPostStationChartService;
import com.project.zcustom.service.service.post.IPlatPostStationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 物业服务Service业务层处理
 *
 * @author change
 * @date 2024-10-21
 */
@Service
public class PlatPostStationServiceImpl extends ServiceImpl<PlatPostStationMapper, PlatPostStation> implements IPlatPostStationService {

    @Resource
    private IPlatPostStationChartService iPlatPostStationChartService;
    @Resource
    private IPlatAccessService iPlatAccessService;

    /**
     * 组装查询条件
     */
    private LambdaQueryWrapper<PlatPostStation> getLambdaQueryWrapper(PlatPostStation platPostStation) {
        LambdaQueryWrapper<PlatPostStation> lqw = new LambdaQueryWrapper<PlatPostStation>();
        if (StringUtils.isNotBlank(platPostStation.getAppOrg())) {
            lqw.eq(PlatPostStation::getAppOrg, platPostStation.getAppOrg());
        }
        return lqw;
    }

    /**
     * 分页查询物业服务列表
     *
     * @param platPostStation 物业服务
     * @return 物业服务集合
     */
    @Override
    public IPage<PlatPostStation> pagingPlatPostStationList(PlatPostStation platPostStation) {
        IPage<PlatPostStation> page = new Page<>(platPostStation.getPageNum(), platPostStation.getPageSize());
        LambdaQueryWrapper<PlatPostStation> lqw = getLambdaQueryWrapper(platPostStation);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatPostStation::getCreateTime);
        return baseMapper.selectPage(page, lqw);
    }

    /**
     * 分页查询物业服务列表
     *
     * @param lqw
     * @return 物业服务集合
     */
    @Override
    public IPage<PlatPostStation> pagingPlatPostStationList(PageParamVo pageParamVo, LambdaQueryWrapper<PlatPostStation> lqw) {
        IPage<PlatPostStation> page = new Page<>(pageParamVo.getPageNum(), pageParamVo.getPageSize());
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatPostStation::getCreateTime);
        return baseMapper.selectPage(page, lqw);
    }

    /**
     * 查询物业服务列表
     *
     * @param platPostStation 物业服务
     * @return 物业服务
     */
    @Override
    public List<PlatPostStation> selectPlatPostStationList(PlatPostStation platPostStation) {
        LambdaQueryWrapper<PlatPostStation> lqw = getLambdaQueryWrapper(platPostStation);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatPostStation::getCreateTime);
        return baseMapper.selectList(lqw);
    }

    /**
     * 查询物业服务列表
     *
     * @param platPostStation 物业服务
     * @return 物业服务
     */
    @Override
    public List<PlatPostStation> selectPlatPostStationList(PlatPostStation platPostStation, Long limitNum) {
        LambdaQueryWrapper<PlatPostStation> lqw = getLambdaQueryWrapper(platPostStation);
        // 排序 默认时间倒序
        lqw.orderByDesc(PlatPostStation::getCreateTime);
        lqw.last("limit " + limitNum);
        return baseMapper.selectList(lqw);
    }

    /**
     * 根据指定字段查询信息
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 物业服务
     */
    @Override
    public PlatPostStation getPlatPostStationByField(String field, String filedValue) {
        QueryWrapper<PlatPostStation> lqw = new QueryWrapper<PlatPostStation>();
        lqw.eq(field, filedValue);
        lqw.last("limit 1");
        return this.getOne(lqw, false);
    }

    /**
     * 根据指定字段查询信息
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 物业服务
     */
    @Override
    public PlatPostStation getPlatPostStationByField(String field, String filedValue,String fieldString) {
        QueryWrapper<PlatPostStation> lqw = new QueryWrapper<PlatPostStation>();
        if(!(Objects.equals(field,"app_org") && Objects.equals(filedValue,"0000"))){
            lqw.eq(field, filedValue);
        }
        lqw.select(fieldString);
        lqw.last("limit 1");
        return this.getOne(lqw, false);
    }

    /**
     * 根据指定字段查询信息列表
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 物业服务
     */
    @Override
    public List<PlatPostStation> selectPlatPostStationListByField(String field, String filedValue, Long limitNum) {
        QueryWrapper<PlatPostStation> lqw = new QueryWrapper<PlatPostStation>();
        lqw.eq(field, filedValue);
        lqw.last("limit " + limitNum);
        return this.list(lqw);
    }

    /**
     * 根据指定字段查询信息列表
     *
     * @param field      字段名称
     * @param filedValue 字段值
     * @return 物业服务
     */
    @Override
    public List<PlatPostStation> selectPlatPostStationListByField(String field, String filedValue) {
        QueryWrapper<PlatPostStation> lqw = new QueryWrapper<PlatPostStation>();
        lqw.eq(field, filedValue);
        return this.list(lqw);
    }

    /**
     * 判断指定字段值是否存在
     *
     * @param field      字段名称
     * @param filedValue 字段值
     */
    @Override
    public void checkFieldExist(String field, String filedValue, String tips, Long id) {
        QueryWrapper<PlatPostStation> lqw = new QueryWrapper<PlatPostStation>();
        lqw.eq(field, filedValue);
        lqw.ne("id", id);
        if (this.getOne(lqw, false) != null) {
            throw new RuntimeException(tips + "已存在");
        }
    }

    /**
     * 添加物业服务
     */
    @Override
    public void addPlatPostStation(String appOrg,Map<String, Object> mapField){
        PlatPostStation platPostStation = this.getPlatPostStationByField("app_org", appOrg);
        try {
            if(StringUtils.isNotNull(platPostStation)){
                this.setPlatPostStation(mapField,platPostStation);
                // 更新数据
                this.updateById(platPostStation);
            }else{
                platPostStation = new PlatPostStation();
                this.setPlatPostStation(mapField,platPostStation);
                platPostStation.setAppOrg(appOrg);
                // 添加数据
                this.save(platPostStation);
            }
            this.addStationChart(appOrg,mapField);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 设置数据
     */
    private void setPlatPostStation(Map<String, Object> mapField, PlatPostStation platPostStation){
       List<String> keyList = Arrays.asList("faultWarranty",
               "dispatched","suggested","repairOrders",
               "questionnaires","furniture","hotColdWater","accessControl",
               "other","wall","electrical","elevator","fireControl","cleaning","airConditioning");
        StringUtils.setFieldValue(platPostStation,mapField,keyList,0, PlatPostStation::setFaultWarrantyNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,1, PlatPostStation::setDispatchedNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,2, PlatPostStation::setSuggestedNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,3, PlatPostStation::setRepairOrdersNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,4, PlatPostStation::setQuestionnairesNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,5, PlatPostStation::setFurniture,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,6, PlatPostStation::setHotColdWater,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,7, PlatPostStation::setAccessControl,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,8, PlatPostStation::setOther,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,9, PlatPostStation::setWall,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,10, PlatPostStation::setElectrical,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,11, PlatPostStation::setElevator,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,12, PlatPostStation::setFireControl,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,13, PlatPostStation::setCleaning,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,14, PlatPostStation::setAirConditioning,Long.class);
    }

    /**
     * 处理表格数据
     * 物业服务 近六个月报修分类占比
     * 依次存入各个月的各种报修的数据
     * @param appOrg
     * @param mapField
     */
    private void addStationChart(String appOrg,Map<String, Object> mapField) {
        QueryWrapper<PlatPostStationChart> chartQueryWrapper = new QueryWrapper<>();
        chartQueryWrapper.eq("app_org", appOrg);
        // 删除当前地区所有数据
        iPlatPostStationChartService.remove(chartQueryWrapper);
        List<PlatPostStationChart> chartList = new ArrayList<>();
        Map<String, Object> coList = StringUtils.getListToMap(mapField.get("coList").toString());
        Map<String, Object> elevatorList = StringUtils.getListToMap(mapField.get("elevatorList").toString());
        Map<String, Object> laList = StringUtils.getListToMap(mapField.get("laList").toString());
        Map<String, Object> seList = StringUtils.getListToMap(mapField.get("seList").toString());
        Map<String, Object> toList = StringUtils.getListToMap(mapField.get("toList").toString());
        Map<String, Object> arList = StringUtils.getListToMap(mapField.get("arList").toString());
        Map<String, Object> diList = StringUtils.getListToMap(mapField.get("diList").toString());
        Map<String, Object> otList = StringUtils.getListToMap(mapField.get("otList").toString());
        Map<String, Object> meList = StringUtils.getListToMap(mapField.get("meList").toString());
        Map<String, Object> ofList = StringUtils.getListToMap(mapField.get("ofList").toString());
//        List<String> prefixList = Arrays.asList("co","el","la","se","to","ar","di","ot","me","of");
        List<String> keyAppendList = Arrays.asList("one","two","three","four","five","six");
        for (int i = 0; i < keyAppendList.size();i++){
            PlatPostStationChart platPostStationChart = new PlatPostStationChart();
            platPostStationChart.setAppOrg(appOrg);
            platPostStationChart.setAppMonth((long) (i+1));
            platPostStationChart.setColNum(Long.parseLong(coList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setElevatorNum(Long.parseLong(elevatorList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setLaNum(Long.parseLong(laList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setSeNum(Long.parseLong(seList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setToNum(Long.parseLong(toList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setArNum(Long.parseLong(arList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setDiNum(Long.parseLong(diList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setOtNum(Long.parseLong(otList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setMeNum(Long.parseLong(meList.get(keyAppendList.get(i)).toString()));
            platPostStationChart.setOfNum(Long.parseLong(ofList.get(keyAppendList.get(i)).toString()));
            chartList.add(platPostStationChart);
        }
        // 添加数据
        iPlatPostStationChartService.saveBatch(chartList);
    }


    /**
     * 获取数据概况
     */
    @Override
    public Map<String, Object> getOverviewData(String appOrg){
        String fieldString = "fault_warranty_num,dispatched_num,suggested_num,repair_orders_num,questionnaires_num";
        if(Objects.equals(appOrg,"0000")){
            fieldString = "sum(fault_warranty_num) as fault_warranty_num,sum(dispatched_num) as dispatched_num,sum(suggested_num) as suggested_num,sum(repair_orders_num) as repair_orders_num,sum(questionnaires_num) as questionnaires_num";
        }
        PlatPostStation platPostStation = this.getPlatPostStationByField("app_org", appOrg,fieldString);
        Map<String, Object> tempMap = new HashMap<>();
        if (StringUtils.isNull(platPostStation)) {
            StringUtils.getMapData("故障报修", "faultWarrantyNum", 0, tempMap);
            StringUtils.getMapData("报修派单", "dispatchedNum", 0, tempMap);
            StringUtils.getMapData("维修完成", "suggestedNum", 0, tempMap);
            StringUtils.getMapData("投诉建议", "repairOrdersNum", 0, tempMap);
            StringUtils.getMapData("调查问卷", "questionnairesNum", 0, tempMap);
        }else{
            StringUtils.getMapData("故障报修", "faultWarrantyNum", platPostStation.getFaultWarrantyNum(), tempMap);
            StringUtils.getMapData("报修派单", "dispatchedNum", platPostStation.getDispatchedNum(), tempMap);
            StringUtils.getMapData("维修完成", "suggestedNum", platPostStation.getSuggestedNum(), tempMap);
            StringUtils.getMapData("投诉建议", "repairOrdersNum", platPostStation.getRepairOrdersNum(), tempMap);
            StringUtils.getMapData("调查问卷", "questionnairesNum", platPostStation.getQuestionnairesNum(), tempMap);
        }
        String fieldStringAccess = "car_license_num";
        if(Objects.equals(appOrg,"0000")){
            fieldStringAccess = "sum(car_license_num) as car_license_num";
        }
        PlatAccess platAccess = iPlatAccessService.getPlatAccessByField("app_org", appOrg,fieldStringAccess);
        if (StringUtils.isNull(platAccess)) {
            StringUtils.getMapData("车证数量", "carlicense", 0, tempMap);
        } else {
            StringUtils.getMapData("车证数量", "carlicense", platAccess.getCarLicenseNum(), tempMap);
        }
        return tempMap;
    }

    /**
     * 近一个月报修分类占比
     */
    @Override
    public List<Map<String, Object>> getPastMonthPieData(String appOrg){
        String fieldString = "furniture,hot_cold_water,access_control,other,wall,electrical,elevator,fire_control,cleaning,air_conditioning";
        if(Objects.equals(appOrg,"0000")){
            fieldString = "sum(furniture) as furniture,sum(hot_cold_water) as hot_cold_water,sum(access_control) as access_control,sum(other) as other,sum(wall) as wall,sum(electrical) as electrical,sum(elevator) as elevator,sum(fire_control) as fire_control,sum(cleaning) as cleaning,sum(air_conditioning) as airConditioning";
        }
        PlatPostStation platPostStation = this.getPlatPostStationByField("app_org", appOrg,fieldString);
        List<Long> valueList = StringUtils.getDefaultListLong(10);
        if(StringUtils.isNotNull(platPostStation)){
            valueList = Arrays.asList(platPostStation.getFurniture(), platPostStation.getHotColdWater(), platPostStation.getAccessControl(), platPostStation.getOther(), platPostStation.getWall(), platPostStation.getElectrical(), platPostStation.getElevator(), platPostStation.getFireControl(), platPostStation.getCleaning(), platPostStation.getAirConditioning());
        }
        List<String> xList = Arrays.asList("办公家具报修", "冷热水故障", "门禁故障", "其他报修故障", "墙类/地类报修", "电气故障报修", "电梯故障", "消防设施设备故障", "保洁服务", "空调故障");
        List<String> colorList = Arrays.asList("#ff9d00", "#2f82fe", "#12db62", "#7565ef", "#079966", "#4e2ffe", "#00f6ec", "#ff7300", "#002aff", "#FF99C3");
        List<Map<String, Object>> tempList = new ArrayList<>();
        StringUtils.createdPieData(xList,colorList,valueList,tempList);
        return tempList;
    }
}
