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

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.utils.encryption.Sm4Utils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.material.basic.domain.BmUnit;
import com.bonus.material.basic.mapper.BmUnitMapper;
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 org.springframework.stereotype.Service;
import com.bonus.material.basic.mapper.BmUnitPersonMapper;
import com.bonus.material.basic.domain.BmUnitPerson;
import com.bonus.material.basic.service.IBmUnitPersonService;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 往来单位管理Service业务层处理
 *
 * @author xsheng
 * @date 2024-09-26
 */
@Service
public class BmUnitPersonServiceImpl implements IBmUnitPersonService
{
    @Resource
    private BmUnitPersonMapper bmUnitPersonMapper;

    @Resource
    private RemoteConfig remoteConfig;

    @Resource
    private BmUnitMapper bmUnitMapper;

    @Resource
    private RemoteDeptService remoteDeptService;

    /**
     * 新增往来单位管理
     *
     * @param bmUnitPerson 往来单位管理
     * @return 结果
     */
    @Override
    public AjaxResult insertBmUnitPerson(BmUnitPerson bmUnitPerson)
    {
        int result = 0;
        if (CollectionUtils.isNotEmpty(bmUnitPerson.getUnitIdList())) {
            for (Long unitId : bmUnitPerson.getUnitIdList()) {
                bmUnitPerson.setCreateTime(DateUtils.getNowDate());
                bmUnitPerson.setUnitId(unitId);
                result += bmUnitPersonMapper.insertBmUnitPerson(bmUnitPerson);
            }
        }
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 删除往来单位管理信息
     *
     * @param bmUnitPerson 往来单位管理主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteBmUnitPersonByID(BmUnitPerson bmUnitPerson)
    {
        int result = bmUnitPersonMapper.deleteBmUnitPersonByID(bmUnitPerson);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 查询关联单位列表
     * @param bmUnitPerson
     * @return
     */
    @Override
    public List<BmUnit> selectBmUnitList(BmUnitPerson bmUnitPerson) {
        Long paramId = bmUnitPerson.getUserId();
        List<BmUnit> bmUnitList = bmUnitPersonMapper.selectBmUnitList(bmUnitPerson);
        Long[] array = bmUnitList.stream()
                // 提取 createBy 字段
                .map(BmUnit::getUserId)
                .map(createBy -> {
                    try {
                        // 转换为 Long
                        return createBy;
                    } catch (NumberFormatException e) {
                        // 处理转换失败的情况，可以返回 null
                        return null;
                    }
                })
                // 过滤掉 null 值
                .filter(value -> value != null)
                // 转换为 Long[] 数组
                .toArray(Long[]::new);
        Map<Long, String> nickNameMap = remoteConfig.getUserName(array);
        if (CollectionUtils.isNotEmpty(bmUnitList)) {
            bmUnitList.forEach(item -> {
                Long userId = item.getUserId();
                if (paramId != null && userId !=null) {
                    if( userId.equals(paramId)){
                        String nickName = nickNameMap.get(paramId);
                        item.setUserName(nickName != null ? nickName : " ");

                    }

                }else{
                    String nickName = nickNameMap.get(userId);
                    item.setUserName(nickName != null ? nickName : " ");

                }
                if(userId !=null){
                    item.setIsBind(bmUnitMapper.countBmUnitPersonByUnitId(item.getUnitId()) > 0 ? 1 : 0);
                }
                extracted(item);
            });
        }
        return bmUnitList;
    }

    @Override
    public int countBmUnitPersonByUnitId(Long unitId) {
        return bmUnitMapper.countBmUnitPersonByUnitId(unitId);
    }

    /**
     * 方法抽取
     * @param unit
     */
    private void extracted(BmUnit unit) {
        Map<String, String> labelMap = remoteConfig.getDictValue("bm_unit_type");
        if (unit.getUserId() != 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()));
        }*/
        if (StringUtils.isNotBlank(unit.getTelphone())) {
        unit.setTelphone(Sm4Utils.decrypt(unit.getTelphone()));
        }
        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());
            }
        }
    }
}
