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

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.TypeReference;
import com.project.zcustom.domain.access.PlatAccess;
import com.project.zcustom.domain.basics.PlatBasics;
import com.project.zcustom.domain.employee.PlatEmployeeHealth;
import com.project.zcustom.domain.post.PlatPostStation;
import com.project.zcustom.domain.post.PlatPostStationChart;
import com.project.zcustom.mapper.post.PlatPostStationChartMapper;
import com.project.zcustom.mapper.post.PlatPostStationMapper;
import com.project.zcustom.service.access.IPlatAccessService;
import com.project.zcustom.service.post.IPlatPostStationChartService;
import com.project.zcustom.service.post.IPlatPostStationService;
import com.project.zcustom.controller.core.PageParamVo;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.zcustom.controller.core.StringUtils;

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 PlatPostStationChartMapper platPostStationChartMapper;
    @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);
                baseMapper.updatePlatPostStation(platPostStation);
            }else{
                platPostStation = new PlatPostStation();
                this.setPlatPostStation(mapField,platPostStation);
                platPostStation.setAppOrg(appOrg);
                baseMapper.insertPlatPostStation(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","fireControl","elevator","lamp",
               "security","toilet","area","conditioner","repairs","meeting","office");
        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::setFireControlNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,6, PlatPostStation::setElevatorNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,7, PlatPostStation::setLampNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,8, PlatPostStation::setSecurityNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,9, PlatPostStation::setToiletNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,10, PlatPostStation::setAreaNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,11, PlatPostStation::setConditionerNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,12, PlatPostStation::setRepairsNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,13, PlatPostStation::setMeetingNum,Long.class);
        StringUtils.setFieldValue(platPostStation,mapField,keyList,14, PlatPostStation::setOfficeNum,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<>();
        List<Map<String, Object>> coList = StringUtils.getListMap(mapField.get("coList").toString());
        List<Map<String, Object>> elevatorList = StringUtils.getListMap(mapField.get("ElevatorList").toString());
        List<Map<String, Object>> laList = StringUtils.getListMap(mapField.get("laList").toString());
        List<Map<String, Object>> seList = StringUtils.getListMap(mapField.get("seList").toString());
        List<Map<String, Object>> toList = StringUtils.getListMap(mapField.get("toList").toString());
        List<Map<String, Object>> arList = StringUtils.getListMap(mapField.get("arList").toString());
        List<Map<String, Object>> diList = StringUtils.getListMap(mapField.get("diList").toString());
        List<Map<String, Object>> otList = StringUtils.getListMap(mapField.get("otList").toString());
        List<Map<String, Object>> meList = StringUtils.getListMap(mapField.get("meList").toString());
        List<Map<String, Object>> ofList = StringUtils.getListMap(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(0).get("co" +keyAppendList.get(i)).toString()));
            platPostStationChart.setElevatorNum(Long.parseLong(elevatorList.get(0).get("el" +keyAppendList.get(i)).toString()));
            platPostStationChart.setLaNum(Long.parseLong(laList.get(0).get("la" +keyAppendList.get(i)).toString()));
            platPostStationChart.setSeNum(Long.parseLong(seList.get(0).get("se" +keyAppendList.get(i)).toString()));
            platPostStationChart.setToNum(Long.parseLong(toList.get(0).get("to" +keyAppendList.get(i)).toString()));
            platPostStationChart.setArNum(Long.parseLong(arList.get(0).get("ar" +keyAppendList.get(i)).toString()));
            platPostStationChart.setDiNum(Long.parseLong(diList.get(0).get("di" +keyAppendList.get(i)).toString()));
            platPostStationChart.setOtNum(Long.parseLong(otList.get(0).get("ot" +keyAppendList.get(i)).toString()));
            platPostStationChart.setMeNum(Long.parseLong(meList.get(0).get("me" +keyAppendList.get(i)).toString()));
            platPostStationChart.setOfNum(Long.parseLong(ofList.get(0).get("of" +keyAppendList.get(i)).toString()));
//            chartList.add(platPostStationChart);
            platPostStationChartMapper.insertPlatPostStationChart(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 = "fire_control_num,elevator_num,lamp_num,security_num,toilet_num,area_num,conditioner_num,repairs_num,meeting_num,office_num";
        if(Objects.equals(appOrg,"0000")){
            fieldString = "sum(fire_control_num) as fire_control_num,sum(elevator_num) as elevator_num,sum(lamp_num) as lamp_num,sum(security_num) as security_num,sum(toilet_num) as toilet_num,sum(area_num) as area_num,sum(conditioner_num) as conditioner_num,sum(repairs_num) as repairs_num,sum(meeting_num) as meeting_num,sum(office_num) as office_num";
        }
        PlatPostStation platPostStation = this.getPlatPostStationByField("app_org", appOrg,fieldString);
        List<Long> valueList = StringUtils.getDefaultListLong(10);
        if(StringUtils.isNotNull(platPostStation)){
            valueList = Arrays.asList(platPostStation.getFireControlNum(), platPostStation.getElevatorNum(), platPostStation.getLampNum(), platPostStation.getSecurityNum(), platPostStation.getToiletNum(), platPostStation.getAreaNum(), platPostStation.getConditionerNum(), platPostStation.getRepairsNum(), platPostStation.getMeetingNum(), platPostStation.getOfficeNum());
        }
        List<String> xList = Arrays.asList("消防", "电梯", "照明灯具", "安防", "卫生间", "公区", "空调", "其它维修", "会议保障", "办公室");
        List<String> colorList = Arrays.asList("#ff9d00", "#2f82fe", "#12db62", "#7565ef", "#079966", "#4e2ffe", "#00f6ec", "#ff7300", "#002aff", "#e1ff00");
        List<Map<String, Object>> tempList = new ArrayList<>();
        StringUtils.createdPieData(xList,colorList,valueList,tempList);
        return tempList;
    }
}
