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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
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.page.PageFactory;
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.siteExecutive.BusinessSiteExecutiveDetail;
import com.casic.missiles.dto.business.siteExecutive.BusinessSiteExecutiveLogDetail;
import com.casic.missiles.dto.business.siteExecutive.SiteExecuteLogRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.enums.business.FilePrintTypeEnum;
import com.casic.missiles.enums.notifyevent.PrintFileDataBeanNameAliasEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.MeterFixedAssetsMapper;
import com.casic.missiles.mapper.business.BusinessSiteExecutiveInfoMapper;
import com.casic.missiles.mapper.business.BusinessSiteExecutiveLogMapper;
import com.casic.missiles.model.business.*;
import com.casic.missiles.model.equipment.EquipmentFixedAssets;
import com.casic.missiles.model.exception.enums.CoreExceptionEnum;
import com.casic.missiles.service.business.IBusinessOrderService;
import com.casic.missiles.service.business.IBusinessSiteExecutiveEquipmentRelationService;
import com.casic.missiles.service.business.IBusinessSiteExecutiveInfoService;
import com.casic.missiles.service.business.IBusinessSiteExecutiveLogService;
import com.casic.missiles.service.equipment.IEquipmentFixedAssetsService;
import com.casic.missiles.service.listeners.register.PrintFileRegister;
import com.casic.missiles.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 现场检测记录表 服务实现类
 * </p>
 *
 * @author zt
 * @since 2023-03-23
 */
@Service
@Slf4j
public class BusinessSiteExecutiveLogServiceImpl extends ServiceImpl<BusinessSiteExecutiveLogMapper, BusinessSiteExecutiveLog> implements IBusinessSiteExecutiveLogService {

    @Autowired
    private IBusinessSiteExecutiveEquipmentRelationService siteExecutiveEquipmentRelationService;
    @Autowired
    private MinioUtil minioUtill;
    @Autowired
    private IBaseExportService iBaseExportService;
    @Autowired
    private IEquipmentFixedAssetsService equipmentFixedAssetsService;
    @Autowired
    private IBusinessSiteExecutiveInfoService siteExecutiveInfoService;
    @Autowired
    private IBusinessOrderService orderService;


    @Override
    public ReturnDTO addSiteExecutiveLog(BusinessSiteExecutiveLog siteExecutiveLog) {
        initBusinessSiteExecutiveLog(siteExecutiveLog);
        if (baseMapper.insert(siteExecutiveLog) > 0) {
            //加入所用设备绑定关系
            if (ObjectUtil.isNotEmpty(siteExecutiveLog.getSiteExecutiveEquipmentRelationList()) && siteExecutiveLog.getSiteExecutiveEquipmentRelationList().size() > 0) {
                siteExecutiveEquipmentRelationService.saveBatch(siteExecutiveLog.getId(), siteExecutiveLog.getSiteExecutiveEquipmentRelationList());
            }
//            ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 30000,
//                    TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>());
//            executor.execute(() -> registerPrintFile(siteExecutiveLog));
//            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO deleteSiteExecutiveLog(Long id) {
        BusinessSiteExecutiveLog siteExecutiveLog = baseMapper.selectById(id);
        if (this.baseMapper.deleteById(id) > 0) {
            //清除监测设备绑定关系
            siteExecutiveEquipmentRelationService.deleteBySiteExecutiveLogId(id);
            deletePrintFile(siteExecutiveLog.getPrintFileName());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO updateSiteExecutiveLog(BusinessSiteExecutiveLog businessSiteExecutiveLog) {
        if (this.baseMapper.updateById(businessSiteExecutiveLog) > 0) {
            //加入所用设备绑定修改
            if (ObjectUtil.isNotEmpty(businessSiteExecutiveLog.getSiteExecutiveEquipmentRelationList()) && businessSiteExecutiveLog.getSiteExecutiveEquipmentRelationList().size() > 0) {
                siteExecutiveEquipmentRelationService.saveBatch(businessSiteExecutiveLog.getId(), businessSiteExecutiveLog.getSiteExecutiveEquipmentRelationList());
            }
//            ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 30000,
//                    TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>());
//            executor.execute(() -> {
//                deletePrintFile(businessSiteExecutiveLog.getPrintFileName());
//                registerPrintFile(businessSiteExecutiveLog);
//            });
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public BusinessSiteExecutiveLogDetail siteExecutiveLogDetail(Long id) throws Exception {
        BusinessSiteExecutiveLog businessSiteExecutiveLog = this.baseMapper.selectById(id);
        BusinessSiteExecutiveLogDetail businessSiteExecutiveLogDetail = ConvertUtils.sourceToTarget(businessSiteExecutiveLog, BusinessSiteExecutiveLogDetail.class);
        if (businessSiteExecutiveLogDetail != null) {
            BusinessSiteExecutiveInfo businessSiteExecutiveInfo = siteExecutiveInfoService.getById(businessSiteExecutiveLogDetail.getSiteExecutiveId());
            BusinessOrder businessOrder = orderService.getById(businessSiteExecutiveInfo.getOrderId());
            populateBusinessSiteExecutiveLogDetail(businessOrder, businessSiteExecutiveLogDetail);
            //查询是否有关联的监测设备
            List<BusinessSiteExecutiveEquipmentRelation> businessSiteExecutiveEquipments = siteExecutiveEquipmentRelationService.getEquipmentsByExecutiveLogId(id);
            List<EquipmentFixedAssets> equipmentFixedAssets = equipmentFixedAssetsService.list();
            Map<Long, String> equipmentFixedAssetMap = equipmentFixedAssets.stream().collect(
                    Collectors.toMap(EquipmentFixedAssets::getId, EquipmentFixedAssets::getEquipmentName)
            );
            for (BusinessSiteExecutiveEquipmentRelation siteExecutiveLog : businessSiteExecutiveEquipments) {
                siteExecutiveLog.setEquipmentName(equipmentFixedAssetMap.get(siteExecutiveLog.getEquipmentId()));
            }
            businessSiteExecutiveLogDetail.setSiteExecutiveEquipmentRelationList(businessSiteExecutiveEquipments);
        }
        return businessSiteExecutiveLogDetail;
    }

    @Override
    public Page<BusinessSiteExecutiveLog> siteExecutiveLogListPage(Page<BusinessSiteExecutiveLog> page, SiteExecuteLogRequest request) throws Exception {
        // 获取列表
        Page<BusinessSiteExecutiveLog> siteExecutiveLogListPage = this.baseMapper.siteExecutiveLogListPage(page, request);
        for (BusinessSiteExecutiveLog siteExecutiveLog : siteExecutiveLogListPage.getRecords()) {
            DictCodeUtils.convertDictCodeToName(siteExecutiveLog);
        }
        return siteExecutiveLogListPage;
    }

    @Override
    public void exportExecuteLog(SiteExecuteLogRequest request, HttpServletResponse response) {
        try {
            Page<BusinessSiteExecutiveLog> page = PageFactory.defaultPage();
            List<BusinessSiteExecutiveLog> siteExecutiveLogList = new ArrayList<>();
            if (CollectionUtils.isEmpty(request.getIds())) {
                page.setCurrent(1);
                page.setSearchCount(false);
                page.setSize(Integer.MAX_VALUE);
                // 获取列表
                Page<BusinessSiteExecutiveLog> siteExecutiveLogListPage =this.siteExecutiveLogListPage(page,request);
                siteExecutiveLogList = siteExecutiveLogListPage.getRecords();
            } else {
                setSiteExecuteLogRequestEmpty(request);
                siteExecutiveLogList = this.listByIds(request.getIds());
            }
            for (BusinessSiteExecutiveLog siteExecutiveLog : siteExecutiveLogList) {
                DictCodeUtils.convertDictCodeToName(siteExecutiveLog);
            }
            iBaseExportService.exportExcel(response, BusinessSiteExecutiveLog.class, siteExecutiveLogList, ExportEnum.ENVIRONMENTAL_RECORD.getSheetName());
        } catch (Exception e) {
            log.error("样品导出出现异常，异常信息为{}", e);
        }

    }

    private    void  setSiteExecuteLogRequestEmpty(SiteExecuteLogRequest request){
        request.setLogNo(null);
        request.setCustomerName(null);
        request.setRecorderName(null);
        request.setLaboratoryName(null);
    }

    private void populateBusinessSiteExecutiveLogDetail(BusinessOrder businessOrder, BusinessSiteExecutiveLogDetail businessSiteExecutiveLogDetail) {
        businessSiteExecutiveLogDetail.setCustomerAddress(businessOrder.getCustomerAddress());
        businessSiteExecutiveLogDetail.setCustomerName(businessOrder.getCustomerName());
        businessSiteExecutiveLogDetail.setCustomerPhone(businessOrder.getCustomerPhone());
        businessSiteExecutiveLogDetail.setDeliverer(businessOrder.getDeliverer());
        businessSiteExecutiveLogDetail.setDelivererTel(businessOrder.getDelivererTel());
        businessSiteExecutiveLogDetail.setOrderCode(businessOrder.getOrderCode());
        businessSiteExecutiveLogDetail.setCustomerNo(businessOrder.getCustomerNo());
    }


    private void initBusinessSiteExecutiveLog(BusinessSiteExecutiveLog siteExecutiveLog) {
        Long maxNo = this.baseMapper.selectMaxCode();
        String originNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.SITE_EXECUTIVE_LOG_PREFIX, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        siteExecutiveLog.setCreateUser(authUser.getId());
        siteExecutiveLog.setRecorder(authUser.getId());
        siteExecutiveLog.setRecordTime(DateUtil.formatDateTime(new Date()));
        siteExecutiveLog.setLogNo(originNo);
    }

    private void deletePrintFile(String printFileName) {
        minioUtill.removeFileName(printFileName);
    }

    /**
     * 增加，修改环境审批单需要进行
     */
//    private void registerPrintFile(BusinessSiteExecutiveLog siteExecutiveLog) {
//        //获取证书报告信息
//        siteExecutiveLog.setLaboratoryName(this.baseMapper.getLaboratoryName(siteExecutiveLog.getLaboratoryId()));
//        //进行证书报告生成，并在远程注册服务器注册
//        PrintFileRegister printFileRegister = SpringContextUtil.getBean(PrintFileRegister.class);
//        try {
//            DictCodeUtils.convertDictCodeToName(siteExecutiveLog);
//            String printFileName = printFileRegister.registerPrintFile(siteExecutiveLog, FilePrintTypeEnum.EXTERNAL_ENVIRONMENTAL_RECORD);
//            setSitePrintFileName(siteExecutiveLog.getId(), printFileName);
//        } catch (Exception ex) {
//            log.error("打印异常，证书报告信息为{},异常信息为{}", JSONObject.toJSON(siteExecutiveLog), ex);
//        }
//    }
//
//    private void setSitePrintFileName(Long id, String printFileName) {
//        //生成证书打印信息
//        BusinessSiteExecutiveLog siteExecutiveLog = new BusinessSiteExecutiveLog();
//        siteExecutiveLog.setId(id);
//        siteExecutiveLog.setPrintFileName(printFileName);
//        this.baseMapper.updateById(siteExecutiveLog);
//    }

}
