package com.ningdatech.carapi.industry.manage;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Component;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.carapi.common.aop.BuildChildrenRegionWrapper;
import com.ningdatech.carapi.common.constant.CommonConstant;
import com.ningdatech.carapi.common.constant.VehicleTypeEnum;
import com.ningdatech.carapi.common.util.CodeUtil;
import com.ningdatech.carapi.common.util.ExcelDownUtil;
import com.ningdatech.carapi.common.util.ExcelExportStyle;
import com.ningdatech.carapi.datascope.aop.LambdaDataScope;
import com.ningdatech.carapi.industry.entity.SafetyEquipmentInstallUseCertificateOperation;
import com.ningdatech.carapi.industry.model.dto.UseCertOperatePageParamDTO;
import com.ningdatech.carapi.industry.model.dto.UseCertOperateUpdateDTO;
import com.ningdatech.carapi.industry.model.vo.DriverTrainingCertificateVO;
import com.ningdatech.carapi.industry.model.vo.SafetyEquipmentInstallUseCertificateOperationVO;
import com.ningdatech.carapi.industry.service.ISafetyEquipmentInstallUseCertificateOperationService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @description
 * @since 2022/11/26 17:02
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SafetyEquipmentInstallUseCertificateOperationManage {

    private final ISafetyEquipmentInstallUseCertificateOperationService safetyEquipmentInstallUseCertificateOperationService;

    public PageVo<SafetyEquipmentInstallUseCertificateOperationVO> list(UseCertOperatePageParamDTO param) {
        Page<SafetyEquipmentInstallUseCertificateOperation> page = param.page();
        LambdaQueryWrapper<SafetyEquipmentInstallUseCertificateOperation> wrapper 
                = Wrappers.lambdaQuery(SafetyEquipmentInstallUseCertificateOperation.class);
        SafetyEquipmentInstallUseCertificateOperationManage context 
                = (SafetyEquipmentInstallUseCertificateOperationManage) AopContext.currentProxy();
        context.buildQuery(page,wrapper,param);
        if (CollectionUtil.isEmpty(page.getRecords())){
            return PageVo.empty();
        }
        List<SafetyEquipmentInstallUseCertificateOperationVO> data
                = page.getRecords().stream().map(o -> convert(o)).collect(Collectors.toList());
        return PageVo.of(data,page.getTotal());
    }

    @LambdaDataScope(wrapperIndex = 1)
    @BuildChildrenRegionWrapper(wrapperIndex = 1,entityIndex = 2)
    public void buildQuery(Page<SafetyEquipmentInstallUseCertificateOperation> page, LambdaQueryWrapper<SafetyEquipmentInstallUseCertificateOperation> wrapper, UseCertOperatePageParamDTO param) {
        wrapper.like(StringUtils.isNotBlank(param.getCompanyName()),SafetyEquipmentInstallUseCertificateOperation::getCompanyName,param.getCompanyName())
               .like(StringUtils.isNotBlank(param.getCarPlate()),SafetyEquipmentInstallUseCertificateOperation::getCarPlate,param.getCarPlate())
               .eq(Objects.nonNull(param.getVehicleType()),SafetyEquipmentInstallUseCertificateOperation::getVehicleType,param.getVehicleType())
               .eq(Objects.nonNull(param.getAnnualStatus()),SafetyEquipmentInstallUseCertificateOperation::getYearCheckStatus,param.getAnnualStatus())
               .eq(Objects.nonNull(param.getApplicationItem()),SafetyEquipmentInstallUseCertificateOperation::getApplicationItem,param.getApplicationItem());
        safetyEquipmentInstallUseCertificateOperationService.page(page,wrapper);
    }

    private SafetyEquipmentInstallUseCertificateOperationVO convert(SafetyEquipmentInstallUseCertificateOperation certificateOperation) {
        SafetyEquipmentInstallUseCertificateOperationVO vo = BeanUtil.copyProperties(certificateOperation, SafetyEquipmentInstallUseCertificateOperationVO.class);
        CodeUtil.searchCompanyNameAndRegionName(vo);
        return vo;
    }

    public SafetyEquipmentInstallUseCertificateOperationVO details(Long id) {
        SafetyEquipmentInstallUseCertificateOperation resVo = safetyEquipmentInstallUseCertificateOperationService.getById(id);
        return convert(resVo);
    }

    public SafetyEquipmentInstallUseCertificateOperationVO modify(UseCertOperateUpdateDTO data, Long userId) {
        SafetyEquipmentInstallUseCertificateOperation certificateOperation = BeanUtil.copyProperties(data, SafetyEquipmentInstallUseCertificateOperation.class);
        CodeUtil.searchCompanyNameAndRegionName(certificateOperation);
        if (Objects.nonNull(data.getVehicleType())){
            Optional.ofNullable(VehicleTypeEnum.getDescByCode(data.getVehicleType())).ifPresent(v ->
                    certificateOperation.setVehicleTypeName(v));
        }
        if (Objects.nonNull(data.getYearCheckStatus())){
            Optional.ofNullable(data.getYearCheckStatus()).ifPresent(y ->
                    certificateOperation.setYearCheckStatus(y));

        }
        if (Objects.nonNull(data.getReplacementStatus())){
            Optional.ofNullable(data.getReplacementStatus()).ifPresent(r ->
                    certificateOperation.setReplacementStatus(r));

        }

        certificateOperation.setUpdateBy(userId);
        safetyEquipmentInstallUseCertificateOperationService.updateById(certificateOperation);
        return BeanUtil.copyProperties(certificateOperation,SafetyEquipmentInstallUseCertificateOperationVO.class);
    }

    public Boolean remove(Long id, Long userId) {
        safetyEquipmentInstallUseCertificateOperationService.removeById(id);
        return Boolean.TRUE;
    }

    public void infoListExport(HttpServletResponse response, UseCertOperatePageParamDTO param) {
        param.page(CommonConstant.EXPORT_PAGE_NUMBER, CommonConstant.EXPORT_PAGE_SIZE);
        PageVo<SafetyEquipmentInstallUseCertificateOperationVO> page = list(param);
        Collection<SafetyEquipmentInstallUseCertificateOperationVO> collect = page.getRecords();
        String fileName = "安全设备安装使用证书列表";
        ExcelDownUtil.setFileName(fileName, response);
        // 数据导出处理函数
        try {
            EasyExcel.write(response.getOutputStream(), SafetyEquipmentInstallUseCertificateOperationVO.class)
                    .autoCloseStream(false)
                    .registerWriteHandler(ExcelExportStyle.formalStyle())
                    .sheet(fileName)
                    .doWrite(collect);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
