package com.siwei.rsmonitoring.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.siwei.common.core.constant.SecurityConstants;
import com.siwei.common.core.domain.R;
import com.siwei.common.core.exception.ServiceException;
import com.siwei.common.core.utils.DateUtils;
import com.siwei.common.core.utils.StringUtils;
import com.siwei.common.core.utils.file.FileTypeUtils;
import com.siwei.common.core.utils.file.FileUtils;
import com.siwei.common.core.utils.file.UnPackageUtils;
import com.siwei.common.core.utils.uuid.IdUtils;
import com.siwei.common.security.utils.SecurityUtils;
import com.siwei.rsmonitoring.domain.*;
import com.siwei.rsmonitoring.mapper.TDkGeomDbDetailsMapper;
import com.siwei.rsmonitoring.mapper.TDkGeomDbMapper;
import com.siwei.rsmonitoring.service.*;
import com.siwei.spatial.api.RemoteSpatialFilesDbService;
import com.siwei.spatial.api.domain.file.TGeomDb;
import com.siwei.spatial.api.domain.file.TGeomDbDetails;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class TDkGeomDbServiceImpl implements ITDkGeomDbService {
    private static final Logger log = LoggerFactory.getLogger(TDkGeomDbServiceImpl.class);
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;
    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    @Autowired
    private RemoteSpatialFilesDbService remoteSpatialFilesDbService;
    @Autowired
    private TDkGeomDbMapper tDkGeomDbMapper;
    @Autowired
    private TDkGeomDbDetailsMapper tDkGeomDbDetailsMapper;
    @Autowired
    private ITDkjbxxService itDkjbxxService;
    @Autowired
    private ITDkjbxxYwypService iTDkjbxxYwypService;
    @Autowired
    private ITDkAuditflowTypeService itDkAuditflowTypeService;
    @Autowired
    private ITDkYwypXlsxDetailsService itDkYwypXlsxDetailsService;
    @Autowired
    private ITDkGeomDbDetailsService itDkGeomDbDetailsService;
    @Autowired
    private ITDkYwypHgxService itDkYwypHgxService;

    @Override
    public List<TDkGeomDb> selectTDkGeomDbList(TDkGeomDb tGeomDb) {
        return tDkGeomDbMapper.selectTDkGeomDbList(tGeomDb);
    }

    public int insertTDkGeomDbYWYP(List<TGeomDbDetails> dbDetails, TDkGeomDb tDkGeomDb, String sheet_name, String tif_path) {
        String dbDetailJson = null;
        Long successNumber = 0L;
        Long fullNumber = 0L;
        Long len_number = 0L;

        TDkYwypHgx yjjbnt_hgx = itDkYwypHgxService.selectTDkYwypHgxByDkType("YJJBNT");
        TDkYwypHgx gd_hgx = itDkYwypHgxService.selectTDkYwypHgxByDkType("GD");

        for (TGeomDbDetails dbDetail : dbDetails) {
            dbDetailJson = dbDetail.getGeomJson();
            if (StringUtils.isEmpty(dbDetailJson)) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("读取shp数据缺失属性");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }
//            swid(swid) *
//            合法性 *
//            合法性1 *
//            面积 (压占面积总和(亩)) *
//            面积集 (压占面积(亩)) *
//            编号集 (压占数据编号) *
            //* 标注为必须字段,不可为空。其他为选配字段 如果还有其他字段，将统一放入到JSON字段中
            JSONObject jsonObject = JSON.parseObject(dbDetailJson);
            //获取属性字段，并将字段进行赋值。获取成功的将删除该KEY
            String jcbh = jsonObject.getString("swid");
            String hfx = jsonObject.getString("合法性");
            String hfx1 = jsonObject.getString("合法性1");
            String mj = jsonObject.getString("面积");
            String mjj = jsonObject.getString("面积集");
            String bhj = jsonObject.getString("编号集");
            if (StringUtils.isEmpty(jcbh) || StringUtils.isEmpty(hfx) || StringUtils.isEmpty(hfx1) || StringUtils.isEmpty(mj) || StringUtils.isEmpty(mjj) || StringUtils.isEmpty(bhj)) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("shp属性字段缺失");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }
            //删除KEY
            jsonObject.remove("swid");
            jsonObject.remove("合法性");
            jsonObject.remove("合法性1");
            jsonObject.remove("面积");
            jsonObject.remove("面积集");
            jsonObject.remove("编号集");
            //获取属性字段，并将字段进行赋值。获取成功的将删除该KEY
            String xzqdm = jsonObject.getString("xzqdm");
            String xzqmc = jsonObject.getString("xzqmc");
            BigDecimal jcmj = jsonObject.getBigDecimal("jcmj");
            String qlx = jsonObject.getString("qlx");
            String hlx = jsonObject.getString("hlx");
            String lzb = jsonObject.getString("lzb");
            String bzb = jsonObject.getString("bzb");
            String qsx = jsonObject.getString("qsx");
            String hsx = jsonObject.getString("hsx");
            //删除KEY
            jsonObject.remove("xzqdm");
            jsonObject.remove("xzqmc");
            jsonObject.remove("jcmj");
            jsonObject.remove("qlx");
            jsonObject.remove("hlx");
            jsonObject.remove("lzb");
            jsonObject.remove("bzb");
            jsonObject.remove("qsx");
            jsonObject.remove("hsx");
            //校验dkbh是否重复，且数据是否进入核查流程状态
            boolean checkUpdateBoolean = iTDkjbxxYwypService.checkDkjbxxYwypUpdate(jcbh);
            TDkGeomDbDetails dkGeomDbDetails = new TDkGeomDbDetails();
            dkGeomDbDetails.setId(IdUtils.fastSimpleUUID());
            dkGeomDbDetails.setGeom(dbDetail.getGeom());
            dkGeomDbDetails.setGeomArea(dbDetail.getGeomArea());
            dkGeomDbDetails.setXzqdm(xzqdm);
            dkGeomDbDetails.setXzqmc(xzqmc);
            dkGeomDbDetails.setDkbh(jcbh);
            dkGeomDbDetails.setDkmj(jcmj.toString());
            dkGeomDbDetails.setQlx(qlx);
            dkGeomDbDetails.setHlx(hlx);
            dkGeomDbDetails.setLzb(lzb);
            dkGeomDbDetails.setBzb(bzb);
            dkGeomDbDetails.setQsx(qsx);
            dkGeomDbDetails.setHsx(hsx);
            dkGeomDbDetails.setUploadId(tDkGeomDb.getId());
            if (checkUpdateBoolean) {
                successNumber++;
                dkGeomDbDetails.setCheckUpdate("0");
            } else {
                fullNumber++;
                dkGeomDbDetails.setCheckUpdate("1");
            }
            dkGeomDbDetails.setShpJson(jsonObject.toJSONString());
            dkGeomDbDetails.setHfx(hfx);
            dkGeomDbDetails.setHfx1(hfx1);
            dkGeomDbDetails.setMj(mj);
            dkGeomDbDetails.setMjj(mjj);
            dkGeomDbDetails.setBhj(bhj);
            String[] sheet_name_str = sheet_name.split(";", -1);
            String[] hfx1_str = hfx1.split(";", -1);
            String[] mj_str = mj.split(";", -1);
            String[] mjj_str = mjj.split(";", -1);
            String[] bhj_str = bhj.split(";", -1);
            List<HashMap<String, String>> sheet_json = new ArrayList<>();
            for (int vi = 0; vi < sheet_name_str.length; vi++) {
                HashMap<String, String> mapvi = new HashMap<>();
                if (StringUtils.isEmpty(mj_str[vi])) {
                    continue;
                }
                mapvi.put("type", sheet_name_str[vi]);
                mapvi.put("yzmj", mj_str[vi]);
                mapvi.put("hfx", hfx1_str[vi]);
                mapvi.put("photo", domain + localFilePrefix + tif_path + "/mapimages/" + jcbh + "_" + sheet_name_str[vi] + ".png");
                mapvi.put("sheet", vi + "");
                mapvi.put("mjj", mjj_str[vi]);
                mapvi.put("bhj", bhj_str[vi]);
                mapvi.put("upload", tDkGeomDb.getId());
                sheet_json.add(mapvi);

                ;
                String yjjbnt_hgx_ywyp = yjjbnt_hgx.getYwypCode();
                String gd_hgx_ywyp = gd_hgx.getYwypCode();
                if (StringUtils.isNotEmpty(yjjbnt_hgx_ywyp)) {
                    if (yjjbnt_hgx_ywyp.equals(hfx1_str[vi])) {
                        dkGeomDbDetails.setYjjbntmj(mj_str[vi]);
                    }
                }
                if (StringUtils.isNotEmpty(gd_hgx_ywyp)) {
                    if (gd_hgx_ywyp.equals(hfx1_str[vi])) {
                        dkGeomDbDetails.setGdmj(mj_str[vi]);
                    }
                }

            }
            dkGeomDbDetails.setSheetJson(JSON.toJSONString(sheet_json));
            tDkGeomDbDetailsMapper.insertTDkGeomDbDetails(dkGeomDbDetails);
        }
        tDkGeomDb.setUpdateNumberCheckSuccess(successNumber);
        tDkGeomDb.setUpdateNumberCheckFull(fullNumber);
        return 0;
    }

    public int insertTDkGeomDb(List<TGeomDbDetails> dbDetails, TDkGeomDb tDkGeomDb, String tif_path) {
        String dbDetailJson = null;
        Long successNumber = 0L;
        Long fullNumber = 0L;
        for (TGeomDbDetails dbDetail : dbDetails) {
            dbDetailJson = dbDetail.getGeomJson();
            if (StringUtils.isEmpty(dbDetailJson)) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("读取shp数据缺失属性");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }
//            xzqdm(行政区代码) *
//            xzqmc(行政区名称)
//            jcbh(监测图斑编号) *
//            jcmj(监测面积(亩)) *
//            qlx(前类型)
//            hlx(后类型)
//            lzb(中心点经度)
//            bzb(中心点维度)
//            qsx(前时相) *
//            hsx(后时相) *
            //* 标注为必须字段,不可为空。其他为选配字段 如果还有其他字段，将统一放入到JSON字段中
            JSONObject jsonObject = JSON.parseObject(dbDetailJson);
            //获取属性字段，并将字段进行赋值。获取成功的将删除该KEY
            String xzqdm = jsonObject.getString("xzqdm");
            String xzqmc = jsonObject.getString("xzqmc");
            String jcbh = jsonObject.getString("jcbh");
            BigDecimal jcmj = jsonObject.getBigDecimal("jcmj");
            String qlx = jsonObject.getString("qlx");
            String hlx = jsonObject.getString("hlx");
            String lzb = jsonObject.getString("lzb");
            String bzb = jsonObject.getString("bzb");
            String qsx = jsonObject.getString("qsx");
            String hsx = jsonObject.getString("hsx");
            if (StringUtils.isEmpty(xzqdm) || StringUtils.isEmpty(jcbh) || null == jcmj || StringUtils.isEmpty(qsx) || StringUtils.isEmpty(hsx)) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("shp属性字段缺失");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }
            //删除KEY
            jsonObject.remove("xzqdm");
            jsonObject.remove("xzqmc");
            jsonObject.remove("jcbh");
            jsonObject.remove("jcmj");
            jsonObject.remove("qlx");
            jsonObject.remove("hlx");
            jsonObject.remove("lzb");
            jsonObject.remove("bzb");
            jsonObject.remove("qsx");
            jsonObject.remove("hsx");
            //校验dkbh是否重复，且数据是否进入核查流程状态
            boolean checkUpdateBoolean = itDkjbxxService.checkDkjbxxUpdate(jcbh);
            TDkGeomDbDetails dkGeomDbDetails = new TDkGeomDbDetails();
            dkGeomDbDetails.setId(IdUtils.fastSimpleUUID());
            dkGeomDbDetails.setGeom(dbDetail.getGeom());
            dkGeomDbDetails.setGeomArea(dbDetail.getGeomArea());
            dkGeomDbDetails.setXzqdm(xzqdm);
            dkGeomDbDetails.setXzqmc(xzqmc);
            dkGeomDbDetails.setDkbh(jcbh);
            dkGeomDbDetails.setDkmj(jcmj.toString());
            dkGeomDbDetails.setQlx(qlx);
            dkGeomDbDetails.setHlx(hlx);
            dkGeomDbDetails.setLzb(lzb);
            dkGeomDbDetails.setBzb(bzb);
            dkGeomDbDetails.setQsx(qsx);
            dkGeomDbDetails.setHsx(hsx);
            dkGeomDbDetails.setUploadId(tDkGeomDb.getId());
            dkGeomDbDetails.setQsxtif(domain + localFilePrefix + tif_path + "/QDOM/" + jcbh + "QDOM.tif");
            dkGeomDbDetails.setHsxtif(domain + localFilePrefix + tif_path + "/DDOM/" + jcbh + "DDOM.tif");
            if (checkUpdateBoolean) {
                successNumber++;
                dkGeomDbDetails.setCheckUpdate("0");
            } else {
                fullNumber++;
                dkGeomDbDetails.setCheckUpdate("1");
            }
            dkGeomDbDetails.setShpJson(jsonObject.toJSONString());
            tDkGeomDbDetailsMapper.insertTDkGeomDbDetails(dkGeomDbDetails);
        }
        tDkGeomDb.setUpdateNumberCheckSuccess(successNumber);
        tDkGeomDb.setUpdateNumberCheckFull(fullNumber);
        return 0;
    }

    private String readMultiSheetXLSXToMap(String fileName, String uploadId) {
        StringBuilder retStr = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(new File(fileName)); Workbook workbook = new XSSFWorkbook(fis)) {
            // 获取工作簿中 sheet 的数量
            int numberOfSheets = workbook.getNumberOfSheets();

            // 遍历每个 sheet
            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                System.out.println("Sheet 名称: " + sheet.getSheetName());
                retStr.append(sheet.getSheetName()).append(";");
                // 获取第一行作为列名
                Row headerRow = sheet.getRow(0);
                List<String> headers = new ArrayList<>();
                for (Cell cell : headerRow) {
                    headers.add(cell.getStringCellValue());
                }

                // 从第二行开始遍历数据行
                for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                    Row row = sheet.getRow(j);
                    Map<String, Object> rowData = new HashMap<>();

                    // 遍历每个单元格
                    for (int k = 0; k < headers.size(); k++) {
                        Cell cell = row.getCell(k);
                        Object cellValue = null;
                        if (cell != null) {
                            switch (cell.getCellType()) {
                                case STRING:
                                    cellValue = cell.getStringCellValue();
                                    break;
                                case NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        cellValue = cell.getDateCellValue();
                                    } else {
                                        cellValue = cell.getNumericCellValue();
                                    }
                                    break;
                                case BOOLEAN:
                                    cellValue = cell.getBooleanCellValue();
                                    break;
                                case FORMULA:
                                    cellValue = cell.getCellFormula();
                                    break;
                                default:
                                    cellValue = null;
                            }
                        }
                        // 将单元格值存入 Map，键为列名
                        rowData.put(headers.get(k), cellValue);
                    }
                    TDkYwypXlsxDetails details = new TDkYwypXlsxDetails();
                    details.setId(IdUtils.fastSimpleUUID());
                    details.setUploadId(uploadId);
                    details.setSheet(i + "");
                    details.setSwid((String) rowData.get("swid"));
                    rowData.remove("swid");
                    details.setSheetJson(JSON.toJSONString(rowData));
                    itDkYwypXlsxDetailsService.insertTDkYwypXlsxDetails(details);
                    // 打印每行数据的 Map
//                    System.out.println(rowData);
                }
//                System.out.println();
            }
        } catch (IOException e) {
//            e.printStackTrace();
            retStr = new StringBuilder();
        }
        return retStr.toString();
    }


    private int checkDataTypeFile(File shpPath, TDkGeomDb tDkGeomDb) {
        String shpNameD0 = shpPath.getName();
        tDkGeomDb.setName(shpNameD0);
        //获取文件夹
        String paremtFilePath = shpPath.getParentFile().getAbsolutePath();
        if ("2".equals(tDkGeomDb.getDataType())) {
            //验证mapimages
            if (!(new File(paremtFilePath + "/mapimages").exists())) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("shp文件中QDOM不存在");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }

            String execl_path = shpNameD0.substring(0, shpNameD0.length() - 4) + ".xlsx";
            if (!(new File(paremtFilePath + "/" + execl_path).exists())) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("shp文件中xlsx不存在");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }
        } else {
            //验证QDOM
            if (!(new File(paremtFilePath + "/QDOM").exists())) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("shp文件中QDOM不存在");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }

            if (!(new File(paremtFilePath + "/DDOM").exists())) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("shp文件中DDOM不存在");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 1;
            }
        }
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTDkGeomDb(TDkGeomDb tDkGeomDb) {
        tDkGeomDb.setStatus("1");
        tDkGeomDb.setId(IdUtils.fastSimpleUUID());
        tDkGeomDb.setCreateTime(DateUtils.getNowDate());
        tDkGeomDb.setCreateBy(SecurityUtils.getUsername());
        //解压zip
        String zipPath = tDkGeomDb.getShppath();
        zipPath = localFilePath + zipPath;
        if (!FileTypeUtils.getFileType(zipPath).equalsIgnoreCase("zip")) {
            log.error("文件类型不是zip");
            tDkGeomDb.setStatus("2");
            tDkGeomDb.setMessage("文件类型不是zip");
            tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
            return 0;
        }
        File zipFile = new File(zipPath);
        if (!zipFile.exists()) {
            log.error("zip文件不存在");
            tDkGeomDb.setStatus("2");
            tDkGeomDb.setMessage("zip文件不存在");
            tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
            return 0;
        }
        //加压路径
        String unZipPath = zipPath.substring(0, zipPath.length() - 4);
        System.out.println(zipPath);
        System.out.println(unZipPath);
        UnPackageUtils.unPackZip(zipPath, unZipPath, null);

        //判断shp文件是否存在
        List<File> shpFiles = new ArrayList<>();
        FileUtils.findTypeByFiles(unZipPath, shpFiles, new String[]{".shp"});
        if (shpFiles.isEmpty()) {
            log.error("shp文件不存在");
            tDkGeomDb.setStatus("2");
            tDkGeomDb.setMessage("shp文件不存在");
            tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
            return 0;
        }
        File shpPile = shpFiles.get(0);
        //验证文件
        int checkDataTypeFile = checkDataTypeFile(shpPile, tDkGeomDb);
        if (1 == checkDataTypeFile) {
            return 0;
        }
        tDkGeomDb.setName(shpPile.getName());

        //获取文件夹
        String paremtFilePath = shpPile.getParentFile().getAbsolutePath();
        String db0_local_path = localFilePath.replaceAll("\\\\", "/").replaceAll("//", "/");
        String db0_paremt_path = paremtFilePath.replaceAll("\\\\", "/").replaceAll("//", "/");
        String tif_path = db0_paremt_path.substring(db0_paremt_path.indexOf(db0_local_path) + db0_local_path.length());


        String db0_shp_path = shpPile.getAbsolutePath();
        String ppp = db0_shp_path.substring(db0_paremt_path.indexOf(db0_local_path) + db0_local_path.length());
        tDkGeomDb.setShppath(ppp);
        //解析shp文件
        R<TGeomDb> readShpResult = remoteSpatialFilesDbService.readShp(shpPile.getName(), ppp, "TDkGeomDbServiceImpl.insertTDkGeomDb", SecurityConstants.INNER);
        if (R.FAIL == readShpResult.getCode()) {
            tDkGeomDb.setStatus("2");
            tDkGeomDb.setMessage("解析shp文件出错");
            tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
            return 0;
        }
        TGeomDb db = readShpResult.getData();
        if (db == null) {
            tDkGeomDb.setStatus("2");
            tDkGeomDb.setMessage("解析shp文件出错");
            tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
            return 0;
        }

        //解析shp文件
        R<List<TGeomDbDetails>> readShpGeomDetails = remoteSpatialFilesDbService.queryGeomDetails(db.getId(), SecurityConstants.INNER);
        if (R.FAIL == readShpGeomDetails.getCode()) {
            tDkGeomDb.setStatus("2");
            tDkGeomDb.setMessage("读取shp数据出错");
            tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
            return 0;
        }
        List<TGeomDbDetails> dbDetails = readShpGeomDetails.getData();

        if ("2".equals(tDkGeomDb.getDataType())) {
            String shpNameD0 = shpPile.getName();
            String execl_path = shpNameD0.substring(0, shpNameD0.length() - 4) + ".xlsx";
            //解析XLSX
            String sheet_name = readMultiSheetXLSXToMap(paremtFilePath + "/" + execl_path, tDkGeomDb.getId());
            if (StringUtils.isEmpty(sheet_name)) {
                tDkGeomDb.setStatus("2");
                tDkGeomDb.setMessage("解析XLSX数据出错");
                tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
                return 0;
            }
            int i = insertTDkGeomDbYWYP(dbDetails, tDkGeomDb, sheet_name, tif_path);
            if (i == 1) {
                return 0;
            }
        } else {
            int i = insertTDkGeomDb(dbDetails, tDkGeomDb, tif_path);
            if (i == 1) {
                return 0;
            }
        }
        tDkGeomDb.setGeom(db.getGeom());
        tDkGeomDb.setGeomArea(db.getGeomArea());
        tDkGeomDb.setGeomNumber(db.getGeomNumber());
        tDkGeomDb.setStatus("0");
        tDkGeomDb.setMessage("处理成功");
        tDkGeomDb.setFiletype(db.getFiletype());
        tDkGeomDbMapper.insertTDkGeomDb(tDkGeomDb);
        return 1;
    }

    /**
     * 下发空间入库存储
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int issueTDkGeomDb(String id) {
        if (StringUtils.isEmpty(id)) {
            log.error("参数为空");
            return 0;
        }
        TDkGeomDb dkGeomDb = tDkGeomDbMapper.selectTDkGeomDbById(id);
        if (dkGeomDb == null) {
            log.error("查询数据为空");
            return 0;
        }
        if (!"0".equals(dkGeomDb.getStatus())) {
            log.error("非成功状态不可处理");
            dkGeomDb.setUpdateMessage("非成功状态不可处理");
            tDkGeomDbMapper.updateTDkGeomDb(dkGeomDb);
            return 0;
        }
        TDkAuditflowType dkAuditflowType = itDkAuditflowTypeService.selectTDkAuditflowTypeDefault();
        if (dkAuditflowType == null) {
            log.error("默认核查流程为空");
            dkGeomDb.setUpdateMessage("默认核查流程为空");
            tDkGeomDbMapper.updateTDkGeomDb(dkGeomDb);
            return 0;
        }
        TDkGeomDbDetails queryData0 = new TDkGeomDbDetails();
        queryData0.setUploadId(id);
        List<TDkGeomDbDetails> tDkGeomDbDetails = tDkGeomDbDetailsMapper.selectTDkGeomDbDetailsList(queryData0);
        Long successNumber = 0L;
        Long fullNumber = 0L;

        for (TDkGeomDbDetails dataObj : tDkGeomDbDetails) {
            if ("2".equals(dkGeomDb.getDataType())) {
                //校验dkbh是否存在
                TDkjbxx dkjbxx = itDkjbxxService.selectTDkjbxxByDkbh(dataObj.getDkbh());
                if (dkjbxx == null) {
                    fullNumber++;
                    continue;
                }

                //校验ywyp是否已经更新过
                boolean checkUpdateBoolean = iTDkjbxxYwypService.checkDkjbxxYwypUpdate(dataObj.getDkbh());
                if (!checkUpdateBoolean) {
                    fullNumber++;
                    continue;
                }

                dataObj = itDkGeomDbDetailsService.selectTDkGeomDbDetailsById(dataObj.getId());
//                //TDkGeomDbDetails 与 TDkjbxx 主要字段尽量保持一致。方便进行转换
                String stuString = JSONObject.toJSONString(dataObj);
                TDkjbxxYwyp tDkjbxx = JSONObject.parseObject(stuString, TDkjbxxYwyp.class);
                tDkjbxx.setCreateBy(SecurityUtils.getUsername());
                tDkjbxx.setId(dkjbxx.getId());
                iTDkjbxxYwypService.insertTDkjbxxYwyp(tDkjbxx);
                successNumber++;

            } else {
                //校验dkbh是否重复，且数据是否进入核查流程状态
                boolean checkUpdateBoolean = itDkjbxxService.checkDkjbxxUpdate(dataObj.getDkbh());
                if (!checkUpdateBoolean) {
                    fullNumber++;
                    continue;
                }
                //TDkGeomDbDetails 与 TDkjbxx 主要字段尽量保持一致。方便进行转换
                String stuString = JSONObject.toJSONString(dataObj);
                TDkjbxx tDkjbxx = JSONObject.parseObject(stuString, TDkjbxx.class);
                tDkjbxx.setAuditflow(dkAuditflowType.getAuditflowCode());
                String username = SecurityUtils.getUsername();
                if (StringUtils.isEmpty(username)) {
                    username = "admin";
                }
                tDkjbxx.setCreateBy(username);
                insertTDkjbxx(tDkjbxx);
                successNumber++;
            }
        }

        dkGeomDb.setUpdateNumberFull(fullNumber);
        dkGeomDb.setUpdateNumberSuccess(successNumber);
        dkGeomDb.setUpdateMessage("执行完成");
        dkGeomDb.setStatus("3");
        dkGeomDb.setUpdateBy(SecurityUtils.getUsername());
        dkGeomDb.setUpdateTime(DateUtils.getNowDate());
        tDkGeomDbMapper.updateTDkGeomDb(dkGeomDb);
        return 1;
    }


    private void insertTDkjbxx(TDkjbxx newDkjbxx) {
        TDkjbxx dkjbxx = itDkjbxxService.selectTDkjbxxByDkbh(newDkjbxx.getDkbh());
        if (dkjbxx == null) {
            itDkjbxxService.insertTDkjbxx(newDkjbxx);
        } else {
            newDkjbxx.setId(dkjbxx.getId());
            itDkjbxxService.updateTDkjbxx(newDkjbxx);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTDkGeomDbByIds(String[] ids) {
        itDkYwypXlsxDetailsService.deleteTDkYwypXlsxDetailsByUploadId(ids);
        tDkGeomDbDetailsMapper.deleteTDkGeomDbDetailsByUploadIds(ids);
        return tDkGeomDbMapper.deleteTDkGeomDbByIds(ids);
    }
}
