package com.siwei.rsmonitoring.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectoryBase;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.exif.GpsDirectory;
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.ImageUtils;
import com.siwei.common.core.utils.uuid.IdUtils;
import com.siwei.common.security.utils.SecurityUtils;
import com.siwei.rsmonitoring.config.StaticConfig;
import com.siwei.rsmonitoring.domain.*;
import com.siwei.rsmonitoring.service.ITDkAuditflowFjService;
import com.siwei.rsmonitoring.service.ITDkAuditflowRecordService;
import com.siwei.rsmonitoring.service.ITDkFieldworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.siwei.rsmonitoring.mapper.TDkjbxxHcMapper;
import com.siwei.rsmonitoring.service.ITDkjbxxHcService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地块基本信息核查判定Service业务层处理
 *
 * @author siwei
 * @date 2025-03-03
 */
@Service
public class TDkjbxxHcServiceImpl implements ITDkjbxxHcService {
    @Autowired
    private TDkjbxxHcMapper tDkjbxxHcMapper;
    @Autowired
    private ITDkFieldworkService itDkFieldworkService;
    @Autowired
    private ITDkAuditflowRecordService dkAuditflowRecordService;
    @Autowired
    private ITDkAuditflowFjService itDkAuditflowFjService;
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 查询地块基本信息核查判定
     *
     * @param id 地块基本信息核查判定主键
     * @return 地块基本信息核查判定
     */
    @Override
    public TDkjbxxHc selectTDkjbxxHcById(String id) {
        return tDkjbxxHcMapper.selectTDkjbxxHcById(id);
    }

    @Override
    public List<TDkjbxxHc> selectTDkjbxxHcInfo(String fieldworkId, String dkid, String auditflowStep, String auditflowId) {
        if (StringUtils.isEmpty(dkid) && StringUtils.isEmpty(fieldworkId)) {
            return null;
        }
        if (StringUtils.isEmpty(auditflowStep)) {
            return null;
        }
        TDkjbxxHc tDkjbxxScQuery = new TDkjbxxHc();
        if (StringUtils.isNotEmpty(fieldworkId)) {
            tDkjbxxScQuery.setFieldworkId(fieldworkId);
        }
        if (StringUtils.isNotEmpty(dkid)) {
            tDkjbxxScQuery.setDkjbxxId(dkid);
        }
        tDkjbxxScQuery.setAuditflowStep(auditflowStep);
        if (StringUtils.isNotEmpty(auditflowId)) {
            tDkjbxxScQuery.setAuditflowId(auditflowId);
        }
        List<TDkjbxxHc> list = tDkjbxxHcMapper.selectTDkjbxxHcList(tDkjbxxScQuery);
        if (list.isEmpty()) {
            return null;
        }

        for (TDkjbxxHc dkjbxxSc : list) {
            TDkAuditflowFj tDkAuditflowFj = new TDkAuditflowFj();
            tDkAuditflowFj.setAuditflowId(dkjbxxSc.getAuditflowId());
            dkjbxxSc.setFjs(itDkAuditflowFjService.selectTDkAuditflowFjList(tDkAuditflowFj));

            TDkAuditflowFj tDkAuditflowSdFj = new TDkAuditflowFj();
            tDkAuditflowSdFj.setAuditflowId(dkjbxxSc.getId());
            dkjbxxSc.setSdfjs(itDkAuditflowFjService.selectTDkAuditflowFjList(tDkAuditflowSdFj));
        }
        return list;
    }

    /**
     * 查询地块基本信息核查判定列表
     *
     * @param tDkjbxxHc 地块基本信息核查判定
     * @return 地块基本信息核查判定
     */
    @Override
    public List<TDkjbxxHc> selectTDkjbxxHcList(TDkjbxxHc tDkjbxxHc) {
        return tDkjbxxHcMapper.selectTDkjbxxHcList(tDkjbxxHc);
    }

    /**
     * 新增地块基本信息核查判定
     *
     * @param tDkjbxxHc 地块基本信息核查判定
     * @return 结果
     */
    @Override
    public int insertTDkjbxxHc(TDkjbxxHc tDkjbxxHc) {
        tDkjbxxHc.setCreateTime(DateUtils.getNowDate());
        return tDkjbxxHcMapper.insertTDkjbxxHc(tDkjbxxHc);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addTDkjbxxHc(TDkjbxxHc tDkjbxxHc) {
        if (null == tDkjbxxHc) {
            return 0;
        }
        if (StringUtils.isEmpty(tDkjbxxHc.getFieldworkId()) || StringUtils.isEmpty(tDkjbxxHc.getAuditflowStep()) || StringUtils.isEmpty(tDkjbxxHc.getDecide()) || StringUtils.isEmpty(tDkjbxxHc.getDlbm()) || StringUtils.isEmpty(tDkjbxxHc.getDlmc())) {
            return 0;
        }
        String fieldworkId = tDkjbxxHc.getFieldworkId();
        String auditflowStep = tDkjbxxHc.getAuditflowStep();
        //验证ID
        TDkFieldwork v1 = itDkFieldworkService.selectTDkFieldworkById(fieldworkId);
        if (v1 == null) {
            throw new ServiceException("信息缺失");
        }
        if (!SecurityUtils.getUserId().toString().equals(v1.getFieldworkId())) {
            throw new ServiceException("信息缺失");
        }
        if (!"1".equals(v1.getStepState()) && !"2".equals(v1.getStepState())) {
            throw new ServiceException("无权限执行");
        }
        String dkid = v1.getDkjdxxId();
        if (StringUtils.isEmpty(dkid)) {
            return 0;
        }
        if (!dkAuditflowRecordService.isCheckUserTDkAuditflowRecord(v1.getDkjdxxId(), v1.getAuditflow(), auditflowStep, null)) {
            return 0;
        }
        tDkjbxxHc.setDkjbxxId(v1.getDkjdxxId());
        tDkjbxxHc.setCreateBy(SecurityUtils.getUsername());
        tDkjbxxHc.setId(IdUtils.fastSimpleUUID());
        tDkjbxxHc.setCreateTime(DateUtils.getNowDate());
        tDkjbxxHcMapper.insertTDkjbxxHc(tDkjbxxHc);

        //核查照片
        for (TDkAuditflowFj fjObj : tDkjbxxHc.getSdfjs()) {
            try {
                fjObj = checkPhoto(fjObj);
            } catch (MetadataException e) {
                throw new RuntimeException(e);
            }
            fjObj.setDkjbxxId(dkid);
            fjObj.setId(IdUtils.fastSimpleUUID());
            fjObj.setCreateBy(SecurityUtils.getUsername());
            fjObj.setCreateTime(DateUtils.getNowDate());
            fjObj.setAuditflowId(tDkjbxxHc.getId());
            itDkAuditflowFjService.insertTDkAuditflowFj(fjObj);
        }

        List<String> fjUpdateList = new ArrayList<>();
        //附件
        for (TDkAuditflowFj fjObj : tDkjbxxHc.getFjs()) {
            fjObj.setDkjbxxId(dkid);
            fjObj.setId(IdUtils.fastSimpleUUID());
            fjObj.setCreateBy(SecurityUtils.getUsername());
            fjObj.setCreateTime(DateUtils.getNowDate());
            itDkAuditflowFjService.insertTDkAuditflowFj(fjObj);
            fjUpdateList.add(fjObj.getId());
        }

        //更新流程
        TDkAuditflowRecord tDkAuditflowRecord = new TDkAuditflowRecord();
        tDkAuditflowRecord.setDkjdxxId(v1.getDkjdxxId());
        tDkAuditflowRecord.setAuditflowType(v1.getAuditflow());
        tDkAuditflowRecord.setCreateBy(SecurityUtils.getUsername());
        tDkAuditflowRecord.setAuditflowStep(auditflowStep);
        Map<String, String> recordData = null;
        tDkAuditflowRecord.setSuccessType("0");
        recordData = dkAuditflowRecordService.refreshTDkAuditflowRecord(tDkAuditflowRecord);
        if (recordData.isEmpty()) {
            throw new ServiceException("流程失败");
        }
        String currentId = recordData.get("current");
        deleteAuditflowId(currentId);

        // TDkFieldwork v1 =
        TDkFieldwork v1Update = new TDkFieldwork();
        v1Update.setId(v1.getId());
        v1Update.setStepState("2");
        itDkFieldworkService.updateTDkFieldwork(v1Update);

        //更新标志
        for (String idObj : fjUpdateList) {
            TDkAuditflowFj tDkAuditflowFj = new TDkAuditflowFj();
            tDkAuditflowFj.setId(idObj);
            tDkAuditflowFj.setAuditflowId(currentId);
            itDkAuditflowFjService.updateTDkAuditflowFj(tDkAuditflowFj);
        }

        TDkjbxxHc tDkjbxxScUpdate = new TDkjbxxHc();
        tDkjbxxScUpdate.setId(tDkjbxxHc.getId());
        tDkjbxxScUpdate.setAuditflowId(currentId);
        tDkjbxxHcMapper.updateTDkjbxxHc(tDkjbxxScUpdate);
        return 1;
    }

    private void deleteAuditflowId(String auditflowId) {
        //删除之前上传的数据
        itDkAuditflowFjService.deleteTDkAuditflowFjByAuditflowId(auditflowId);
        TDkjbxxHc tDkjbxxHc = new TDkjbxxHc();
        tDkjbxxHc.setAuditflowId(auditflowId);
        List<TDkjbxxHc> removerList = tDkjbxxHcMapper.selectTDkjbxxHcList(tDkjbxxHc);
        for (TDkjbxxHc hc : removerList) {
            tDkjbxxHcMapper.deleteTDkjbxxHcById(hc.getId());
            itDkAuditflowFjService.deleteTDkAuditflowFjByAuditflowId(hc.getId());
        }

    }

    private TDkAuditflowFj checkPhoto(TDkAuditflowFj fjObj) throws MetadataException {
        // 读取照片元数据
        Metadata metadata = ImageUtils.readFileMetadata(new File(localFilePath + fjObj.getFjPath()));
        if (metadata == null) {
            throw new ServiceException("图片信息读取失败");
        }

        // 读取GPS信息
        GpsDirectory gpsDirectory = metadata.getFirstDirectoryOfType(GpsDirectory.class);
        if (gpsDirectory != null) {
            // 纬度经度坐标
            if (gpsDirectory.containsTag(GpsDirectory.TAG_LATITUDE) && gpsDirectory.containsTag(GpsDirectory.TAG_LONGITUDE)) {
                double latitude = gpsDirectory.getGeoLocation().getLatitude();
                double longitude = gpsDirectory.getGeoLocation().getLongitude();
                System.out.println("纬度: " + latitude);
                System.out.println("经度: " + longitude);
                fjObj.setFjLatitude(String.valueOf(latitude));
                fjObj.setFjLongitude(String.valueOf(longitude));
            } else {
                System.out.println("图片中不包含经纬度信息。");
                throw new ServiceException("图片信息读取失败");
            }
            //高度
            if (gpsDirectory.containsTag(GpsDirectory.TAG_ALTITUDE)) {
                double altitude = gpsDirectory.getDouble(GpsDirectory.TAG_ALTITUDE);
                System.out.println("高度: " + altitude);
                fjObj.setFjAltitude(String.valueOf(altitude));
            }
            if (gpsDirectory.containsTag(GpsDirectory.TAG_TIME_STAMP)) {
                Date altitude = gpsDirectory.getGpsDate();
                System.out.println("TIME: " + altitude);
            }
            //方向
            if (gpsDirectory.containsTag(GpsDirectory.TAG_IMG_DIRECTION)) {
                double direction = gpsDirectory.getDouble(GpsDirectory.TAG_IMG_DIRECTION);
                System.out.println("方向: " + direction);
                fjObj.setFjDirection(String.valueOf(direction));
            } else {
                System.out.println("图片中不包含方向信息。");
                throw new ServiceException("图片信息读取失败");
            }
        } else {
            System.out.println("图片中不包含 GPS 元数据。");
            throw new ServiceException("图片中不包含 GPS 元数据");
        }

        ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
        if (exifIFD0Directory != null) {
            if (exifIFD0Directory.containsTag(ExifDirectoryBase.TAG_ARTIST)) {
                String artist = exifIFD0Directory.getString(ExifDirectoryBase.TAG_ARTIST);
                System.out.println("照片作者: " + artist);
                fjObj.setFjArtist(artist);
            } else {
                System.out.println("照片中未包含 Artist 信息。");
            }

            if (exifIFD0Directory.containsTag(ExifDirectoryBase.TAG_SOFTWARE)) {
                String software = exifIFD0Directory.getString(ExifDirectoryBase.TAG_SOFTWARE);
                System.out.println("拍摄或处理照片的软件: " + software);
                fjObj.setFjSoftware(software);
            } else {
                System.out.println("照片中未包含 Software 信息。");
            }

            if (exifIFD0Directory.containsTag(ExifDirectoryBase.TAG_DATETIME)) {
                String software1 = exifIFD0Directory.getString(ExifDirectoryBase.TAG_DATETIME);
                System.out.println("拍摄时间: " + software1);
                fjObj.setFjDatetime(software1);
            } else {
                System.out.println("照片中未包含 拍摄时间 信息。");
                throw new ServiceException("图片中不包含拍摄时间");
            }
        } else {
            throw new ServiceException("图片中不包含拍摄时间");
        }
        return fjObj;
    }

    /**
     * 修改地块基本信息核查判定
     *
     * @param tDkjbxxHc 地块基本信息核查判定
     * @return 结果
     */
    @Override
    public int updateTDkjbxxHc(TDkjbxxHc tDkjbxxHc) {
        return tDkjbxxHcMapper.updateTDkjbxxHc(tDkjbxxHc);
    }

    /**
     * 批量删除地块基本信息核查判定
     *
     * @param ids 需要删除的地块基本信息核查判定主键
     * @return 结果
     */
    @Override
    public int deleteTDkjbxxHcByIds(String[] ids) {
        return tDkjbxxHcMapper.deleteTDkjbxxHcByIds(ids);
    }

    /**
     * 删除地块基本信息核查判定信息
     *
     * @param id 地块基本信息核查判定主键
     * @return 结果
     */
    @Override
    public int deleteTDkjbxxHcById(String id) {
        return tDkjbxxHcMapper.deleteTDkjbxxHcById(id);
    }
}
