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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.common.constant.StatusEnum;
import com.testor.ddd.safetyControl.infrastructure.repository.equipment.dao.TSafeEquipmentTypeDao;
import com.testor.ddd.safetyControl.infrastructure.repository.space.dao.TSafeSpaceTypeDao;
import com.testor.ddd.safetyControl.infrastructure.repository.space.entity.TSafeSpaceTypeDO;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentTypeDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.equipment.TSafeEquipmentTypeVO;
import com.testor.module.safe.dao.TSafeHazardStandardTypeDao;
import com.testor.module.safe.model.domain.TSafeHazardStandardType;
import com.testor.module.safe.model.dto.TSafeHazardStandardTypeAllVO;
import com.testor.module.safe.model.dto.TSafeHazardStandardTypeEditDTO;
import com.testor.module.safe.model.dto.TSafeHazardStandardTypeParam;
import com.testor.module.safe.model.vo.TSafeHazardStandardTypeVO;
import com.testor.module.safe.service.TSafeHazardStandardTypeService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.response.ResponseInfo;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 巡检排查标准管理Service业务层处理
 *
 * @author testor-framework
 * @date 2022-08-08 10:55:55
 */
@Service
public class TSafeHazardStandardTypeServiceImpl extends SuperServiceImpl<TSafeHazardStandardTypeDao, TSafeHazardStandardType> implements TSafeHazardStandardTypeService {
    @Autowired(required = false)
    private TSafeHazardStandardTypeDao tSafeHazardStandardTypeDao;

    @Autowired(required = false)
    private TSafeSpaceTypeDao tSafeSpaceTypeRepo;

    @Autowired(required = false)
    private TSafeEquipmentTypeDao tSafeEquipmentTypeDao;

    @Override
    public TSafeHazardStandardType getOne(TSafeHazardStandardTypeParam queryParam) {
        QueryWrapper<TSafeHazardStandardType> query = this.createQuery(queryParam);
        return getOne(query);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BaseResponse<TSafeHazardStandardType> addEntity(TSafeHazardStandardTypeEditDTO addRequest) {
        BaseResponse<TSafeHazardStandardType> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {

            List<TSafeHazardStandardType> addTSafeHazardStandardTypes = new ArrayList<>();

            String id = IdHelper.getId32bit();
            String name = addRequest.getName();
            TSafeHazardStandardTypeParam tSafeHazardStandardTypeParam = new TSafeHazardStandardTypeParam();
            tSafeHazardStandardTypeParam.setName(name).setStatus(StatusEnum.USE.getCode());
            TSafeHazardStandardType one = getOne(tSafeHazardStandardTypeParam);
            if (ObjectHelper.isNotEmpty(one)) {
                baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                baseResponse.setMsg("名称不可重复");
                return baseResponse;
            }

            TSafeHazardStandardType data = BeanHelper.beanToBean(addRequest, TSafeHazardStandardType.class);
            data.setSort(currentSort());
            data.setId(id);

            addTSafeHazardStandardTypes.add(data);

            List<TSafeHazardStandardTypeEditDTO> standardTypeEditDTOS = addRequest.getStandardTypeEditDTOS();
            for (TSafeHazardStandardTypeEditDTO standardTypeEditDTO : standardTypeEditDTOS) {
                TSafeHazardStandardTypeParam tSafeHazardStandardTypeParamChild = new TSafeHazardStandardTypeParam();
                tSafeHazardStandardTypeParamChild.setName(name).setStatus(StatusEnum.USE.getCode());
                TSafeHazardStandardType oneChild = getOne(tSafeHazardStandardTypeParamChild);
                if (ObjectHelper.isNotEmpty(oneChild)) {
                    baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                    baseResponse.setMsg("名称不可重复");
                    return baseResponse;
                }

                TSafeHazardStandardType standardTypeChild = BeanHelper.beanToBean(standardTypeEditDTO, TSafeHazardStandardType.class);
                String childId = IdHelper.getId32bit();
                standardTypeChild.setParentId(id);
                standardTypeChild.setId(childId);

                addTSafeHazardStandardTypes.add(standardTypeChild);
            }


            boolean result = saveBatch(addTSafeHazardStandardTypes);
            if (result) {
                TSafeHazardStandardType newEntity = new TSafeHazardStandardType();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BaseResponse<TSafeHazardStandardType> updateEntity(TSafeHazardStandardTypeEditDTO updateRequest) {
        BaseResponse<TSafeHazardStandardType> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {

            String id = updateRequest.getId();
            TSafeHazardStandardType tSafeHazardStandardTypeById = getById(id);
            if (ObjectHelper.isEmpty(tSafeHazardStandardTypeById)) {
                baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                baseResponse.setMsg("资源不存在");
                return baseResponse;
            }

            List<TSafeHazardStandardType> tSafeHazardStandardTypeDeleteList = list(new QueryWrapper<TSafeHazardStandardType>().eq("parent_id", id));
            tSafeHazardStandardTypeDeleteList.add(tSafeHazardStandardTypeById);
            tSafeHazardStandardTypeDeleteList.forEach(t -> t.setStatus(StatusEnum.DELETE.getCode()));
            boolean updateBatchById = updateBatchById(tSafeHazardStandardTypeDeleteList);
            if (updateBatchById) {
                BaseResponse<TSafeHazardStandardType> tSafeHazardStandardTypeBaseResponse = addEntity(updateRequest);
                Integer code = tSafeHazardStandardTypeBaseResponse.getCode();
                if (BaseStatusEnum.SUCCESS.code() == code) {
                    baseResponse.setData(tSafeHazardStandardTypeBaseResponse.getData());
                    return baseResponse;
                } else {
                    throw new ApiException(new ResponseInfo(BaseStatusEnum.UN_DATA.code(), "巡检排查标准修改失败"));
                }
            }

        } else {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("传值异常");
            return baseResponse;
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BaseResponseList<TSafeHazardStandardTypeVO>> listEntity(TSafeHazardStandardTypeParam param) {
        BaseResponse<BaseResponseList<TSafeHazardStandardTypeVO>> baseResponse = new BaseResponse<>();
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
//        Long offset = (page - 1) * limit;
//        List<TSafeHazardStandardType> resultList = tSafeHazardStandardTypeDao.getTSafeHazardStandardTypePage(limit, offset);
//        int count = tSafeHazardStandardTypeDao.count();

        Page<TSafeHazardStandardType> resultPage = new Page<>(page, limit);

        QueryWrapper<TSafeHazardStandardType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("\"level\"", 1);
        queryWrapper.eq("status", StatusEnum.USE.getCode());
        queryWrapper.orderByAsc("sort");
        Page<TSafeHazardStandardType> resultList = page(resultPage, queryWrapper);

        List<TSafeHazardStandardType> records = resultList.getRecords();
        List<TSafeHazardStandardTypeVO> tSafeHazardStandardTypeVOS = BeanHelper.listToList(records, TSafeHazardStandardTypeVO.class);
        for (TSafeHazardStandardTypeVO tSafeHazardStandardTypeVO : tSafeHazardStandardTypeVOS) {
            String id = tSafeHazardStandardTypeVO.getId();

            queryWrapper.clear();
            queryWrapper.eq("parent_id", id);
            queryWrapper.eq("\"level\"", 2);
            queryWrapper.eq("status", StatusEnum.USE.getCode());
            List<TSafeHazardStandardType> list = list(queryWrapper);
            List<TSafeHazardStandardTypeVO> tSafeHazardStandardTypeVOS1 = BeanHelper.listToList(list, TSafeHazardStandardTypeVO.class);

            tSafeHazardStandardTypeVO.setStandardTypeEditDTOS(tSafeHazardStandardTypeVOS1);
        }


        BaseResponseList<TSafeHazardStandardTypeVO> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(tSafeHazardStandardTypeVOS);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @Override
    public BaseResponse<List<TSafeHazardStandardTypeAllVO>> listAll() {
        BaseResponse<List<TSafeHazardStandardTypeAllVO>> baseResponse = new BaseResponse<>();
        List<TSafeHazardStandardType> listLevel = list(new QueryWrapper<TSafeHazardStandardType>().eq("\"level\"", 1).eq("status", StatusEnum.USE.getCode()));
        List<TSafeHazardStandardTypeAllVO> listLevelAllVOS = BeanHelper.listToList(listLevel, TSafeHazardStandardTypeAllVO.class);
        for (TSafeHazardStandardTypeAllVO tSafeHazardStandardTypeLevelVO : listLevelAllVOS) {
            String idLevel = tSafeHazardStandardTypeLevelVO.getId();
            String builtIn = tSafeHazardStandardTypeLevelVO.getBuiltIn();
            if ("0".equals(builtIn)) {
                List<TSafeHazardStandardType> list = list(new QueryWrapper<TSafeHazardStandardType>().eq("parent_id", idLevel).eq("\"level\"", 2).eq("status", StatusEnum.USE.getCode()));
                List<TSafeHazardStandardTypeAllVO> tSafeHazardStandardTypeAllVOS = BeanHelper.listToList(list, TSafeHazardStandardTypeAllVO.class);
                for (TSafeHazardStandardTypeAllVO tSafeHazardStandardTypeAllVO : tSafeHazardStandardTypeAllVOS) {
                    tSafeHazardStandardTypeAllVO.setName(tSafeHazardStandardTypeAllVO.getCategoryItem());
                }
                tSafeHazardStandardTypeLevelVO.setTypeAllVOList(tSafeHazardStandardTypeAllVOS);
            } else {
                String name = tSafeHazardStandardTypeLevelVO.getName();
                if ("设备设施".equals(name)) {
                    // 设备
                    TSafeEquipmentTypeDTOParam param = new TSafeEquipmentTypeDTOParam();
                    Long page =
                            StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
                    Long limit =
                            StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
                    Page<TSafeEquipmentTypeVO> resultPage = new Page<>(page, limit);
//                    UserInfo curUser = ContextUtils.getLoginUser();
                    /*String curUserOrgId = curUser.getOrgId();
                    param.setOrgId(curUserOrgId);*/
                    IPage<TSafeEquipmentTypeVO> tSafeEquipmentTypeVOIPage = tSafeEquipmentTypeDao.listPage(resultPage, param);
                    List<TSafeEquipmentTypeVO> records = tSafeEquipmentTypeVOIPage.getRecords();
                    List<TSafeHazardStandardTypeAllVO> tSafeHazardStandardTypeAllVOS = BeanHelper.listToList(records, TSafeHazardStandardTypeAllVO.class);
                    tSafeHazardStandardTypeLevelVO.setTypeAllVOList(tSafeHazardStandardTypeAllVOS);
//                    Map<String,String > map=new HashMap<>(16);


//                    List<TSafeHazardStandardTypeAllVO> tSafeHazardStandardTypeAllVOS = OrikaUtils.conversionList(records, TSafeHazardStandardTypeAllVO.class, map);
//                    tSafeHazardStandardTypeLevelVO.setTypeAllVOList(tSafeHazardStandardTypeAllVOS);

                } else if ("空间场所".equals(name)) {
                    // 空间场所
                    List<TSafeSpaceTypeDO> tSafeSpaceTypeDOS = tSafeSpaceTypeRepo.selectList(new QueryWrapper<TSafeSpaceTypeDO>().eq("status", StatusEnum.USE.getCode()));
                    List<TSafeHazardStandardTypeAllVO> tSafeHazardStandardTypeAllVOS = BeanHelper.listToList(tSafeSpaceTypeDOS, TSafeHazardStandardTypeAllVO.class);
                    tSafeHazardStandardTypeLevelVO.setTypeAllVOList(tSafeHazardStandardTypeAllVOS);
                }
            }

        }
        baseResponse.setData(listLevelAllVOS);
        return baseResponse;
    }

    @Override
    public List<TSafeHazardStandardType> listLevelOne() {
        return list(new QueryWrapper<TSafeHazardStandardType>().eq("\"level\"", 1).eq("status", StatusEnum.USE.getCode()));
    }


    @Override
    public int maxSort() {
        Integer sort = tSafeHazardStandardTypeDao.maxSort();
        if (null == sort) {
            return 0;
        }
        return sort;
    }

    @Override
    public int currentSort() {
        return maxSort() + 1;
    }


    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSafeHazardStandardType> createQuery(TSafeHazardStandardTypeParam queryParam) {
        QueryWrapper<TSafeHazardStandardType> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TSafeHazardStandardType.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TSafeHazardStandardType.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TSafeHazardStandardType.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TSafeHazardStandardType.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSafeHazardStandardType.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getName())) {
            queryWrapper.like(TSafeHazardStandardType.NAME, queryParam.getName());
        }
        if (StringHelper.isNotEmpty(queryParam.getCategoryItem())) {
            queryWrapper.eq(TSafeHazardStandardType.CATEGORY_ITEM, queryParam.getCategoryItem());
        }
        if (StringHelper.isNotEmpty(queryParam.getBuiltIn())) {
            queryWrapper.eq(TSafeHazardStandardType.BUILT_IN, queryParam.getBuiltIn());
        }
        if (StringHelper.isNotEmpty(queryParam.getImage())) {
            queryWrapper.eq(TSafeHazardStandardType.IMAGE, queryParam.getImage());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getSort())) {
            queryWrapper.eq(TSafeHazardStandardType.SORT, queryParam.getSort());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getLevel())) {
            queryWrapper.eq(TSafeHazardStandardType.LEVEL, queryParam.getLevel());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSafeHazardStandardType.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSafeHazardStandardType.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TSafeHazardStandardType.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
