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.enums.HttpCodeEnum;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.material.basic.mapper.BmUnitMapper;
import com.bonus.material.basic.domain.BmUnit;
import com.bonus.material.basic.service.IBmUnitService;

import javax.annotation.Resource;

/**
 * 往来单位管理Service业务层处理
 * 
 * @author xsheng
 * @date 2024-09-26
 */
@Service
@Slf4j
public class BmUnitServiceImpl implements IBmUnitService 
{
    @Autowired
    private BmUnitMapper bmUnitMapper;

    @Resource
    private RemoteConfig remoteConfig;

    @Resource
    private RemoteDeptService remoteDeptService;


    /**
     * 查询往来单位管理
     * 
     * @param unitId 往来单位管理主键
     * @return 往来单位管理
     */
    @Override
    public BmUnit selectBmUnitByUnitId(Long unitId)
    {
        BmUnit unit = bmUnitMapper.selectBmUnitByUnitId(unitId);
        extracted(unit);
        return unit;
    }

    /**
     * 查询往来单位管理列表
     * 
     * @param bmUnit 往来单位管理
     * @return 往来单位管理
     */
    @Override
    public List<BmUnit> selectBmUnitList(BmUnit bmUnit)
    {
        List<BmUnit> bmUnitList = bmUnitMapper.selectBmUnitList(bmUnit);
        if (CollectionUtils.isNotEmpty(bmUnitList)) {
            bmUnitList.forEach(item -> {
                extracted(item);
                });
        }
        return bmUnitList;
    }

    /**
     * 方法抽取
     * @param unit
     */
    private void extracted(BmUnit unit) {
        Map<String, String> labelMap = remoteConfig.getDictValue("bm_unit_type");
        if (unit.getUnitId() != null) {
            //根据单位id去人员绑定中查询是否绑定，赋值绑定状态
            unit.setIsBind(bmUnitMapper.countBmUnitPersonByUnitId(unit.getUnitId()) > 0 ? 1 : 0);
        }
        if (unit.getTypeId() != null) {
            unit.setTypeName(labelMap.get(unit.getTypeId().toString()) == null ? "" : labelMap.get(unit.getTypeId().toString()));
        }
        AjaxResult ajaxResult = remoteDeptService.getInfo(unit.getDeptId(), 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);
                unit.setDeptName(sysDept.getDeptName() == null ? "" : sysDept.getDeptName());
            }
        }
    }


    /**
     * 新增往来单位管理
     * 
     * @param bmUnit 往来单位管理
     * @return 结果
     */
    @Override
    public AjaxResult insertBmUnit(BmUnit bmUnit)
    {
        //根据单位名称查询去重
        BmUnit unit = bmUnitMapper.selectBmUnitByProName(bmUnit.getUnitName());
        if (unit != null) {
            return AjaxResult.error(HttpCodeEnum.NAME_DUPLICATE.getCode(), HttpCodeEnum.NAME_DUPLICATE.getMsg());
        }
        //判断手机号是否合法
        if (StringUtils.isNotBlank(bmUnit.getTelphone()) && !PhoneUtil.isMobile(bmUnit.getTelphone())) {
            return AjaxResult.error(HttpCodeEnum.INVALID_PHONE_FORMAT.getCode(), HttpCodeEnum.INVALID_PHONE_FORMAT.getMsg());
        }
        bmUnit.setCreateTime(DateUtils.getNowDate());
        bmUnit.setCreateBy(SecurityUtils.getUserId().toString());
        int result = bmUnitMapper.insertBmUnit(bmUnit);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 修改往来单位管理
     * 
     * @param bmUnit 往来单位管理
     * @return 结果
     */
    @Override
    public AjaxResult updateBmUnit(BmUnit bmUnit)
    {
        //根据单位名称查询去重
        BmUnit unit = bmUnitMapper.selectBmUnitByProName(bmUnit.getUnitName());
        if (unit != null) {
            if (!Objects.equals(unit.getUnitId(), bmUnit.getUnitId())) {
                return AjaxResult.error(HttpCodeEnum.NAME_DUPLICATE.getCode(), HttpCodeEnum.NAME_DUPLICATE.getMsg());
            }
        }
        //判断手机号是否合法
        if (StringUtils.isNotBlank(bmUnit.getTelphone()) && !PhoneUtil.isMobile(bmUnit.getTelphone())) {
            return AjaxResult.error(HttpCodeEnum.INVALID_PHONE_FORMAT.getCode(), HttpCodeEnum.INVALID_PHONE_FORMAT.getMsg());
        }
        bmUnit.setUpdateTime(DateUtils.getNowDate());
        bmUnit.setUpdateBy(SecurityUtils.getUserId().toString());
        int result = bmUnitMapper.updateBmUnit(bmUnit);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 批量删除往来单位管理
     * 
     * @param unitIds 需要删除的往来单位管理主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteBmUnitByUnitIds(Long[] unitIds)
    {
        int result = bmUnitMapper.deleteBmUnitByUnitIds(unitIds);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 删除往来单位管理信息
     * 
     * @param unitId 往来单位管理主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteBmUnitByUnitId(Long unitId)
    {
        //先查看往来单位是否被绑定，绑定则不能删除
        if (bmUnitMapper.countBmUnitPersonByUnitId(unitId) > 0) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), "该单位还绑定相关人员，无法删除");
        }
        int result = bmUnitMapper.deleteBmUnitByUnitId(unitId);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }
}
