package com.ningdatech.carapi.industry.manage;

import java.io.IOException;
import java.util.Collections;
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.beans.BeanUtils;
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.exception.BizException;
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.datascope.contants.LambdaDataScopeTypeEnum;
import com.ningdatech.carapi.industry.entity.SafetyEquipmentInstallUseCertificate;
import com.ningdatech.carapi.industry.model.dto.SafetyEqInsUseCertExportDTO;
import com.ningdatech.carapi.industry.model.dto.UseCertPageParamDTO;
import com.ningdatech.carapi.industry.model.dto.UseCertSaveDTO;
import com.ningdatech.carapi.industry.model.dto.UseCertUpdateDTO;
import com.ningdatech.carapi.industry.model.vo.SafetyEquipmentInstallUseCertificateVO;
import com.ningdatech.carapi.industry.service.ISafetyEquipmentInstallUseCertificateService;

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

/**
 * @Classname SafetyEquipmentIntallUserCertificateManage
 * @Description
 * @Date 2022/11/3 17:57
 * @Created by PoffyZhang
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SafetyEquipmentIntallUserCertificateManage {

    private final ISafetyEquipmentInstallUseCertificateService safetyEquipmentInstallUseCertificateService;

    public PageVo<SafetyEquipmentInstallUseCertificateVO> list(UseCertPageParamDTO param) {
        Page<SafetyEquipmentInstallUseCertificate> page = param.page();
        LambdaQueryWrapper<SafetyEquipmentInstallUseCertificate> wrapper = Wrappers.lambdaQuery(SafetyEquipmentInstallUseCertificate.class);
        SafetyEquipmentIntallUserCertificateManage context = (SafetyEquipmentIntallUserCertificateManage) AopContext.currentProxy();
        context.search(page,wrapper,param);
        if(CollUtil.isEmpty(page.getRecords())){
            return PageVo.of(Collections.emptyList(), page.getTotal());
        }
        List<SafetyEquipmentInstallUseCertificateVO> data = page.getRecords().stream().map(w -> convert(w)).collect(Collectors.toList());
        return PageVo.of(data, page.getTotal());
    }

    public SafetyEquipmentInstallUseCertificateVO details(Long id) {
        LambdaQueryWrapper<SafetyEquipmentInstallUseCertificate> wrapper = Wrappers.lambdaQuery(SafetyEquipmentInstallUseCertificate.class);
        SafetyEquipmentIntallUserCertificateManage context = (SafetyEquipmentIntallUserCertificateManage) AopContext.currentProxy();
        context.buildStandardFileQuery(wrapper, id);
        SafetyEquipmentInstallUseCertificate record = safetyEquipmentInstallUseCertificateService.getOne(wrapper);
        if (Objects.isNull(record)){
            return null;
        }
        //SafetyEquipmentInstallUseCertificate record = safetyEquipmentInstallUseCertificateService.getById(id);
        return convert(record);
    }

    @LambdaDataScope(type = LambdaDataScopeTypeEnum.ALL)
    public void buildStandardFileQuery(LambdaQueryWrapper<SafetyEquipmentInstallUseCertificate> wrapper, Long id) {

    }

    /**
     * 查询
     * @param page
     * @param param
     */
    @LambdaDataScope(wrapperIndex = 1)
    @BuildChildrenRegionWrapper(wrapperIndex = 1,entityIndex = 2)
    public void search(Page<SafetyEquipmentInstallUseCertificate> page,LambdaQueryWrapper<SafetyEquipmentInstallUseCertificate> wrapper,UseCertPageParamDTO param) {
        wrapper.like(StringUtils.isNotBlank(param.getCompanyName()), SafetyEquipmentInstallUseCertificate::getCompanyName, param.getCompanyName())
                .like(StringUtils.isNotBlank(param.getCarPlate()), SafetyEquipmentInstallUseCertificate::getCarPlate, param.getCarPlate())
                .eq(Objects.nonNull(param.getVehicleType()), SafetyEquipmentInstallUseCertificate::getVehicleType, param.getVehicleType())
                .ge(Objects.nonNull(param.getStartTime()), SafetyEquipmentInstallUseCertificate::getIssueDate, param.getStartTime())
                .le(Objects.nonNull(param.getEndTime()), SafetyEquipmentInstallUseCertificate::getIssueDate, param.getEndTime())
                .like(Objects.nonNull(param.getAnnualInspectionRecords()), SafetyEquipmentInstallUseCertificate::getAnnualInspectionRecords, param.getAnnualInspectionRecords())
                .orderBy(Boolean.TRUE,Boolean.FALSE, SafetyEquipmentInstallUseCertificate::getUpdateOn);
        safetyEquipmentInstallUseCertificateService.page(page, wrapper);
    }

    private SafetyEquipmentInstallUseCertificateVO convert(SafetyEquipmentInstallUseCertificate certificate) {
        SafetyEquipmentInstallUseCertificateVO vo = BeanUtil.copyProperties(certificate, SafetyEquipmentInstallUseCertificateVO.class);
        CodeUtil.searchCompanyNameAndRegionName(vo);
        return vo;
    }


    public SafetyEquipmentInstallUseCertificateVO save(UseCertSaveDTO data, Long userId) {
        SafetyEquipmentInstallUseCertificate certificate = BeanUtil.copyProperties(data, SafetyEquipmentInstallUseCertificate.class);
        CodeUtil.searchCompanyNameAndRegionName(certificate);
        if(Objects.nonNull(data.getVehicleType())){
            Optional.ofNullable(VehicleTypeEnum.getDescByCode(data.getVehicleType())).ifPresent(v ->
                    certificate.setVehicleTypeName(v));
        }
        certificate.setCreateBy(userId);
        certificate.setUpdateBy(userId);
        safetyEquipmentInstallUseCertificateService.save(certificate);
        return BeanUtil.copyProperties(certificate, SafetyEquipmentInstallUseCertificateVO.class);
    }

    public SafetyEquipmentInstallUseCertificateVO modify(UseCertUpdateDTO data, Long userId) {
        SafetyEquipmentInstallUseCertificate certificate = BeanUtil.copyProperties(data, SafetyEquipmentInstallUseCertificate.class);
        CodeUtil.searchCompanyNameAndRegionName(certificate);
        if(Objects.nonNull(data.getVehicleType())){
            Optional.ofNullable(VehicleTypeEnum.getDescByCode(data.getVehicleType())).ifPresent(v ->
                    certificate.setVehicleTypeName(v));
        }
        certificate.setUpdateBy(userId);
        safetyEquipmentInstallUseCertificateService.updateById(certificate);
        return BeanUtil.copyProperties(certificate, SafetyEquipmentInstallUseCertificateVO.class);
    }

    public Boolean remove(Long id, Long userId) {
        LambdaQueryWrapper<SafetyEquipmentInstallUseCertificate> wrapper = Wrappers.lambdaQuery(SafetyEquipmentInstallUseCertificate.class);
        SafetyEquipmentIntallUserCertificateManage context = (SafetyEquipmentIntallUserCertificateManage) AopContext.currentProxy();
        context.buildQuery(wrapper, id);
        SafetyEquipmentInstallUseCertificate record = safetyEquipmentInstallUseCertificateService.getOne(wrapper);
        if (Objects.isNull(record)){
            throw new BizException("无法删除!");
        }
        safetyEquipmentInstallUseCertificateService.removeById(id);
        return Boolean.TRUE;
    }
    @LambdaDataScope(type = LambdaDataScopeTypeEnum.ALL)
    public void buildQuery(LambdaQueryWrapper<SafetyEquipmentInstallUseCertificate> wrapper, Long id) {
        wrapper.eq(SafetyEquipmentInstallUseCertificate::getId,id);
    }

    public void infoListExport(HttpServletResponse response, UseCertPageParamDTO param) {
        param.page(CommonConstant.EXPORT_PAGE_NUMBER, CommonConstant.EXPORT_PAGE_SIZE);
        PageVo<SafetyEquipmentInstallUseCertificateVO> page = list(param);
        List<SafetyEqInsUseCertExportDTO> collect = page.getRecords().stream().map(r -> {
            SafetyEqInsUseCertExportDTO certExportDTO = new SafetyEqInsUseCertExportDTO();
            BeanUtils.copyProperties(r, certExportDTO);
            return certExportDTO;
        }).collect(Collectors.toList());
        String fileName = "安全设备安装使用证书信息列表";
        ExcelDownUtil.setFileName(fileName, response);
        // 数据导出处理函数
        try {
            EasyExcel.write(response.getOutputStream(), SafetyEqInsUseCertExportDTO.class)
                    .autoCloseStream(false)
                    .registerWriteHandler(ExcelExportStyle.formalStyle())
                    .sheet(fileName)
                    .doWrite(collect);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
