package com.testor.module.contractor.ledger.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.model.domain.SysDictData;
import com.testor.biz.sys.dict.data.service.SysDictDataService;
import com.testor.biz.sys.dict.type.model.domain.SysDictType;
import com.testor.biz.sys.dict.type.service.SysDictTypeService;
import com.testor.common.core.utils.StringUtils;
import com.testor.module.contractor.ledger.dao.TContractorToolsDao;
import com.testor.module.contractor.ledger.model.domain.TContractorTools;
import com.testor.module.contractor.ledger.model.dto.TContractorToolsExcelDto;
import com.testor.module.contractor.ledger.model.dto.TContractorToolsParam;
import com.testor.module.contractor.ledger.service.TContractorToolsService;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
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.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 工器具台账Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-11-19 10:30:09
 */
@Service
public class TContractorToolsServiceImpl extends SuperServiceImpl<TContractorToolsDao, TContractorTools> implements TContractorToolsService
{
    Logger logger = org.slf4j.LoggerFactory.getLogger(TContractorToolsServiceImpl.class);

    @Autowired(required = false)
    private TContractorToolsDao tContractorToolsDao;

    @Resource
    private SysDictDataService dictDataService;
    @Resource
    private SysDictTypeService dictTypeService;

    @Autowired
    private NewSysOrgService newSysOrgService;

    /**
     * 批量导入工器具台账
     * @param list
     * @return
     */
    @Override
    public BaseResponse<String> importExcel(List<TContractorToolsExcelDto> list) {
        BaseResponse<String> baseResponse = new BaseResponse<>();

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        String curUserOrgId = curUser.getOrgId();
        String userId = curUser.getUserId();

        //判断是否为null
        if (StringUtils.isEmpty(list)) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("上传文件数据错误");
            return baseResponse;
        }

        StringBuilder sbMsg = new StringBuilder();
        int index = 1;
        Map<String, String> typeMap = findDictDataMap("contractor_tools_type");
        if(StringUtils.isEmpty(typeMap)){
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("工器具类型缺少数据字典配置信息");
            return baseResponse;
        }
        try {
            for(TContractorToolsExcelDto dto : list){
                if(StringUtils.isBlank(dto.getToolsName()) || StringUtils.isBlank(dto.getType()) || StringUtils.isBlank(dto.getModel())){
                    sbMsg.append("第"+(index++)+"行数据不完整，请检查！");
                    continue;
                }
                TContractorTools tools = BeanHelper.beanToBean(dto, TContractorTools.class);
                tools.setOrgId(curUserOrgId);
                tools.setCreateBy(userId);
                String typeId = typeMap.get(dto.getType());
                tools.setTypeId(typeId);
                Date checkTime = dto.getCheckTime();
                if(checkTime == null){
                    tools.setCheckTime(new Date());
                } else {
                    tools.setCheckTime(checkTime);
                }
                tools.setStatus(BizConstants.STATUS_ENABLE);
                String id = IdHelper.getId32bit();
                tools.setId(id);
                this.save(tools);
            }
        }catch (Exception e) {
            logger.error("导入工器具台账失败, 错误信息：" + e.getMessage(), e);
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setData(e.getMessage());
            return baseResponse;
        }
        baseResponse.setData(StringUtils.isEmpty(sbMsg.toString()) ? "导入成功" : sbMsg.toString());
        return baseResponse;
    }

    @Override
    public Page<TContractorTools> listEntity(TContractorToolsParam param) {
        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<TContractorTools> resultPage=new Page<>(page,limit);
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TContractorTools> queryWrapper=this.createQuery(param);
        return this.page(resultPage, queryWrapper);
    }

    @Override
    public List<TContractorTools> listAllEntity(TContractorToolsParam param) {
        QueryWrapper<TContractorTools> queryWrapper=this.createQuery(param);
        return this.list(queryWrapper);
    }

    private Map<String, String> findDictDataMap(String dictType) {
        if (StrUtil.isBlank(dictType)) {
            return null;
        }
        Map<String, String> dictDataMap = new HashMap<>();

        QueryWrapper<SysDictType> typeQueryWrapper = new QueryWrapper<>();
        typeQueryWrapper.eq("dict_type", dictType);
        SysDictType dictTypeObj = dictTypeService.getOne(typeQueryWrapper);

        LambdaQueryWrapper<SysDictData> dataQueryWrapper = new LambdaQueryWrapper<>();
        dataQueryWrapper.eq(SysDictData::getDictId, dictTypeObj.getDictId())
                .eq(SysDictData::getStatus, BizConstants.STATUS_ENABLE);
        List<SysDictData> dictDataList = dictDataService.list(dataQueryWrapper);
        if (dictDataList == null || dictDataList.size() == 0) {
            return null;
        }
        for (SysDictData dictData : dictDataList) {
            dictDataMap.put(dictData.getDictValue(), dictData.getDictDataId());
        }
        return dictDataMap;
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TContractorTools> createQuery(TContractorToolsParam queryParam){
        QueryWrapper<TContractorTools> queryWrapper=new QueryWrapper<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(orgId);
        //查询下级机构id
        queryWrapper.in("org_id", idsChildrenById);
        if (ObjectHelper.isNotEmpty(queryParam.getIds())) {
            if ("0".equals(queryParam.getTypeQuery())){
                queryWrapper.notIn("id", queryParam.getIds());
            }else {
                queryWrapper.in("id", queryParam.getIds());
            }
        }
        if(StringHelper.isNotEmpty(queryParam.getToolsName())){
            queryWrapper.like(TContractorTools.TOOLS_NAME,queryParam.getToolsName());
        }
        if(StringHelper.isNotEmpty(queryParam.getTypeId())){
            queryWrapper.eq(TContractorTools.TYPE_ID,queryParam.getTypeId());
        }
        if(StringHelper.isNotEmpty(queryParam.getType())){
            queryWrapper.eq(TContractorTools.TYPE,queryParam.getType());
        }
        if(StringHelper.isNotEmpty(queryParam.getModel())){
            queryWrapper.eq(TContractorTools.MODEL,queryParam.getModel());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getNum())){
            queryWrapper.eq(TContractorTools.NUM,queryParam.getNum());
        }
        if(StringHelper.isNotEmpty(queryParam.getPurpose())){
            queryWrapper.eq(TContractorTools.PURPOSE,queryParam.getPurpose());
        }
        if(StringHelper.isNotEmpty(queryParam.getCheckStatus())){
            queryWrapper.eq(TContractorTools.CHECK_STATUS,queryParam.getCheckStatus());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getCheckTime())){
            queryWrapper.eq(TContractorTools.CHECK_TIME,queryParam.getCheckTime());
        }
        if(StringHelper.isNotEmpty(queryParam.getIsPass())){
            queryWrapper.eq(TContractorTools.IS_PASS,queryParam.getIsPass());
        }
        if(StringHelper.isNotEmpty(queryParam.getComplianceCertificate())){
            queryWrapper.eq(TContractorTools.COMPLIANCE_CERTIFICATE,queryParam.getComplianceCertificate());
        }
        if(StringHelper.isNotEmpty(queryParam.getOrgId())){
            queryWrapper.eq(TContractorTools.ORG_ID,queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TContractorTools.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TContractorTools.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(TContractorTools.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
