package com.artfess.cqxy.designEstimate.manager.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.artfess.base.context.BaseContext;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.bidManagement.model.BiddingPriceExamine;
import com.artfess.cqxy.designEstimate.dao.GeologicalProspectingDao;
import com.artfess.cqxy.designEstimate.dao.GeologicalProspectingDao;
import com.artfess.cqxy.designEstimate.manager.GeologicalProspectingManager;
import com.artfess.cqxy.designEstimate.manager.GeologicalProspectingManager;
import com.artfess.cqxy.designEstimate.model.GeologicalProspecting;
import com.artfess.cqxy.designEstimate.model.GeologicalProspecting;
import com.artfess.cqxy.projectManagement.enums.ProjectStatusEnum;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.search.enums.FunctionEnum;
import com.artfess.cqxy.search.manager.GlobalRetrievalManager;
import com.artfess.cqxy.search.model.GlobalRetrieval;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.universal.model.Accessory;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.poi.util.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 设计概算-地勘
 * @Author: Rong Tao
 * @Date: 2022/10/20 14:30
 */
@Service
public class GeologicalProspectingManagerImpl extends BaseManagerImpl<GeologicalProspectingDao, GeologicalProspecting> implements GeologicalProspectingManager {
    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private ProjectManagementManager pmm;

    @Autowired
    private GlobalRetrievalManager grm;

    @Override
    public boolean saveOrUpdate(GeologicalProspecting entity) {
        entity.setIsDele("0");
        boolean save = StringUtils.isEmpty(entity.getId());
        boolean savedMain = super.saveOrUpdate(entity);
        // 处理附件信息
        List<Accessory> flag = entity.getAccessoryInfo();//处理空指针
        List<Accessory> accessoryList = null == flag ? new ArrayList<>():flag;
        for (Accessory ele : accessoryList) {
            ele.setSourceId(entity.getId());
            ele.setProjectId(entity.getProjectId());
            ele.setDirectory(ProjectStatusEnum.eight.getCode());
            ele.setGroup("GeologicalProspecting");
            ele.setNode(ProjectStatusEnum.eight.getCode());
            ele.setCreateBy(baseContext.getCurrentUserId());
            ele.setCreateName(baseContext.getCurrentUserName());
            ele.setCreateTime(LocalDateTime.now());
        }
        // 先清空该ID下的所有附件信息再添加
        accessoryManager.removeBySourceId(entity.getId());
        // 如果没有附件则返回true，不进入添加
        boolean saveAcc = accessoryList.size() == 0 || accessoryManager.saveAccess(accessoryList);
        //更新项目状态
        pmm.updateStatusById(entity.getProjectId(), Integer.valueOf(ProjectStatusEnum.six.getCode()));
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return savedMain && saveAcc;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval,GeologicalProspecting entity){
        ProjectManagement projectManagement = pmm.getById(entity.getProjectId());
        globalRetrieval.setProjectId(entity.getProjectId());
        globalRetrieval.setProjectName(projectManagement.getProjectName());
        globalRetrieval.setPersonCharge(projectManagement.getProjectManager());
        globalRetrieval.setArchivesType(1);
        globalRetrieval.setBizDataId(entity.getId());
        globalRetrieval.setFunctionCode(FunctionEnum.ten.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.ten.getName());
        globalRetrieval.setBizTableName(FunctionEnum.ten.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.ten.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.ten.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.ten.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.ten.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.ten.getFunctionPath());
        globalRetrieval.setDocumentNumber(entity.getDocumentNumber());
        grm.saveOrUpdate(globalRetrieval);
    }

    @Override
    public boolean deleteByIds(List<String> ids) {
        // 同步删除检索表中的信息
        for(String ele:ids){
            grm.remove(1,ele);
        }
        return removeByIds(ids);
    }

    @Override
    public GeologicalProspecting getById(String id) {
        GeologicalProspecting result = baseMapper.getById(id);
        result.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(id));
        return result;
    }

    @Override
    public PageList<GeologicalProspecting> queryAllByPage(QueryFilter<GeologicalProspecting> queryFilter) {
        BizUtils.handleFilter(queryFilter,"bgp" ,"pm");
        IPage<GeologicalProspecting> result =
                baseMapper.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        // 附件信息处理
        List<GeologicalProspecting> records = result.getRecords();
        for (GeologicalProspecting ele: records ) {
            ele.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(ele.getId()));
        }

        return new PageList<>(result);
    }

    @Override
    public void importExcelData(MultipartFile file, String projectId) {
//        try(InputStream inputStream = file.getInputStream()) {
//            // 获取数据
//            List<GeologicalProspecting> data = ExcelImportUtil.importExcel(inputStream,GeologicalProspecting.class,new ImportParams());
//            for(GeologicalProspecting ele:data){
//                ele.setProjectId(projectId);
//                LocalDate prospectingDate = ele.getProspectingDate();
//                // 保存数据 & 同步到检索表
//                saveOrUpdate(ele);
//                handleRetrieval(new GlobalRetrieval(),ele);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        try {
            //1、获取文件输入流
            InputStream inputStream = file.getInputStream();
            //2、获取Excel工作簿对象
            Workbook workbook = WorkbookFactory.create(inputStream);
            //3、得到Excel工作表对象
            Sheet sheetAt = workbook.getSheetAt(0);
            //4、循环读取表格数据
            for (Row row : sheetAt) {
                //首行（表头）不读取
                if (row.getRowNum() == 0) {
                    continue;
                }
                //读取当前行中单元格数据并赋值到对象，索引从0开始
                GeologicalProspecting data = new GeologicalProspecting();
                //处理单元格数据可能为空 getCell将会抛出空指针的问题
                data.setDocumentNumber(null==row.getCell(1)?row.createCell(1).getStringCellValue():row.getCell(1).getStringCellValue());
                data.setGeologicalProspectingUnit(null==row.getCell(2)?row.createCell(2).getStringCellValue():row.getCell(2).getStringCellValue());

                if(null!=row.getCell(3)){
                    String dateValue = row.getCell(3).getStringCellValue();
                    data.setProspectingDate(LocalDate.parse(dateValue));
                }
                data.setConstructionScale(null==row.getCell(4)?row.createCell(4).getStringCellValue():row.getCell(4).getStringCellValue());
                data.setEstablishmentRemarks(null==row.getCell(5)?row.createCell(5).getStringCellValue():row.getCell(5).getStringCellValue());
               
                data.setProjectId(projectId);
                saveOrUpdate(data);
                // 同步到检索表
                handleRetrieval(new GlobalRetrieval(),data);
            }
            //5、关闭流
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<GeologicalProspecting> queryFilter, HttpServletResponse response) throws IOException {
        String fileName = "设计概算-地勘-导出结果";

        // 获取数据
        BizUtils.handleFilter(queryFilter, "bgp", "pm");
        List<GeologicalProspecting> data = baseMapper.queryAllByPage(
                        convert2IPage(new PageBean(0,-1,false)),
                        convert2Wrapper(queryFilter, currentModelClass())).
                getRecords();
        if(null==data||data.size()==0){
            throw new RuntimeException("没有要导出的的数据！");
        }

        // EasyPoi 导出参数、样式、表格格式设置
        ExportParams exportParams = BizUtils.getExportParams(fileName);
        fileName += ".xlsx";

        // 导出下载excel文件
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, GeologicalProspecting.class, data);
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }
}
