package com.trade.client.enterprise.companyrelated.service.impl;

import javax.annotation.Resource;

import com.github.pagehelper.PageInfo;
import com.trade.client.enterprise.companyrelated.service.CBizEntityRelatedService;
import com.trade.service.enterprise.companyrelated.domain.vo.BizEntityRelatedSearch;
import com.trade.service.enterprise.companyrelated.service.BizEntityRelatedService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.common.utils.StringUtils;
import com.trade.common.utils.bean.BeanUtils;
import com.trade.service.enterprise.companyrelated.domain.BizEntityRelated;
import com.trade.service.enterprise.companyrelated.domain.BizEntityRelatedPerson;
import com.trade.service.enterprise.companyrelated.domain.vo.BizEntityRelatedVO;
import com.trade.service.enterprise.companyrelated.mapper.BizEntityRelatedMapper;
import com.trade.service.enterprise.companyrelated.service.BizEntityRelatedPersonService;

import java.util.List;

/**
 * <p>
 * 关系企业信息 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-05-28
 */
@Service
public class CBizEntityRelatedServiceImp extends ServiceImpl<BizEntityRelatedMapper, BizEntityRelated> implements CBizEntityRelatedService {

    @Resource
    private BizEntityRelatedService bizEntityRelatedService;
    @Resource
    private BizEntityRelatedPersonService bizEntityRelatedPersonService;

    @Override
    @Transactional
    public void add(BizEntityRelatedVO addBizEntity) {
        // 参数校验
        preCheckParams(addBizEntity);
        // 保存关系企业信息
        BizEntityRelated bizEntityRelated = new BizEntityRelated();
        BeanUtils.copyProperties(addBizEntity, bizEntityRelated);
        this.save(bizEntityRelated);
        for (BizEntityRelatedPerson relatedPerson : addBizEntity.getRelatedPersons()) {
            relatedPerson.setEntityId(bizEntityRelated.getId());
            bizEntityRelatedPersonService.save(relatedPerson);
        }
    }

    /**
     * 参数校验
     * 
     * @param addBizEntity 关系企业信息
     */
    private void preCheckParams(BizEntityRelatedVO addBizEntity) {
        BizEntityRelated exist = getBaseMapper().getByUserIdAndCertNo(addBizEntity.getUserId(),
                addBizEntity.getCertNo());
        if (exist != null) {
            throw new ServiceException("证件号码已存在", HttpStatus.BAD_REQUEST);
        }
        if ("CN".equals(addBizEntity.getCountry())) {
            if (StringUtils.isAllEmpty(addBizEntity.getIndustry(), addBizEntity.getRegisteredCapital(),
                    addBizEntity.getRegisteredAddress()) || null == addBizEntity.getEstablishDate()) {
                throw new ServiceException("请填写完整信息", HttpStatus.BAD_REQUEST);
            }
            // 大陆校验手机号
            if (!StringUtils.isChinaPhone(addBizEntity.getContactMobile())) {
                throw new ServiceException("请输入正确的手机号", HttpStatus.BAD_REQUEST);
            }
            addBizEntity.getRelatedPersons().forEach(relatedPerson -> {
                if (StringUtils.isEmpty(relatedPerson.getIdNo())) {
                    throw new ServiceException("请填写相关人员证件号码", HttpStatus.BAD_REQUEST);
                }
                // 大陆校验手机号
                if (!StringUtils.isChinaPhone(relatedPerson.getMobile())) {
                    throw new ServiceException("相关人员手机号格式不正确", HttpStatus.BAD_REQUEST);
                }
            });
        }
    }

    @Override
    public void update(BizEntityRelatedVO addBizEntity) {
        // 请注意，修改不支持暂存功能，无需简单功能复杂化
        preCheckParams(addBizEntity);
        BizEntityRelated bizEntityRelated = this.getById(addBizEntity.getId());
        if (bizEntityRelated == null) {
            throw new ServiceException("关系企业信息不存在", HttpStatus.BAD_REQUEST);
        }
        BeanUtils.copyProperties(addBizEntity, bizEntityRelated);
        this.updateById(bizEntityRelated);
        // 由于是逻辑删除，这里多次修改可能会导致多条相同数据，所以选择更新，让前端传id
        // bizEntityRelatedPersonService
        // .remove(new QueryWrapper<BizEntityRelatedPerson>().eq("entity_id", addBizEntity.getId()));
        for (BizEntityRelatedPerson relatedPerson : addBizEntity.getRelatedPersons()) {
            // relatedPerson.setEntityId(addBizEntity.getId());
            bizEntityRelatedPersonService.updateById(relatedPerson);
        }
    }

    @Override
    public void deleteByBizEntityId(Long bizEntityId) {
        // 客户生效的融资业务或贸易合同中涉及的关系企业不可删除。 贸易合同中涉及的企业是怎么界定的？？？？
        // todo 校验是否存在在融资
        BizEntityRelated bizEntityRelated = this.getById(bizEntityId);
        if (bizEntityRelated != null) {
            bizEntityRelatedPersonService
                    .remove(new QueryWrapper<BizEntityRelatedPerson>().eq("entity_id", bizEntityId));
            this.removeById(bizEntityId);
        }
    }

    @Override
    public PageInfo<BizEntityRelated> queryListBySearch(BizEntityRelatedSearch search) {
        return bizEntityRelatedService.queryListBySearch(search);
    }

    @Override
    public List<BizEntityRelated> getRelatedListByUserId(Long userId) {
        return bizEntityRelatedService.getRelatedListByUserId(userId);
    }

    @Override
    public BizEntityRelatedVO getByBizEntityId(Long bizEntityId) {
        return bizEntityRelatedService.getByBizEntityId(bizEntityId);
    }
}
