package com.casic.missiles.service.Impl.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.business.environment.EnvironmentListRequest;
import com.casic.missiles.dto.business.environment.EnvironmentListResponse;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.meter.MeterDictEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessEnvironmentRecordMapper;
import com.casic.missiles.mapper.business.EnvironmentListResponseMapper;
import com.casic.missiles.model.business.BusinessEnvironmentRecord;
import com.casic.missiles.service.business.IBusinessEnvironmentRecordService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2023-02-02
 */
@Service
public class BusinessEnvironmentRecordServiceImpl extends ServiceImpl<BusinessEnvironmentRecordMapper, BusinessEnvironmentRecord> implements IBusinessEnvironmentRecordService {


    @Resource
    private EnvironmentListResponseMapper environmentListResponseMapper;
    @Resource
    private IBaseExportService iBaseExportService;

    @Override
    public Page<EnvironmentListResponse> environmentListPage(Page<EnvironmentListResponse> page, EnvironmentListRequest request) throws Exception {

        // 获取列表
        QueryWrapper<EnvironmentListResponse> wrapper = listParamWrapper(request);
        Page<EnvironmentListResponse> environmentListResponsePage = this.environmentListResponseMapper.selectPage(page, wrapper);
        if (!CollectionUtils.isEmpty(environmentListResponsePage.getRecords())) {
            for (EnvironmentListResponse record : environmentListResponsePage.getRecords()) {
                DictCodeUtils.convertDictCodeToName(record);
            }
        }
        return environmentListResponsePage;
    }

    @Override
    public BusinessEnvironmentRecord environmentDetail(Long id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public ReturnDTO deleteEnvironment(Long id) {
        if (this.baseMapper.deleteById(id) > 0)
            return ReturnUtil.success();
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO updateEnvironment(BusinessEnvironmentRecord businessEnvironmentRecord) {
        if (this.baseMapper.updateById(businessEnvironmentRecord) > 0)
            return ReturnUtil.success();
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO addEnvironment(BusinessEnvironmentRecord businessEnvironmentRecord) {
        initBusinessEnvironmentRecord(businessEnvironmentRecord);
        if (baseMapper.insert(businessEnvironmentRecord) > 0)
            return ReturnUtil.success();
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public void environmentExport(EnvironmentListRequest request, HttpServletResponse response) {

        QueryWrapper<EnvironmentListResponse> wrapper = listParamWrapper(request);
        List<EnvironmentListResponse> environmentListResponseList = this.environmentListResponseMapper.selectList(wrapper);
        try {
            iBaseExportService.exportExcel(response, EnvironmentListResponse.class,
                    environmentListResponseList, ExportEnum.ENVIRONMENT_DATA.getSheetName());
        } catch (IOException e) {
            log.error("环境记录单导出出现异常，异常信息为{}", e);
        }
    }

    private void initBusinessEnvironmentRecord(BusinessEnvironmentRecord businessEnvironmentRecord) {
        Long maxNo = this.baseMapper.selectMaxCode();
        String environmentNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.ENVIRONMENT_PREFIX, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        businessEnvironmentRecord.setCreateUser(authUser.getId());
        businessEnvironmentRecord.setRecorder(StringUtils.
                isNotBlank(businessEnvironmentRecord.getRecorder()) ?
                businessEnvironmentRecord.getRecorder() : authUser.getName());
        businessEnvironmentRecord.setEnvironmentCode(environmentNo);
    }


    private QueryWrapper<EnvironmentListResponse> listParamWrapper(EnvironmentListRequest request) {
        QueryWrapper<EnvironmentListResponse> wrapper = new QueryWrapper<>();
        if(!CollectionUtils.isEmpty(request.getIds()) && request.getIds().size()!=0){
            wrapper.in("id", request.getIds());
        }
        wrapper.like(StringUtils.isNotBlank(request.getEnvironmentCode()), "environment_code", request.getEnvironmentCode());
        wrapper.like(StringUtils.isNotBlank(request.getRoomNumber()), "room_number", request.getRoomNumber());
        wrapper.apply(StringUtils.isNotBlank(request.getStartTime()),//apply方法传入参数名不能为空
                "{0} <= DATE_FORMAT(record_time,'%Y-%m-%d %H:%i:%s')", request.getStartTime());
        wrapper.apply(StringUtils.isNotBlank(request.getEndTime()),
                "{0} >= DATE_FORMAT(record_time,'%Y-%m-%d %H:%i:%s')", request.getEndTime());
        wrapper.eq("is_del", MeterDictEnum.DELETE_FALSE);
        return wrapper;
    }


}
