package com.bonus.material.basic.service.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.util.PhoneUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.archives.service.ArchivesService;
import com.bonus.material.basic.domain.BmAgreementInfo;
import com.bonus.material.basic.mapper.BmAgreementInfoMapper;
import com.bonus.material.purchase.config.RemoteConfig;
import com.bonus.system.api.RemoteDeptService;
import com.bonus.system.api.domain.SysDept;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.material.basic.mapper.BmProjectMapper;
import com.bonus.material.basic.domain.BmProject;
import com.bonus.material.basic.service.IBmProjectService;

import javax.annotation.Resource;


/**
 * 标段工程管理Service业务层处理
 * 
 * @author xsheng
 * @date 2024-09-26
 */
@Service
@Slf4j
public class BmProjectServiceImpl implements IBmProjectService 
{
    @Resource
    private BmProjectMapper bmProjectMapper;

    @Resource
    private RemoteDeptService remoteDeptService;

    @Resource
    private ArchivesService archivesService;

    @Resource
    private RemoteConfig remoteConfig;

    @Resource
    private BmAgreementInfoMapper bmAgreementInfoMapper;


    /**
     * 查询标段工程管理
     * 
     * @param proId 标段工程管理主键
     * @return 标段工程管理
     */
    @Override
    public BmProject selectBmProjectByProId(Long proId)
    {
        BmProject project = bmProjectMapper.selectBmProjectByProId(proId);
        extractedImpUnit(project);
        extractProject(project);
        return project;
    }

    /**
     * 方法抽取
     * @param project
     */
    private void extractProject(BmProject project) {
        Map<String, String> typeMap = remoteConfig.getDictValue("bm_project_type");
        Map<String, String> natureMap = remoteConfig.getDictValue("bm_project_nature");
        Map<String, String> statusMap = remoteConfig.getDictValue("bm_project_status");
        if (StringUtils.isNotBlank(project.getProTypeId())) {
            String type = typeMap.get(project.getProTypeId());
            project.setProType(StringUtils.isBlank(type) ? "" : type);
        }
        if (StringUtils.isNotBlank(project.getProNature())) {
            String nature = natureMap.get(project.getProNature());
            project.setProNatureName(StringUtils.isBlank(nature) ? "" : nature);
        }
        if (StringUtils.isNotBlank(project.getProStatus())) {
            String status = statusMap.get(project.getProStatus());
            project.setProStatusName(StringUtils.isBlank(status) ? "" : status);
        }
    }

    /**
     * 实施单位方法抽取
     * @param project
     */
    private void extractedImpUnit(BmProject project) {
        try {
            if (!StringUtils.isBlank(project.getTelphone())) {
                project.setTelphone(Sm4Utils.decrypt(project.getTelphone()));
            }
            AjaxResult ajaxResult = remoteDeptService.getInfo(Long.parseLong(project.getImpUnit()), SecurityConstants.INNER);
            //健壮性判断
            if (ajaxResult.isSuccess()) {
                // ajaxResult.get("data") 返回的是 LinkedHashMap
                LinkedHashMap rawDataList = (LinkedHashMap) ajaxResult.get("data");
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                if (rawDataList != null) {
                    SysDept sysDept = objectMapper.convertValue(rawDataList, SysDept.class);
                    project.setImpUnitName(sysDept.getDeptName() == null ? "" : sysDept.getDeptName());
                }
            }
        } catch (NumberFormatException e) {
            project.setTelphone("");
            log.error("远程调用查询失败：", e.getMessage());
        }
    }

    /**
     * 查询标段工程管理列表
     * 
     * @param bmProject 标段工程管理
     * @return 标段工程管理
     */
    @Override
    public List<BmProject> selectBmProjectList(BmProject bmProject)
    {
        List<BmProject> list = bmProjectMapper.selectBmProjectList(bmProject);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(this::extractedImpUnit);
            extracted(list);
        }
        return list;
    }

    /**
     * 方法抽取
     * @param list
     */
    private void extracted(List<BmProject> list) {
        Map<String, String> typeMap = remoteConfig.getDictValue("bm_project_type");
        Map<String, String> natureMap = remoteConfig.getDictValue("bm_project_nature");
        Map<String, String> statusMap = remoteConfig.getDictValue("bm_project_status");
        for (BmProject item : list) {
            if (StringUtils.isNotBlank(item.getProTypeId())) {
                String type = typeMap.get(item.getProTypeId());
                item.setProType(StringUtils.isBlank(type) ? "" : type);
            }
            if (StringUtils.isNotBlank(item.getProNature())) {
                String nature = natureMap.get(item.getProNature());
                item.setProNatureName(StringUtils.isBlank(nature) ? "" : nature);
            }
            if (StringUtils.isNotBlank(item.getProStatus())) {
                String status = statusMap.get(item.getProStatus());
                item.setProStatusName(StringUtils.isBlank(status) ? "" : status);
            }
            item.setIsMatchI8(StringUtils.isNotEmpty(item.getExternalId()) ? "匹配" : "不匹配");
        }
    }

    /**
     * 新增标段工程管理
     * 
     * @param bmProject 标段工程管理
     * @return 结果
     */
    @Override
    public AjaxResult insertBmProject(BmProject bmProject)
    {
        if (bmProject == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        //首先根据工程或名称去表中查询，看是否重复
        List<BmProject> projectList = bmProjectMapper.selectBmProjectByProName(bmProject);
        if (CollectionUtils.isNotEmpty(projectList)) {
            return AjaxResult.error(HttpCodeEnum.NAME_DUPLICATE.getCode(), "工程名称或工程编码与库中重复");
        }
        //校验输入的经纬度是否合规
        /*if (bmProject.getLon() != null) {
            if (!bmProject.getLon().matches(MaterialConstants.LONGITUDE_PATTERN)){
                return AjaxResult.error(HttpCodeEnum.INVALID_LONGITUDE_FORMAT.getCode(), HttpCodeEnum.INVALID_LONGITUDE_FORMAT.getMsg());
            }
        }
        if (bmProject.getLat() != null) {
            if (!bmProject.getLat().matches(MaterialConstants.LATITUDE_PATTERN)){
                return AjaxResult.error(HttpCodeEnum.INVALID_LATITUDE_FORMAT.getCode(), HttpCodeEnum.INVALID_LATITUDE_FORMAT.getMsg());
            }
        }*/
        //判断手机号是否合法
        if (StringUtils.isNotBlank(bmProject.getTelphone()) && !PhoneUtil.isMobile(bmProject.getTelphone())) {
            return AjaxResult.error(HttpCodeEnum.INVALID_PHONE_FORMAT.getCode(), HttpCodeEnum.INVALID_PHONE_FORMAT.getMsg());
        }
        String telPhone = Sm4Utils.encrypt(bmProject.getTelphone());
        bmProject.setCreateTime(DateUtils.getNowDate());
        bmProject.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
        bmProject.setTelphone(telPhone);
        int result = bmProjectMapper.insertBmProject(bmProject);
        if (result > 0) {
            // 工程标段添加成功
            try {
                AjaxResult projectAddEventCopeResult = archivesService.projectAddEventCope(bmProject);
                if (projectAddEventCopeResult.isSuccess()) {
                    log.info("工程标段添加成功，且档案事件处理成功");
                }
            } catch (Exception e) {
                log.error("工程标段添加成功，但档案事件处理失败,触发异常：" + e.getMessage());
            }
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 修改标段工程管理
     * 
     * @param bmProject 标段工程管理
     * @return 结果
     */
    @Override
    public AjaxResult updateBmProject(BmProject bmProject)
    {
        if (bmProject == null || bmProject.getProId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        //首先根据工程名称去表中查询，看是否重复
        List<BmProject> projectList = bmProjectMapper.selectBmProjectByProName(bmProject);
        if (projectList.size() > 1) {
            return AjaxResult.error(HttpCodeEnum.NAME_DUPLICATE.getCode(), "工程名称或工程编码与库中重复");
        }
        if (projectList.size() == 1) {
            if (!Objects.equals(projectList.get(0).getProId(), bmProject.getProId())) {
                return AjaxResult.error(HttpCodeEnum.NAME_DUPLICATE.getCode(), "工程名称或工程编码与库中重复");
            }
        }
        //校验输入的经纬度是否合规
        /*if (bmProject.getLon() != null) {
            if (!bmProject.getLon().matches(MaterialConstants.LONGITUDE_PATTERN)){
                return AjaxResult.error(HttpCodeEnum.INVALID_LONGITUDE_FORMAT.getCode(), HttpCodeEnum.INVALID_LONGITUDE_FORMAT.getMsg());
            }
        }
        if (bmProject.getLat() != null) {
            if (!bmProject.getLat().matches(MaterialConstants.LATITUDE_PATTERN)){
                return AjaxResult.error(HttpCodeEnum.INVALID_LATITUDE_FORMAT.getCode(), HttpCodeEnum.INVALID_LATITUDE_FORMAT.getMsg());
            }
        }*/
        //判断手机号是否合法
        if (StringUtils.isNotBlank(bmProject.getTelphone()) && !PhoneUtil.isMobile(bmProject.getTelphone())) {
            return AjaxResult.error(HttpCodeEnum.INVALID_PHONE_FORMAT.getCode(), HttpCodeEnum.INVALID_PHONE_FORMAT.getMsg());
        }
        String telPhone = Sm4Utils.encrypt(bmProject.getTelphone());
        bmProject.setTelphone(telPhone);
        bmProject.setUpdateTime(DateUtils.getNowDate());
        bmProject.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
        int result = bmProjectMapper.updateBmProject(bmProject);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 删除标段工程管理信息
     * 
     * @param proId 标段工程管理主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteBmProjectByProId(Long proId)
    {
        if (proId == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        // 根据工程id查询该工程是否已新建协议，存在则不能删除
        BmAgreementInfo bmAgreementInfo = new BmAgreementInfo();
        bmAgreementInfo.setProjectId(proId);
        List<BmAgreementInfo> list = bmAgreementInfoMapper.selectBmAgreementInfoList(bmAgreementInfo);
        if (CollectionUtils.isNotEmpty(list)) {
            return AjaxResult.error("该工程已新建协议，不能删除");
        }
        int result = bmProjectMapper.deleteBmProjectByProId(proId);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }
}
