package com.sckw.fleet.service;

import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.fleet.dao.KwfFleetMapper;
import com.sckw.fleet.model.KwfFleet;
import com.sckw.fleet.model.dto.KwfFleetDto;
import com.sckw.fleet.model.vo.KwfFleetTruckCountVo;
import com.sckw.fleet.model.vo.KwfFleetVo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zk
 * @desc 车队
 * @date 2023/7/6 0006
 */
@Service
public class KwfFleetService {

    @Autowired
    KwfFleetMapper fleetDao;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    /**
     * @param key 主键id
     * @desc 根据主键查询
     * @author zk
     * @date 2023/7/6
     **/
    public KwfFleet selectByKey(Long key) {
        return fleetDao.selectById(key);
    }

    /**
     * @param params 分页参数
     * @desc 分页查询
     * @author zk
     * @date 2023/7/6
     **/
    public List<KwfFleetVo> findPage(Map<String, Object> params) {
        /**获取查询数据集**/
        params.put("entId", LoginUserHolder.getEntId());
        List<KwfFleetVo> fleets = fleetDao.findPage(params);

        /**获取查询数据**/
        List<Long> createBys = new ArrayList<>();
        for (KwfFleetVo fleetVo:fleets) {
            createBys.add(Long.parseLong(fleetVo.getCreateBy()));
        }
        //用户数据集
        createBys = createBys.stream().distinct().collect(Collectors.toList());
        Map<Long, UserCacheResDto> users = remoteSystemService.queryUserCacheMapByIds(createBys);

        /**数据组装**/
        for (KwfFleetVo fleetVo:fleets) {
            UserCacheResDto user = users == null ? null : users.get(Long.parseLong(fleetVo.getCreateBy()));
            fleetVo.setCreateByName(user != null ? user.getName() : null);
        }
        return fleets;
    }

    /**
     * @param params 查询参数
     * @desc 查询
     * @author zk
     * @date 2023/7/6
     **/
    public List<Map<String, Object>> findList(Map<String, Object> params) {
        return fleetDao.findList(params);
    }

    /**
     * @param params 新增参数
     * @desc 新增司机
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult add(KwfFleetDto params) {
        /**唯一性交易**/
        List<Map<String, Object>> fleets = fleetDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN){{
            put("wholeName", params.getName()); put("entId", LoginUserHolder.getEntId());}});
        if (!CollectionUtils.isEmpty(fleets)) {
            return HttpResult.error("车队班组已存在！");
        }

        /**新增**/
        KwfFleet fleet = new KwfFleet();
        BeanUtils.copyProperties(params, fleet);
        fleet.setEntId(LoginUserHolder.getEntId());
        int count = fleetDao.insert(fleet);
        return count > 0 ? HttpResult.ok("车队信息新增成功！") : HttpResult.error("车队信息新增失败！");
    }

    /**
     * @param params 修改参数
     * @desc 修改司机
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult update(KwfFleetDto params) {
        /**唯一性交易**/
        List<Map<String, Object>> fleets = fleetDao.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN){{
            put("name", params.getName()); put("entId", LoginUserHolder.getEntId());}});
        //校验list中对象key值是否存在与value不一致的情况
        boolean bool = CollectionUtils.listByKeyValueV1(fleets, "id", params.getId());
        if (bool) {
            return HttpResult.error("车队班组已存在！");
        }

        /**更新**/
        KwfFleet fleet = new KwfFleet();
        BeanUtils.copyProperties(params, fleet);
        int count = fleetDao.updateById(fleet);
        return count > 0 ? HttpResult.ok("车队信息修改成功！") : HttpResult.error("车队信息修改失败！");
    }

    /**
     * @param {ids：主键ID（多个以逗号隔开）}
     * @description 删除
     * @author zk
     * @date 2023/7/6
     **/
    public HttpResult del(String ids) {
        /*1.数据校验*/
        if (StringUtils.isBlank(ids)) {
            return HttpResult.error("请选择要删除的数据！");
        }

        String[] idArray = ids.split(",");
        for (String id : idArray) {
            KwfFleet fleet = fleetDao.selectById(id);
            if (fleet != null) {
                fleet.setDelFlag(Global.YES);
                if (fleetDao.updateById(fleet) <= 0) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
                }
            } else {
                return HttpResult.error("选择删除的数据已不存在！");
            }
        }
        return HttpResult.ok("删除成功！");
    }

    /**
     * @param params {entId 企业ID, fleetName 车队班组名称}
     * @desc 车辆实况统计
     * @author zk
     * @date 2023/8/4
     **/
    public Map<String, Object> findTruckList(Map<String, Object> params) {
        //全量数据统计
        params.put("entId", LoginUserHolder.getEntId());
        List<KwfFleetTruckCountVo> truckCounts = fleetDao.findTruckList(new HashMap<>(Global.NUMERICAL_SIXTEEN){{put("entId", LoginUserHolder.getEntId());}});
        KwfFleetTruckCountVo truck = new KwfFleetTruckCountVo();
        truck.setFleetTotal(truckCounts != null ? truckCounts.size() : Global.NUMERICAL_ZERO);
        for (KwfFleetTruckCountVo truckCount:truckCounts) {
            truck.setIdleTotal(truckCount.getIdleTotal() != null ? truckCount.getIdleTotal() + truck.getIdleTotal() : truck.getIdleTotal());
            truck.setTruckTotal(truckCount.getTruckTotal() != null ? truckCount.getTruckTotal() + truck.getTruckTotal() : truck.getTruckTotal());
            truck.setBusyTotal(truckCount.getBusyTotal() != null ? truckCount.getBusyTotal() + truck.getBusyTotal() : truck.getBusyTotal());
        }

        //筛选数据统计
        truckCounts = fleetDao.findTruckList(params);

        //返回数据
        Map<String, Object> result = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        result.put("truckCount", truck);
        result.put("truckCounts", truckCounts);
        return result;
    }
}
