package com.artfess.cqxy.constructionPermit.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.BiddingPriceLimit;
import com.artfess.cqxy.constructionPermit.dao.ConstructionPermitDao;
import com.artfess.cqxy.constructionPermit.manager.ConstructionPermitManager;
import com.artfess.cqxy.constructionPermit.model.ConstructionPermit;
import com.artfess.cqxy.projectApproval.model.DecisionAnnualPlan;
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.conditions.update.UpdateWrapper;
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.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 五方责任主体对象(原施工许可表)(BizConstructionPermit)表服务实现类
 * @author 黎沐华
 * @since 2022-02-23 10:24:55
 */
@Service
public class ConstructionPermitManagerImpl extends BaseManagerImpl<ConstructionPermitDao, ConstructionPermit> implements ConstructionPermitManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private ProjectManagementManager pmm;

    @Autowired
    private GlobalRetrievalManager grm;

    @Override
    public boolean saveOrUpdate(ConstructionPermit entity) {
        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.ten.getCode());
            ele.setGroup("ConstructionPermit");
            ele.setNode(ProjectStatusEnum.ten.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.ten.getCode()));
        //更新项目项目建设地址
        ProjectManagement projectManagement = pmm.get(entity.getProjectId());
        if(null != projectManagement ){
            if(org.apache.commons.lang3.StringUtils.isNotBlank(entity.getProposedLocation())){
                projectManagement.setProjectAddress(entity.getProposedLocation());
            }
            if(org.apache.commons.lang3.StringUtils.isNotBlank(entity.getProposedLandArea())){
                projectManagement.setProjectContent(entity.getProposedLandArea());
            }
            pmm.updateById(projectManagement);
        }
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return savedMain && saveAcc;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval, ConstructionPermit 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.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.setDocumentNumber(entity.getCode());
        globalRetrieval.setName(entity.getName());
        globalRetrieval.setDocumentUnit(entity.getEstablishmentApprovalUnit());
        globalRetrieval.setSearchTitle(entity.getName()+"_"+entity.getCode()+"_"+entity.getEstablishmentApprovalUnit()+"_"+
                entity.getProposedLocation()+"_"+entity.getSupervisorUnit()+"_"+entity.getDesignUnit()+"_"+
                entity.getConstructionUnit()+"_"+entity.getSurveyUnit()+"_"+entity.getEstablishmentRemarks());
        grm.saveOrUpdate(globalRetrieval);
    }

    @Override
    public ConstructionPermit getById(String id) {
        return baseMapper.getById(id);
    }

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

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



    @Override
    public void importExcelData(MultipartFile file, String projectId) {
        Assert.notNull(projectId,"项目ID不能为空");
        try(InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<ConstructionPermit> data = ExcelImportUtil.importExcel(inputStream,ConstructionPermit.class,new ImportParams());
            for(ConstructionPermit ele:data){
                ele.setProjectId(projectId);
                // 保存数据 & 同步到检索表
                save(ele);
                handleRetrieval(new GlobalRetrieval(),ele);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<ConstructionPermit> queryFilter, HttpServletResponse response) throws IOException {
        String fileName = "五方责任主体-导出结果";
        // 获取数据
        BizUtils.handleFilter(queryFilter, "bcp", "pm");
        List<ConstructionPermit> 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, ConstructionPermit.class, data);
        Sheet sheet = workbook.getSheetAt(0);
        for(int i = 2;i<=17;i++){
            sheet.setColumnWidth(i,4500);
        }
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

    @Override
    public void updateProjectIdByProiectId(String oldProjectIds, String newProjectId) {
        UpdateWrapper<ConstructionPermit> wrapper = new UpdateWrapper<ConstructionPermit>()
                .set(org.apache.commons.lang3.StringUtils.isNotBlank(newProjectId), "PROJECT_ID_", newProjectId)
                .in("PROJECT_ID_", Arrays.asList(oldProjectIds.split(",")));
        this.update(wrapper);
    }

}

