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

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.originRecord.OriginRecordRequest;
import com.casic.missiles.dto.business.originRecord.OriginRecordResponse;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessOriginalRecordMapper;
import com.casic.missiles.model.business.BusinessOriginalRecord;
import com.casic.missiles.model.customer.CustomerSampleInfo;
import com.casic.missiles.model.system.SystemTemplate;
import com.casic.missiles.service.business.*;
import com.casic.missiles.service.customer.CustomerSampleService;
import com.casic.missiles.service.system.ISystemTemplateService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2023-02-02
 */
@Service
public class BusinessOriginalRecordServiceImpl extends ServiceImpl<BusinessOriginalRecordMapper, BusinessOriginalRecord> implements IBusinessOriginalRecordService {


    @Resource
    private CustomerSampleService customerSampleService;
    @Resource
    private IBusinessEnvironmentRecordService businessEnvironmentRecordService;
    @Resource
    private IBusinessOrderService businessOrderService;
    @Resource
    private IBusinessOriginalRecordFileRelationService originalRecordFileRelationService;
    @Resource
    private IBusinessOriginalRecordEquipmentRelationService originalRecordEquipmentRelationService;
    @Resource
    private IBaseExportService iBaseExportService;
    @Resource
    private ISystemTemplateService templateService;


    @Override
    public Page<BusinessOriginalRecord> originListPage(Page<BusinessOriginalRecord> page, OriginRecordRequest request) throws Exception {
        // 获取列表
        Page<BusinessOriginalRecord> originalRecordPage = this.baseMapper.originListPage(page, request);
        if (!CollectionUtils.isEmpty(originalRecordPage.getRecords())) {
            for (BusinessOriginalRecord record : originalRecordPage.getRecords()) {
                DictCodeUtils.convertDictCodeToName(record);
                if (!StrUtil.isBlankIfStr(record.getSampleId())) {
                    record.setCustomerSampleInfo(customerSampleService.sampleDetail(record.getSampleId()));
                }
            }
        }
        return originalRecordPage;
    }

    @Override
    public Page<CustomerSampleInfo> samplesByOderId(Page<CustomerSampleInfo> sampleInfoPage, OriginRecordRequest request) {
        return customerSampleService.samplesByOderId(sampleInfoPage, request.getId(), request.getSampleNo(), request.getSampleName());
    }

    @Override
    public BusinessOriginalRecord originalDetail(Long id) throws Exception {
        BusinessOriginalRecord businessOriginalRecord = this.baseMapper.selectById(id);
        if (businessOriginalRecord != null) {
            //查询样品详情
            if (businessOriginalRecord.getSampleId() != null) {
                businessOriginalRecord.setCustomerSampleInfo(customerSampleService.sampleDetail(businessOriginalRecord.getSampleId()));
            }
            //查询环境记录单详情
            if (businessOriginalRecord.getEnvironmentId() != null) {
                businessOriginalRecord.setBusinessEnvironmentRecord(businessEnvironmentRecordService.environmentDetail(businessOriginalRecord.getEnvironmentId()));
            }
            //查询委托单详情
            if (businessOriginalRecord.getOrderId() != null) {
                businessOriginalRecord.setBusinessOrder(businessOrderService.orderDetail(businessOriginalRecord.getOrderId()));
            }

            //查询是否有关联的计量文件
            businessOriginalRecord.setFileList(originalRecordFileRelationService.getFilesByOriginalRecordId(id));
            //查询是否有关联的监测设备
            businessOriginalRecord.setEquipmentInfoList(originalRecordEquipmentRelationService.getEquipmentsByOriginalRecordId(id));

            //字典值转换
            DictCodeUtils.convertDictCodeToName(businessOriginalRecord);

            //显示模板名称
            if (null != businessOriginalRecord.getTemplateId()) {
                SystemTemplate systemTemplate = templateService.getById(businessOriginalRecord.getTemplateId());
                if (systemTemplate != null) {
                    businessOriginalRecord.setTemplateName(systemTemplate.getTemplateName());
                }
            }
        }
        return businessOriginalRecord;
    }

    @Transactional
    @Override
    public ReturnDTO deleteOriginal(Long id) {
        if (this.baseMapper.deleteById(id) > 0) {
            //删除计量文件绑定关系
            originalRecordFileRelationService.deleteByOriginId(id);
            //删除监测设备绑定关系
            originalRecordEquipmentRelationService.deleteByOriginId(id);
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO updateOriginal(BusinessOriginalRecord businessOriginalRecord) {
        if (this.baseMapper.updateById(businessOriginalRecord) > 0) {
            //加入技术文件绑定
            if (ObjectUtil.isNotEmpty(businessOriginalRecord.getFileList()) && businessOriginalRecord.getFileList().size() > 0) {
                originalRecordFileRelationService.saveBatch(businessOriginalRecord.getId(), businessOriginalRecord.getFileList());
            }
            //加入所用设备绑定
            if (ObjectUtil.isNotEmpty(businessOriginalRecord.getEquipmentInfoList()) && businessOriginalRecord.getEquipmentInfoList().size() > 0) {
                originalRecordEquipmentRelationService.saveBatch(businessOriginalRecord.getId(), businessOriginalRecord.getEquipmentInfoList());
            }
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * @param businessOriginalRecord
     * @return
     */
    @Override
    @Transactional
    public ReturnDTO addOriginal(BusinessOriginalRecord businessOriginalRecord) {
        initBusinessEnvironmentRecord(businessOriginalRecord);
        if (baseMapper.insert(businessOriginalRecord) > 0) {
            //加入技术文件绑定
            if (ObjectUtil.isNotEmpty(businessOriginalRecord.getFileList()) && businessOriginalRecord.getFileList().size() > 0) {
                originalRecordFileRelationService.saveBatch(businessOriginalRecord.getId(), businessOriginalRecord.getFileList());
            }
            //加入所用设备绑定
            if (ObjectUtil.isNotEmpty(businessOriginalRecord.getEquipmentInfoList()) && businessOriginalRecord.getEquipmentInfoList().size() > 0) {
                originalRecordEquipmentRelationService.saveBatch(businessOriginalRecord.getId(), businessOriginalRecord.getEquipmentInfoList());
            }
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public void originExport(OriginRecordRequest request, HttpServletResponse response) {
        try {
            List<OriginRecordResponse> originExportList = this.baseMapper.originExportList(request);
            for (OriginRecordResponse originRecordResponse : originExportList) {
                //字典值转换
                DictCodeUtils.convertDictCodeToName(originRecordResponse);
            }
            iBaseExportService.exportExcel(response, OriginRecordResponse.class, originExportList, ExportEnum.ORIGIN_DATA.getSheetName());
        } catch (Exception e) {
            log.error("环境记录单导出出现异常，异常信息为{}", e);
        }
    }

    private void initBusinessEnvironmentRecord(BusinessOriginalRecord businessOriginalRecord) {
        Long maxNo = this.baseMapper.selectMaxCode();
        String originNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.ORIGIN_PREFIX, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        businessOriginalRecord.setCreateUser(authUser.getId());
        businessOriginalRecord.setOriginalRecordCode(originNo);
    }

}
