package com.nantian.cloud.jljc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.entity.EnterpriseInfo;
import com.nantian.cloud.jljc.entity.TSuperviseTask;
import com.nantian.cloud.jljc.mapper.DictRegionMapper;
import com.nantian.cloud.jljc.mapper.TSuperviseTaskMapper;
import com.nantian.cloud.jljc.service.TSuperviseTaskService;
import com.nantian.cloud.jljc.vo.Query;
import com.nantian.cloud.jljc.vo.SuperviseHistoryColumns;
import com.nantian.cloud.jljc.vo.TSuperviseTaskOrganizationVo;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.data.datascope.DataScope;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.netty.util.internal.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;


/**
 * 节能监察任务表 服务实现类
 * @author stz
 * @since 2020-09-21
 */
@Service("tSuperviseTaskService")
public class TSuperviseTaskServiceImpl extends ServiceImpl<TSuperviseTaskMapper, TSuperviseTask> implements TSuperviseTaskService {
    private static final String EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";
    @Autowired
    private EnterpriseInfoServiceImpl enterpriseInfoService;

    @Autowired
    DictRegionMapper dictRegionMapper;

    @Override
    public IPage<EnterpriseInfo> getPageCom(Page page, Query map) {
        if(StringUtils.isNotEmpty(map.getPArea())){
            map.setArea(map.getPArea().replaceAll("0000","").replaceAll("00",""));
        }else if (StringUtils.isNotEmpty(map.getArea())) {
            map.setArea(map.getArea().replaceAll("0000","").replaceAll("00",""));
        }
        //return baseMapper.getPageCom(page,map,new DataScope());
        return baseMapper.getPageCom(page,map,new DataScope());
    }

    @Override
    public IPage<TSuperviseTaskOrganizationVo> getPageScope(Page page, Query query) {
        if(StringUtils.isNotEmpty(query.getPArea())){
            query.setArea(query.getPArea().replaceAll("0000","").replaceAll("00",""));
        }else if (StringUtils.isNotEmpty(query.getArea())) {
            query.setArea(query.getArea().replaceAll("0000","").replaceAll("00",""));
        }
        return baseMapper.getPageScope(page,query,new DataScope());
        //return baseMapper.getPageScope(page,query);
    }

    @Override
    public List<TSuperviseTask> haveTaskRelease(String epc) {
        return baseMapper.haveTaskRelease(epc);
    }

    @Override
    public TSuperviseTaskOrganizationVo getTaskById(Long id) {
        return baseMapper.getTaskById(id);
    }

    @Override
    public int updateTask(TSuperviseTask task) {
        return baseMapper.updateTask(task);
    }

    @Override
    public IPage<TSuperviseTaskOrganizationVo> getTSuperviseTask(Page page, Query query) {
        return baseMapper.getTSuperviseTask(page,query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary1(Query query) {
        return baseMapper.getSuperviseTaskSummary1(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary2(Query query) {
        return baseMapper.getSuperviseTaskSummary2(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary3(Query query) {
        return baseMapper.getSuperviseTaskSummary3(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary4_1(Query query) {
        return baseMapper.getSuperviseTaskSummary4_1(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary4_2(Query query) {
        return baseMapper.getSuperviseTaskSummary4_2(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary5(Query query) {
        return baseMapper.getSuperviseTaskSummary5(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary6(Query query) {
        return baseMapper.getSuperviseTaskSummary6(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary7(Query query) {
        return baseMapper.getSuperviseTaskSummary7(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary8(Query query) {
        return baseMapper.getSuperviseTaskSummary8(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary9(Query query) {
        return baseMapper.getSuperviseTaskSummary9(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary10_1(Query query) {
        return baseMapper.getSuperviseTaskSummary10_1(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary10_2(Query query) {
        return baseMapper.getSuperviseTaskSummary10_2(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary10_3(Query query) {
        return baseMapper.getSuperviseTaskSummary10_3(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary10_4(Query query) {
        return baseMapper.getSuperviseTaskSummary10_4(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary10_5(Query query) {
        return baseMapper.getSuperviseTaskSummary10_5(query);
    }

    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary10_6(Query query) {
        return baseMapper.getSuperviseTaskSummary10_6(query);
    }


    @Override
    public List<Map<String, Object>> getSuperviseTaskSummary11(Query query) {
        return baseMapper.getSuperviseTaskSummary11(query);
    }

    @Override
    public Map<String, Object> totalByTask(Query query) {
        if (query.getArea().contains("0000")) { //省
            query.setArea(StrUtil.subWithLength(query.getArea(), 0, 2));
        } else if (query.getArea().contains("00")) {  //州市
            query.setArea(StrUtil.subWithLength(query.getArea(), 0, 4));
        }
        return baseMapper.totalByTask(query);
    }

    @Override
    public Map<String, Object> taskInfo(TSuperviseTask query) {
        return baseMapper.taskInfo(query);
    }


    @Override
    public IPage<Map<String, Object>> pageByWX(Page page, Query query) {
        return baseMapper.pageByWX(page,query);
    }

    @Override
    public List<Map<String, Object>> noticeListByJnjc(Query query, String deptId, String inspectorsid) {
        return baseMapper.noticeListByJnjc(query, deptId, inspectorsid);
    }

    @Override
    public List<Map<String, Object>> jnjcSummary(Query query) {
        return baseMapper.jnjcSummary(query);
    }

    @Override
    public List<Map<String, Object>> jnjcPersonal(Query query) {
        return baseMapper.jnjcPersonal(query);
    }


    @Override
    public R excelImport(MultipartFile file) throws FileFormatException {
        if (file == null) {
            //throw new FileFormatException("");
            return R.failed("导入失败，传入文件不存在！");
        }

        //获取原文件
        String originalFileName = file.getOriginalFilename();

        //判断传入文件格式
        if (!(originalFileName.endsWith(EXTENSION_XLS) || originalFileName.endsWith(EXTENSION_XLSX))) {
            throw new FileFormatException("传入文件不是excel格式!");
        }
        Workbook workbook = null;
        try {
            if (originalFileName.endsWith(EXTENSION_XLS)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFileName.endsWith(EXTENSION_XLSX)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }

            //读文件
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(numSheet);
                if (sheet == null) {
                    continue;
                }
                int firstRowIndex = sheet.getFirstRowNum();
                int lastRowIndex = sheet.getLastRowNum();
                //读取首行（表头）
                Row firstRow = sheet.getRow(firstRowIndex);
                if(firstRow == null){
                    continue;
                }
                for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
                    System.err.println(i + " "+firstRow.getLastCellNum());
                    Cell cell = firstRow.getCell(i);
                    String cellValue = this.getCellValue(cell, true);
                    System.err.println("表头数据：" + cellValue + "\t");
                }

                System.err.println("开始导入数据...");
                List<TSuperviseTask> list = new ArrayList<>();
                for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);
                    int firstColumnIndex = currentRow.getFirstCellNum(); //首列
                    int lastColumnIndex = currentRow.getLastCellNum(); //尾列
                    boolean s = false;
                    TSuperviseTask tSuperviseTask = new TSuperviseTask();
                    ScUser u = SecurityUtils.getUser();
                    for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
                        Cell currentCell = currentRow.getCell(columnIndex);
                        String currentCellValue = this.getCellValue(currentCell, true);
                        System.err.println(firstColumnIndex+" "+columnIndex+" " + currentCellValue + "\t");
                        if (columnIndex == firstColumnIndex ) {
                            if (currentCellValue == "") {
                                return R.failed("第"+rowIndex+"行的监察编号为空，请输入监察编号");
                            }else {
                                if (this.isExistMonitorId(currentCellValue) >= 1) {
                                    return R.failed("第" + rowIndex + "行监察编号为" + currentCellValue + "的数据重复，请重新输入监察编号");
                                } else {
                                    tSuperviseTask.setMonitorId(currentCellValue);
                                }
                            }
                        }
                        if (columnIndex == firstColumnIndex + 1){
                            if(currentCellValue == ""){
                                return R.failed("第"+rowIndex+"行的企业名称为空，请输入企业名称");
                            }else {
                                String epcName = currentCellValue;
                                EnterpriseInfo enterpriseInfo = enterpriseInfoService.getOne(new QueryWrapper<>(new EnterpriseInfo()).eq("cmp_name", epcName));
                                if (enterpriseInfo != null){
                                    tSuperviseTask.setMonitoredEnt(enterpriseInfo.getCmpName());
                                    tSuperviseTask.setEpc(enterpriseInfo.getEnterpriseCode());
                                    tSuperviseTask.setLocate(enterpriseInfo.getRegionCode());
                                    //tSuperviseTask.setIndustry(enterpriseInfo.getIndustryCode());
                                    tSuperviseTask.setAddress(enterpriseInfo.getAddress());
                                }else{
                                    tSuperviseTask.setMonitoredEnt(currentCellValue);
                                }
                            }
                        }
                        if (columnIndex == firstColumnIndex + 2) {
                            if (currentCellValue.isEmpty() && tSuperviseTask.getEpc().isEmpty()){
                                return R.failed("第" + rowIndex + "行社会信用代码不能为空");
                            }else if (tSuperviseTask.getEpc() == null){
                                tSuperviseTask.setEpc(currentCellValue);
                            }
                        }
                        if (columnIndex == firstColumnIndex + 3) {
                            tSuperviseTask.setTaskHandle(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4) {
                            tSuperviseTask.setTaskTransmit(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5) {
                            tSuperviseTask.setSource(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6){
                            if (StringUtils.isEmpty(tSuperviseTask.getLocate())){
                                if (StringUtils.isEmpty(currentCellValue)){
                                    return R.failed("第" + rowIndex + "行所属地区名称不能为空！");
                                }else {
                                    String region = dictRegionMapper.selectLRegion(currentCellValue);
                                    if (StringUtils.isEmpty(region)){
                                        tSuperviseTask.setLocate(u.getDeptId().toString());
                                    }else {
                                        tSuperviseTask.setLocate(region);
                                    }
                                }
                            }
                        }
                        if (columnIndex == firstColumnIndex + 8) {
                            tSuperviseTask.setType(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 9) {
                            tSuperviseTask.setGroupLeader(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 10) {
                            tSuperviseTask.setInspectors(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 11 && StringUtils.isEmpty(tSuperviseTask.getAddress())) {
                            tSuperviseTask.setAddress(currentCellValue);
                        }
                    }
                    tSuperviseTask.setUserid(u.getId());
                    tSuperviseTask.setDeptId(u.getDeptId());
                    tSuperviseTask.setUpdateTime(new Date());
                    tSuperviseTask.setTaskState("1");
                    tSuperviseTask.setDelFlag("1");
                    list.add(tSuperviseTask);
                }
                this.saveBatch(list);
            }
            return R.ok("导入成功");
        } catch (Exception e) {
            System.err.println(e.toString());
            e.printStackTrace();
            return R.failed("导入失败！" + e.getMessage());
        } finally {
            if (workbook != null) {
                try {
                    file.getInputStream().close();
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String getCellValue(Cell cell, boolean b) {
        if (cell == null) {
            return "";
        }
        if (b) {
            //虽然excel中设置的都是文本，但是数字文本还被读错，如“1”取成“1.0”,加上下面这句，临时把它当做文本来读取
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return String.valueOf(cell.getStringCellValue());
        }
    }
    @Override
    public Integer isExistMonitorId(String monitorId){
        return baseMapper.isExistMonitorId(monitorId);
    }

    @Override
    public Map<String, Object> getHistoryData(Query query) {
        Map<String, Object> data = new HashMap<>();
        query.setYear(query.getYear()+1);
        List<Map<String, Object>> historyData = baseMapper.getHistoryData(query);
        String historyColumns = baseMapper.getHistoryColumns(query.getItem());
        List<SuperviseHistoryColumns> columnsList = new ArrayList<>();
        if(StringUtils.isNotEmpty(historyColumns)){
            columnsList = JSONArray.parseArray(historyColumns,SuperviseHistoryColumns.class);
        }
        data.put("type","2"); //历史数据
        data.put("data",historyData);
        data.put("columnsList",columnsList);
        data.put("columns",historyColumns);
        return data;
    }
}
