package com.testor.module.safeCheck.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.module.safeCheck.dao.TSafeHazardCheckObjectDao;
import com.testor.module.safeCheck.model.domain.TSafeHazardCheckObject;
// import com.testor.module.safeCheck.model.vo.SafeHazardCheckObjectGroupVO;
import com.testor.module.safeCheck.model.vo.SafeHazardCheckObjectVO;
import com.testor.module.safeCheck.service.TSafeHazardCheckObjectService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import org.springframework.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 巡检对象Service业务层处理
 * 
 * @author testor-framework
 * @date 2022-08-04 11:07:48
 */
@Service
public class TSafeHazardCheckObjectServiceImpl extends SuperServiceImpl<TSafeHazardCheckObjectDao, TSafeHazardCheckObject> implements TSafeHazardCheckObjectService
{
    @Autowired(required = false)
    private TSafeHazardCheckObjectDao tSafeHazardCheckObjectDao;

//    /**
//     * @param checkObjectDTOList
//     * @return
//     */
//    public boolean editBatch(List<TSafeHazardCheckObjectDTO> checkObjectDTOList) {
//        if(checkObjectDTOList == null || checkObjectDTOList.size() == 0) {
//            return false;
//        }
//
//        List<TSafeHazardCheckObject> checkObjectList = new ArrayList<>();
//        TSafeHazardCheckObject checkObject;
//        for(TSafeHazardCheckObjectDTO checkObjectDTO : checkObjectDTOList) {
//            String objIds = checkObjectDTO.getObjIds();
//            String[] objIdArr = objIds.split(",");
//            for(String objId : objIdArr) {
//                checkObject = BeanHelper.beanToBean(checkObjectDTO, TSafeHazardCheckObject.class);
//                checkObject.setObjId(objId);
//                checkObjectList.add(checkObject);
//            }
//        }
//
//        return saveBatch(checkObjectList, checkObjectList.size());
//    }
//
//    @Transactional
//    public BaseResponse editCheckObject(TSafeHazardCheckObject checkObject) {
//        BaseResponse baseResponse = new BaseResponse<>();
//
//        UserInfo curUser = ContextUtils.getLoginUser();
//        if (StrUtil.isBlank(curUser.getOrgId())) {
//            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
//            baseResponse.setMsg("用户信息错误");
//            return baseResponse;
//        }
//
//        String userId = curUser.getUserId();
//
//        String checkPlanId = checkObject.getPlanId();
//        String dataId = checkObject.getId();
//        boolean checkResult = checkUniqueness(checkPlanId, dataId, checkObject.getObjId());
//        if (!checkResult) {
//            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
//            baseResponse.setMsg("已存在相同的排查对象");
//            return baseResponse;
//        }
//
//        Integer doResult;
//        if (StrUtil.isBlank(dataId)) { // 新增
//            checkObject.setCreateBy(userId);
//            doResult = tSafeHazardCheckObjectDao.insert(checkObject);
//        } else {
//            checkObject.setUpdateBy(userId);
//            doResult = tSafeHazardCheckObjectDao.updateById(checkObject);
//        }
//
//        if(doResult == null || doResult != 1) {
//            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
//            baseResponse.setMsg("排查对象编辑失败");
//            return baseResponse;
//        }
//
//        baseResponse.setData(checkObject);
//        return baseResponse;
//    }

//    /**
//     * 查询排查对象列表 ，按 对象分类、 排查标准 分组查询
//     * @param checkObject
//     * @return
//     */
//    public List<SafeHazardCheckObjectGroupVO> listByGroup(TSafeHazardCheckObject checkObject){
//        return tSafeHazardCheckObjectDao.listByGroup(checkObject);
//    }


    /**
     * 根据 巡检计划 编辑 巡检对象（新增、修改、删除的处理）
     * @param planId
     * @param checkObjectList
     * @return
     */
    @Transactional
    public boolean editBatchByPlan(String planId, List<TSafeHazardCheckObject> checkObjectList) {
        if(StrUtil.isBlank(planId) || checkObjectList == null || checkObjectList.size() == 0) {
            return false;
        }

        Map<String, List<TSafeHazardCheckObject>> checkObjectMap = analysisCheckObject(planId, checkObjectList);
        List<TSafeHazardCheckObject> newCheckObjectList = checkObjectMap.get("new");
        List<TSafeHazardCheckObject> editCheckObjectList = checkObjectMap.get("edit");
        List<TSafeHazardCheckObject> deleteCheckObjectList = checkObjectMap.get("delete");

        if(editCheckObjectList == null) {
            editCheckObjectList = new ArrayList<>();
        }

        // 新增
        if(newCheckObjectList != null && newCheckObjectList.size() > 0) {
            for(TSafeHazardCheckObject checkObject : newCheckObjectList){
                checkObject.setPlanId(planId);
            }
            editCheckObjectList.addAll(newCheckObjectList);
        }

        // 删除
        if(deleteCheckObjectList != null && deleteCheckObjectList.size() > 0) {
            for(TSafeHazardCheckObject checkObject : deleteCheckObjectList){
                checkObject.setStatus(BizConstants.STATUS_DELETE);
            }
            editCheckObjectList.addAll(deleteCheckObjectList);
        }

        return saveOrUpdateBatch(editCheckObjectList, editCheckObjectList.size());
    }

    /**
     * 检测 排查对象 是否都唯一
     * @return true - 唯一； false - 不唯一
     */
    private boolean checkUniqueness(String checkPlanId, String checkObjId, String objId){
        LambdaQueryWrapper<TSafeHazardCheckObject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSafeHazardCheckObject::getStatus, BizConstants.STATUS_ENABLE)
                .eq(TSafeHazardCheckObject::getPlanId, checkPlanId)
                .eq(TSafeHazardCheckObject::getObjId, objId) ;
        if(!StrUtil.isBlank(checkObjId)) {
            queryWrapper.ne(TSafeHazardCheckObject::getId, checkObjId);
        }
        List<TSafeHazardCheckObject> list = tSafeHazardCheckObjectDao.selectList(queryWrapper);
        if(list == null || list.size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据巡检计划id 查询 巡检对象
     * @param planId
     * @return
     */
    public List<TSafeHazardCheckObject> listByPlan(String planId) {
        if(StrUtil.isBlank(planId)) {
            return null;
        }

        LambdaQueryWrapper<TSafeHazardCheckObject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSafeHazardCheckObject::getStatus, BizConstants.STATUS_ENABLE)
                .eq(TSafeHazardCheckObject::getPlanId, planId);
        List<TSafeHazardCheckObject> checkObjectList = tSafeHazardCheckObjectDao.selectList(queryWrapper);
        return checkObjectList;
    }

    /**
     * 解析、区分 巡检对象： 新增、 已存在编辑、 删除
     * @param planId 计划id
     * @param checkObjectList
     * @return
     */
    public Map analysisCheckObject(String planId, List<TSafeHazardCheckObject> checkObjectList) {

        if(StrUtil.isBlank(planId)) {
            return null;
        }

        Map<String, List<TSafeHazardCheckObject>> resultMap = new HashMap<>();

        List<TSafeHazardCheckObject> newCheckObjectList = new ArrayList<>();
        List<TSafeHazardCheckObject> editCheckObjectList = new ArrayList<>();
        List<TSafeHazardCheckObject> deleteCheckObjectList = new ArrayList<>();

        List<TSafeHazardCheckObject> oldCheckObjectList = listByPlan(planId);
        if(oldCheckObjectList == null || oldCheckObjectList.size() == 0) {
            newCheckObjectList = checkObjectList;
            resultMap.put("new", newCheckObjectList);
            return resultMap;
        }

        Map<String, TSafeHazardCheckObject> checkObjectMap = new HashMap<>();
        for(TSafeHazardCheckObject checkObject : oldCheckObjectList) {
            checkObjectMap.put(checkObject.getObjId(), checkObject);
        }

        for(TSafeHazardCheckObject checkObject : checkObjectList){
            if(checkObjectMap.get(checkObject.getObjId()) != null) {
                editCheckObjectList.add(checkObject);
              //  checkObjectMap.put(checkObject.getObjId(), null);
                checkObjectMap.remove(checkObject.getObjId());
                continue;
            }
            newCheckObjectList.add(checkObject);
        }

        for (Map.Entry<String, TSafeHazardCheckObject> entry : checkObjectMap.entrySet()) {
            deleteCheckObjectList.add(entry.getValue());
        }

        resultMap.put("new", newCheckObjectList);
        resultMap.put("edit", editCheckObjectList);
        resultMap.put("delete", deleteCheckObjectList);
        return resultMap;
    }

    /**
     * 根据巡检计划，获取对象名称字符串
     * @param planId
     * @return
     */
    public String findObjectNamesByPlan(String planId) {
        if(StrUtil.isBlank(planId)) {
            return null;
        }

        List<SafeHazardCheckObjectVO> objectVOList = listVOByPlan(planId);
        if(objectVOList == null || objectVOList.size() == 0) {
            return null;
        }
        StringBuilder objNames = new StringBuilder();
        for(SafeHazardCheckObjectVO objectVO : objectVOList) {
            objNames.append(objectVO.getObjName());
            objNames.append(",");
        }
        String objNameStr = objNames.toString();
        return objNameStr.substring(0, objNameStr.length()-1);
    }

    @Override
    public List<SafeHazardCheckObjectVO> listVOByPlan(String planId) {
        return tSafeHazardCheckObjectDao.listVOByPlan(planId);
    }
}
