package com.glxp.mipsdl.service.thrsys;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.glxp.mipsdl.config.ThirdSysConfig;
import com.glxp.mipsdl.dao.basic.BasicCorpDao;
import com.glxp.mipsdl.dao.thrsys.ThrCorpDao;
import com.glxp.mipsdl.entity.basic.BasicCorpEntity;
import com.glxp.mipsdl.entity.thrsys.ThrCorpEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 第三方系统往来单位Service
 */
@Slf4j
@Service
public class ThrCorpService {

    @Resource
    private ThirdSysConfig thirdSysConfig;
    @Resource
    private BasicCorpDao basicCorpDao;
    @Resource
    ThrCorpDao thrCorpDao;

    /**
     * 查询第三方系统的往来单位
     *
     * @param corpId
     * @return
     */
    public ThrCorpEntity getThrCorp(String corpId) {
        if (StrUtil.isNotBlank(corpId)) {
            ThrCorpEntity thrCorpEntity = new ThrCorpEntity();
            BasicCorpEntity basicCorpEntity = basicCorpDao.selectOne(new LambdaQueryWrapper<BasicCorpEntity>()
                    .eq(BasicCorpEntity::getErpId, corpId));
            try {
                //获取本服务配置的thirdId对应的第三方系统的往来单位名称和编码
//                String thirdCorpId = (String) ReflectUtil.getFieldValue(basicCorpEntity, basicCorpEntity.getClass().getField(thirdSysConfig.getThirdId()));
//                String thirdCorpName = (String) ReflectUtil.getFieldValue(basicCorpEntity, basicCorpEntity.getClass().getField(thirdSysConfig.getThirdName()));
                thrCorpEntity.setUnitId(basicCorpEntity.getThirdId());
                thrCorpEntity.setName(basicCorpEntity.getName());
//                log.info("获取第三方系统往来单位成功，往来单位编码：{}，第三方系统往来单位编码：{}，名称：{}", corpId, thirdCorpId, thirdCorpName);
                return thrCorpEntity;
            } catch (Exception e) {
                log.error("查询第三方系统往来单位异常，往来单位编码：{}, 异常信息：{}", corpId, e);
            }
        }
        log.info("查询第三方往来单位失败，往来单位编码参数为空");
        return null;
    }


    public ThrCorpEntity getThrCorpByName(String corpName) {
        if (StrUtil.isEmpty(corpName))
            return null;
        ThrCorpEntity thrCorpEntity = thrCorpDao.selectOne(new QueryWrapper<ThrCorpEntity>().like("name", corpName).last("limit 1"));
        return thrCorpEntity;
    }


}
