package com.artfess.yhxt.thirdparty.manager.impl;

import cn.hutool.core.bean.BeanUtil;
import com.artfess.base.context.BaseContext;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;

import com.artfess.uc.exception.BaseException;
import com.artfess.yhxt.basedata.manager.BridgeInformationManager;
import com.artfess.yhxt.basedata.model.BridgeInformation;

import com.artfess.yhxt.statistics.manager.CamerasResourceManager;
import com.artfess.yhxt.statistics.model.CamerasResource;
import com.artfess.yhxt.thirdparty.manager.BizTpBridgeHealthManager;
import com.artfess.yhxt.thirdparty.model.BizTpBridge;
import com.artfess.yhxt.thirdparty.dao.BizTpBridgeDao;
import com.artfess.yhxt.thirdparty.manager.BizTpBridgeManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.thirdparty.model.BizTpBridgeHealth;
import com.artfess.yhxt.thirdparty.vo.BridgeResourceVo;
import com.artfess.yhxt.thirdparty.vo.TpBridgeCountVo;
import com.artfess.yhxt.thirdparty.vo.TpBridgePageVo;
import com.artfess.yhxt.util.PermissionUtils;
import com.artfess.yhxt.util.StreamUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 第三方传输桥梁基础信息 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author 管理员
 * @since 2023-06-15
 */
@Service
public class BizTpBridgeManagerImpl extends BaseManagerImpl<BizTpBridgeDao, BizTpBridge> implements BizTpBridgeManager {

    @Resource
    BizTpBridgeDao bizTpBridgeDao;
    @Resource
    PermissionUtils permissionUtils;
    @Resource
    BaseContext baseContext;
    @Resource
    CamerasResourceManager camerasResourceManager;
    @Resource
    BizTpBridgeHealthManager bizTpBridgeHealthManager;


    @Resource
    BridgeInformationManager bridgeInformationManager;



    @Override
    public BizTpBridge selectByCode(String bridgeCode) {
        QueryWrapper<BizTpBridge> wrapper = new QueryWrapper<>();
        wrapper.eq("BRIDGE_CODE_",bridgeCode);
        wrapper.eq("IS_DELE_","0");
        List<BizTpBridge> list = this.list(wrapper);

        if(null != list && list.size() > 0 ){
            return list.get(0);
        }
        return null;
    }

    @Override
    public BizTpBridge selectById(String id) {

        BizTpBridge bizTpBridge = bizTpBridgeDao.selectByIdNoElse(id);


        return bizTpBridge;
    }

    /**
     * 获取不同类型的桥梁数量统计
     * @return
     */
    @Override
    public TpBridgeCountVo getBridgeCount(QueryFilter<BizTpBridge> queryFilter){
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        PageBean pageBean = queryFilter.getPageBean();

        pageBean.setPageSize(-1);


        queryFilter.setPageBean(pageBean);

        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())) {
            permissionUtils.addPermission(queryFilter);
        }
        IPage<BizTpBridge> result = baseMapper.queryBizTpBridge(convert2IPage(pageBean), map, convert2Wrapper(queryFilter, currentModelClass()));

        List<BizTpBridge> list = result.getRecords();

        TpBridgeCountVo countVo = new TpBridgeCountVo();

        if(null != list && list.size() > 0 ){
            Map<Integer, List<BizTpBridge>> resultMap = list.stream().collect(Collectors.groupingBy(BizTpBridge::getType));
            //桥梁类型 1.悬索桥 2.斜拉桥 3.梁桥 4.拱桥
            List<BizTpBridge> bizTpBridges1 = resultMap.get(1);
            List<BizTpBridge> bizTpBridges2 = resultMap.get(2);
            List<BizTpBridge> bizTpBridges3 = resultMap.get(3);
            List<BizTpBridge> bizTpBridges4 = resultMap.get(4);

            if(null != bizTpBridges1){
                countVo.setSuspensionCount(bizTpBridges1.size());
            }
             if(null != bizTpBridges2){
                countVo.setCableStayedCount(bizTpBridges2.size());
            }
             if(null != bizTpBridges3){
                countVo.setArchCount(bizTpBridges3.size());
            }
             if(null != bizTpBridges4){
                countVo.setGirderCount(bizTpBridges4.size());
            }
        }
        return countVo;
    }


    /**
     * 分业查询
     * @param queryFilter
     * @return
     */
    @Override
    public PageList<TpBridgePageVo>  pageVo(QueryFilter<BizTpBridge> queryFilter) {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())) {
            permissionUtils.addPermission(queryFilter);
        }

        IPage<BizTpBridge> result = baseMapper.queryBizTpBridge(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));


        List<BizTpBridge> rows = result.getRecords();


        if(null == rows  || rows.isEmpty()){
            return new PageList();
        }

        List<String> ids = rows.stream().map(e -> e.getBridgeId()).collect(Collectors.toList());
        List<BridgeInformation> bridgeInformations = bridgeInformationManager.listByIds(ids);

        Map<String, BridgeInformation> bridgeInformationMap = StreamUtil.toMap(bridgeInformations, BridgeInformation::getId);

        List<TpBridgePageVo> vos = new ArrayList<>();


        for (BizTpBridge row : rows) {
            TpBridgePageVo tpBridgePageVo = new TpBridgePageVo();

            BeanUtil.copyProperties(row, tpBridgePageVo);


            BridgeInformation information = bridgeInformationMap.get(row.getBridgeId());

            if(null != information){
                BeanUtil.copyProperties(information, tpBridgePageVo);
            }

            QueryWrapper<BizTpBridgeHealth> healthQueryWrapper = new QueryWrapper<>();

            healthQueryWrapper.eq("TP_BRIDGE_ID_", row.getBridgeId());
            List<BizTpBridgeHealth> healths = bizTpBridgeHealthManager.list(healthQueryWrapper);

            if(null != healths && !healths.isEmpty()){

                tpBridgePageVo.setState(healths.get(healths.size()-1).getHealthAssessmentLevel());
            }
            vos.add(tpBridgePageVo);
        }
        PageList<TpBridgePageVo> pageList = new PageList();
        pageList.setPage(result.getPages());
        pageList.setPageSize(result.getSize());
        pageList.setTotal(result.getTotal());
        pageList.setRows(vos);
        return pageList;
    }


    /**
     * 详情，包含视频资源相关属性
     * @param id
     * @return
     */
    @Override
    public BridgeResourceVo detailById(String id) {

        BridgeInformation bridgeInformation = bridgeInformationManager.getById(id);

        if(null == bridgeInformation){
            throw new BaseException("桥梁不存在");
        }

        BridgeResourceVo resourceVo = new BridgeResourceVo();

        resourceVo.setBridgeInformation(bridgeInformation);


        QueryWrapper<CamerasResource> queryWrapper = new QueryWrapper<>();

        String name = bridgeInformation.getName();

        //todo 暂时取桥梁名称前两位进行匹配
        String substring = name.substring(0, 2);

        queryWrapper.like("NAME_", substring);

        List<CamerasResource> list = camerasResourceManager.list(queryWrapper);

        resourceVo.setResources(list);

        QueryWrapper<BizTpBridgeHealth> healthQueryWrapper = new QueryWrapper<>();

        healthQueryWrapper.eq("TP_BRIDGE_ID_", id);
        List<BizTpBridgeHealth> healths = bizTpBridgeHealthManager.list(healthQueryWrapper);

        if(null != healths && !healths.isEmpty()){
            resourceVo.setCount(healths.size());
            resourceVo.setHealthAssessmentLevel(healths.get(healths.size()-1).getHealthAssessmentLevel());
        }


        return resourceVo;
    }
}
