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

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.*;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.contract.dao.ItemDao;
import com.artfess.cqxy.contract.manager.ContractManager;
import com.artfess.cqxy.contract.manager.ItemManager;
import com.artfess.cqxy.contract.model.Item;
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.utils.BizUtils;
import com.artfess.poi.util.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黎沐华
 * @date 2022/2/26 11:01
 */
@Service
public class ItemManagerImpl extends BaseManagerImpl<ItemDao, Item> implements ItemManager {

    @Autowired
    ContractManager cm;

    @Autowired
    private GlobalRetrievalManager grm;

    @Override
    public boolean saveOrUpdate(Item entity) {
        boolean save = StringUtils.isEmpty(entity.getId());
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return save ? save(entity) : updateById(entity);
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval, Item entity){
        globalRetrieval.setArchivesType(1);
        globalRetrieval.setBizDataId(entity.getId());
        globalRetrieval.setFunctionCode(FunctionEnum.fivteen.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.fivteen.getName());
        globalRetrieval.setBizTableName(FunctionEnum.fivteen.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.fivteen.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.fivteen.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.fivteen.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.fivteen.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.fivteen.getFunctionPath());
        globalRetrieval.setName(entity.getName());
        globalRetrieval.setSearchTitle(entity.getName()+"_"+entity.getCode()+"_"+
                entity.getSubjectCode()+"_"+entity.getSubjectName()+"_"+entity.getRemarks());
        grm.saveOrUpdate(globalRetrieval);
    }

    @Override
    public PageList<Item> queryAllByPage(QueryFilter<Item> queryFilter) {
        // 限制合同ID不能为空
        String contractId = null;
        List<QueryField> test = queryFilter.getQuerys();
        for (QueryField ele : test){
            if("CONTRACT_ID_".equals(ele.getProperty())) {
                contractId = String.valueOf(ele.getValue());
                break;
            }
        }
        Assert.notNull(contractId,"合同ID不能为空");

        IPage<Item> result =
                baseMapper.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }



    @Override
    public void importExcelData(MultipartFile file, String contractId) {
        Assert.notNull(contractId,"合同ID不能为空");
        List<Item> data = readExcelData(file);
        for(Item ele:data){
            ele.setContractId_(contractId);
            baseMapper.insert(ele);
            // 同步到检索表
            handleRetrieval(new GlobalRetrieval(),ele);
        }
    }

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

    @Override
    public List<Item> readExcelData(MultipartFile file) {
        List<Item> result = new ArrayList<>();
        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开始
                Item data = new Item();
                //处理单元格数据可能为空 getCell将会抛出空指针的问题
                data.setSort_(null==row.getCell(0)?(int)row.createCell(0).getNumericCellValue():(int)row.getCell(0).getNumericCellValue());
                data.setCode_(null==row.getCell(1)?row.createCell(1).getStringCellValue():row.getCell(1).getStringCellValue());
                data.setName_(null==row.getCell(2)?row.createCell(2).getStringCellValue():row.getCell(2).getStringCellValue());
                data.setSubjectCode_(null==row.getCell(3)?row.createCell(3).getStringCellValue():row.getCell(3).getStringCellValue());
                data.setSubjectName_(null==row.getCell(4)?row.createCell(4).getStringCellValue():row.getCell(4).getStringCellValue());
                data.setSpec_(null==row.getCell(5)?row.createCell(5).getStringCellValue():row.getCell(5).getStringCellValue());
                data.setPrice_(null==row.getCell(6)?row.createCell(6).getNumericCellValue():row.getCell(6).getNumericCellValue());
                data.setAmount_((int)(null==row.getCell(7)?row.createCell(7).getNumericCellValue():row.getCell(7).getNumericCellValue()));
                data.setMonty_(null==row.getCell(8)?row.createCell(8).getNumericCellValue():row.getCell(8).getNumericCellValue());
                data.setRemarks_(null==row.getCell(9)?row.createCell(9).getStringCellValue():row.getCell(9).getStringCellValue());
                result.add(data);
            }
            //5、关闭流
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void exportDatatoExcel(QueryFilter<Item> queryFilter, HttpServletResponse response) throws IOException {
        String fileName = "合同详细信息-导出结果";

        // 获取数据
        queryFilter.addFilter("IS_DELE_","0", QueryOP.EQUAL);
        List<Item> 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, Item.class, data);
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

}
