package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationCoordinateDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationInfoDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationRecordInfo;
import com.yeejoin.amos.boot.module.jxiop.api.entity.*;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.service.IStationBasicService;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationBasicDto;
import com.yeejoin.amos.boot.module.jxiop.biz.utils.MapUtils;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 场站基础信息表服务实现类
 *
 * @author system_generator
 * @date 2023-04-20
 */
@Service
public class StationBasicServiceImpl extends BaseService<StationBasicDto, StationBasic, StationBasicMapper> implements IStationBasicService {


    @Autowired
    StationCoordinateServiceImpl stationCoordinateServiceImpl;

    @Autowired
    PersonBasicServiceImpl personBasicServiceImpl;
    @Autowired
    StationBasicMapper stationBasicMapper;
    @Autowired
    IndicatorServiceImpl indicatorServiceImpl;
    @Autowired
    RegionServiceImpl regionServiceImpl;
    @Autowired
    MapRegionServiceImpl mapRegionServiceImpl;
    private final String CZLX = "CZLX";
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页查询
     */
    public Page<StationBasicDto> queryForStationBasicPage(Page<StationBasicDto> page) {
        return this.queryForPage(page, null, false);
    }


    /**
     * 分页查询
     */
    public Page<StationBasicDto> queryPage(Page<StationBasicDto> page,
                                           String stationMasterName,
                                           String stationName,
                                           String stationType,
                                           String orgCode
    ) {
        List<StationBasicDto> list = stationBasicMapper.queryPage((page.getCurrent() - 1) * page.getSize(), page.getSize(), stationMasterName,
                stationName,
                stationType, orgCode);
        List<StationBasicDto> listcount = stationBasicMapper.queryPagecount(stationMasterName,
                stationName,
                stationType,
                orgCode);
        page.setTotal(listcount.size());
        page.setRecords(list);
        return page;
    }


    /**
     * 列表查询 示例
     */
    public List<StationBasicDto> queryForStationBasicList() {
        return this.queryForList("", false);
    }

    @Transactional
    public void add(StationBasic stationBasic) {
        stationBasic.setRecDate(new Date());
        //场站坐标信息
        List<StationCoordinate> list = stationBasic.getStationCoordinate();
        List<StationCoordinate> listdate = new ArrayList<>();
        if (stationBasic.getBelongArealist() != null) {
            stationBasic.setBelongArea(JSON.toJSONString(stationBasic.getBelongArealist()));
        }
        CompanyModel companyModel = new CompanyModel();
        //单位
        companyModel = personBasicServiceImpl.getCompanyModel(Long.parseLong(stationBasic.getArea()));
        stationBasic.setAreaName(companyModel.getCompanyName());
        stationBasic.setAreaCode(companyModel.getCompanyCode());
        //获取类型名称
        String typeName = this.queryByCode(CZLX, stationBasic.getStationType());
        stationBasic.setStationTypeName(typeName);

        //场站基本信息
        this.save(stationBasic);
        if (CollectionUtils.isEmpty(list)) {
            StationCoordinate stationCoordinate = new StationCoordinate();
            stationCoordinate.setStationId(stationBasic.getSequenceNbr());
        } else {
            for (StationCoordinate stationCoordinate : list) {
                stationCoordinate.setStationId(stationBasic.getSequenceNbr());
                listdate.add(stationCoordinate);
            }
        }
        stationCoordinateServiceImpl.saveBatch(listdate);
        //平台增加场站
        CompanyModel companyModeldata = new CompanyModel();
        companyModeldata.setCompanyName(stationBasic.getStationName());
        companyModeldata.setCompanyType("company");
        companyModeldata.setLevel("station");
        companyModeldata.setParentId(Long.valueOf(stationBasic.getArea()));
        companyModeldata.setCompanyCode(stationBasic.getStationCode());
        companyModeldata = this.addCompanyModel(companyModeldata);
        stationBasic.setProjectOrgCode(companyModeldata.getOrgCode());
        stationBasic.setPlatformStationId(companyModeldata.getSequenceNbr().toString());
        this.update(stationBasic);
    }


    private CompanyModel addCompanyModel(CompanyModel companyModel) {
        FeignClientResult<CompanyModel> Model = Privilege.companyClient.create(companyModel);
        CompanyModel user = new CompanyModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if (Model.getStatus() == 200) {
                user = Model.getResult();
            } else {
                throw new RuntimeException(Model.getMessage());
            }
        }
        return user;
    }

    private void deleteCompany(String ids) {
        FeignClientResult Model = Privilege.companyClient.deleteCompany(ids);

        CompanyModel user = new CompanyModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if (Model.getStatus() != 200) {
                throw new RuntimeException(Model.getMessage());
            }
        }

    }


    private String queryByCode(String dictCode, String dictDataKey) {
        FeignClientResult<DictionarieValueModel> Model = Systemctl.dictionarieClient.value(dictCode, dictDataKey);
        DictionarieValueModel user = new DictionarieValueModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if (Model.getStatus() == 200) {
                user = Model.getResult();
            } else {
                throw new RuntimeException(Model.getMessage());
            }
        }
        return user.getDictDataValue();
    }


    private CompanyModel updateCompanyModel(CompanyModel companyModel, Long sequenceNbr) {
        FeignClientResult<CompanyModel> Model = Privilege.companyClient.update(companyModel, sequenceNbr);
        CompanyModel user = new CompanyModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if (Model.getStatus() == 200) {
                user = Model.getResult();
            } else {
                throw new RuntimeException(Model.getMessage());
            }
        }
        return user;
    }


    @Transactional
    public void update(StationBasic stationBasic) {
        stationBasic.setRecDate(new Date());
        //场站坐标信息
        List<StationCoordinate> list = stationBasic.getStationCoordinate();
        List<StationCoordinate> listdate = new ArrayList<>();
        if (stationBasic.getBelongArealist() != null) {
            stationBasic.setBelongArea(JSON.toJSONString(stationBasic.getBelongArealist()));
        }
        CompanyModel companyModel = new CompanyModel();
        //单位
        companyModel = personBasicServiceImpl.getCompanyModel(Long.parseLong(stationBasic.getArea()));
        stationBasic.setAreaName(companyModel.getCompanyName());
        stationBasic.setAreaCode(companyModel.getCompanyCode());

        //获取类型名称
        String typeName = this.queryByCode(CZLX, stationBasic.getStationType());
        stationBasic.setStationTypeName(typeName);

        //场站基本信息
        stationBasicMapper.updateById(stationBasic);
        stationBasicMapper.deleteStationCoordinateByStationid(stationBasic.getSequenceNbr());
        for (StationCoordinate stationCoordinate : list) {
            stationCoordinate.setStationId(stationBasic.getSequenceNbr());
            listdate.add(stationCoordinate);
        }
        stationCoordinateServiceImpl.saveOrUpdateBatch(listdate);

        //平台增加场站
        CompanyModel companyModeldata = new CompanyModel();
        companyModeldata.setCompanyName(stationBasic.getStationName());
        companyModeldata.setCompanyType("company");
        companyModeldata.setLevel("station");
        companyModeldata.setParentId(Long.valueOf(stationBasic.getArea()));
        companyModeldata.setCompanyCode(stationBasic.getStationCode());
        companyModeldata = this.updateCompanyModel(companyModeldata, Long.valueOf(stationBasic.getPlatformStationId()));
        stationBasic.setProjectOrgCode(companyModeldata.getOrgCode());
        stationBasic.setPlatformStationId(companyModeldata.getSequenceNbr().toString());
        stationBasicMapper.updateById(stationBasic);
    }


    public int deleteList(String ids) {
        QueryWrapper<StationBasic> wrapper = new QueryWrapper();
        wrapper.in("sequence_nbr", ids);
        List<StationBasic> list = this.list(wrapper);
        List<String> idscom = new ArrayList<>();
        for (StationBasic personAccount : list) {
            idscom.add(personAccount.getPlatformStationId());
        }
        //删除平台
        int deleteResult = stationBasicMapper.deleteList(ids);
        this.deleteCompany(String.join(",", idscom));
        return deleteResult;
    }


    public StationBasic getById(Long sequenceNbr) {

        QueryWrapper<StationBasic> wrapper1 = new QueryWrapper();
        wrapper1.eq("sequence_nbr", sequenceNbr);
        StationBasic stationBasic = this.getOne(wrapper1);

        if (stationBasic.getBelongArea() != null) {
            stationBasic.setBelongArealist(JSON.parseArray(stationBasic.getBelongArea(), Integer.class));
        }

        QueryWrapper<StationCoordinate> wrapper = new QueryWrapper();
        wrapper.eq("station_id", sequenceNbr);
        List<StationCoordinate> list = stationCoordinateServiceImpl.list(wrapper);
        stationBasic.setStationCoordinate(list);
        return stationBasic;

    }

    public List<StationInfoDto> getStationList(String areaCode, String type) {
        JSONArray stationSelectDefault =(JSONArray)redisUtils.get("STATION_FIRST_SELECT");
        //  场站信息列表 地图接口返回使用
        List<StationInfoDto> stationInfoDtoList = new LinkedList<>();
        //场站信息列表
        List<StationRecordInfo> list = new ArrayList<>();
        //图例数据列表
        List<Indicator> indicatorList = indicatorServiceImpl.getIndicatorByType(type);
        // 如果传递areaCode 或者areaCode值不为空
        if (StringUtils.isNotEmpty(areaCode)) {
            //查询区域信息
            MapRegion mapRegion = mapRegionServiceImpl.getOne(new QueryWrapper<MapRegion>().eq("name", areaCode));
            //如果区域信息不为空则继续查询省份
            if (mapRegion != null) {
                ArrayList<String> provinces = mapRegion.getProvince();
                if (!provinces.isEmpty()) {
                    for (int i = 0; i < provinces.size(); i++) {
                        Region region = regionServiceImpl.getRegionCodeByRegionName(provinces.get(i));
                        if (region != null && region.getRegionCode() != null) {
                            list.addAll(stationBasicMapper.getStationList(String.valueOf(region.getRegionCode())));
                        }
                    }
                }
            } else {
                //如果查不到区域 则查询省份信息
                Region region = regionServiceImpl.getRegionCodeByRegionName(areaCode);
                if (region != null && region.getRegionCode() != null) {
                    list = stationBasicMapper.getStationList(String.valueOf(region.getRegionCode()));
                }
            }
        } else {
            // 全国
            list.addAll(stationBasicMapper.getStationList(null));
        }
        List<StationRecordInfo> stationRecordInfoList = list.stream().filter(stationRecordInfo -> !org.springframework.util.ObjectUtils.isEmpty(stationRecordInfo.getTitlePos())).collect(Collectors.toList());
        //遍历返回给地图的数据并对数据进行处理
        stationRecordInfoList.forEach(stationRecordInfo -> {
            StationInfoDto stationInfoDto = new StationInfoDto();
            stationInfoDto.setStationId(stationRecordInfo.getStationId());
            stationInfoDto.setPlatformStationId(stationRecordInfo.getPlatformStationId());
            stationInfoDto.setStationName(stationRecordInfo.getStationName());
            stationInfoDto.setType(stationRecordInfo.getStationType());
            if(stationRecordInfo.getStationType().contains("GFDZ")){
                stationInfoDto.setType("GFZ");
            }
            //url 暂时写死
            stationInfoDto.setUrl("https://tse4-mm.cn.bing.net/th/id/OIP-C.ySnewoc464X4Aecg9jl03AAAAA?w=162&h=180&c=7&r=0&o=5&pid=1.7");
            stationInfoDto.setJumpPath(stationRecordInfo.getJumpPath());
            if (stationRecordInfo.getBelongArea() != null) {
                stationInfoDto.setRegion(this.getProviceName(stationRecordInfo.getBelongArea()));
            }
//            ArrayList<Double> arrayList = MapUtils.geoTo3d(Double.valueOf(stationRecordInfo.getLongitude()), Double.valueOf(stationRecordInfo.getLaitude()));
            String []original = stationRecordInfo.getTitlePos().replace("[","").replace("]","").split(",");
            ArrayList<Double> doubleList = new ArrayList<>();
            for (String s : original) {
                doubleList.add(Double.parseDouble(s));
            }
            stationInfoDto.setStationCode(stationRecordInfo.getStationCode());
            stationInfoDto.setTitlePos(doubleList);
            stationInfoDto.setIndicatorData(indicatorList);
            stationInfoDto.setRiskLevel(stationRecordInfo.getRiskLevel());
            //添加默认场站选中的值
            if(!CollectionUtils.isEmpty(stationSelectDefault)){
                for (Object o : stationSelectDefault) {
                    if(o instanceof  JSONObject){
                        JSONObject jsonObject=(JSONObject) o;
                        if(stationRecordInfo.getStationId().equals(jsonObject.getLong("stationBasicId"))){
                            stationInfoDto.setEquipmentNameDefault(jsonObject.getString("equipmentNameDefault"));
                            stationInfoDto.setSubSystemDefault(jsonObject.getString("subSystemDefault"));
                            stationInfoDto.setIndexAddressDefault(jsonObject.getString("indexAddressDefault"));
                        }
                    }
                }
            }
            stationInfoDtoList.add(stationInfoDto);
        });

        return stationInfoDtoList;
    }

    public int getStationPersonByStationID(String id) {
        return stationBasicMapper.getStationPersonByStationID(id);
    }

    public String getProviceName(String belongArea) {
        String proviceName = "湖北";
        if (belongArea != null) {
            String[] strings = belongArea.replace("[", "").replace("]", "").split(",");
            if (strings.length > 0) {
                Region region = regionServiceImpl.getRegionByRegionCode(strings[0]);
                proviceName = region.getRegionName().replace("省", "").replace("市", "");
            }
        }
        return proviceName;
    }
}