package com.pusong.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pusong.business.domain.PsContractCompany;
import com.pusong.business.domain.PsContractInfo;
import com.pusong.business.domain.PsContractPay;
import com.pusong.business.domain.bo.PsCompanyQueryBo;
import com.pusong.business.domain.bo.PsContractBusinessBo;
import com.pusong.business.enums.ApproverTypeEnum;
import com.pusong.business.enums.PayStatusEnum;
import com.pusong.business.mapper.PsContractCompanyMapper;
import com.pusong.business.mapper.PsContractInfoMapper;
import com.pusong.business.service.approver.ApproverContainer;
import com.pusong.business.service.approver.ApproverService;
import com.pusong.common.core.exception.ServiceException;
import com.pusong.common.core.utils.MapstructUtils;
import com.pusong.common.core.utils.StringUtils;
import com.pusong.common.mybatis.core.page.TableDataInfo;
import com.pusong.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.pusong.business.domain.bo.PsCompanyInfoBo;
import com.pusong.business.domain.vo.PsCompanyInfoVo;
import com.pusong.business.domain.PsCompanyInfo;
import com.pusong.business.mapper.PsCompanyInfoMapper;
import com.pusong.business.service.IPsCompanyInfoService;

import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

/**
 * 公司信息Service业务层处理
 *
 * @author wls
 * @date 2024-07-29
 */
@RequiredArgsConstructor
@Service
public class PsCompanyInfoServiceImpl implements IPsCompanyInfoService {

    private final PsCompanyInfoMapper baseMapper;
    private final PsContractCompanyMapper contractCompanyMapper;
    private final PsContractInfoMapper contractInfoMapper;
    @Resource
    private final ApproverContainer container;

    /**
     * 查询公司信息
     *
     * @param id 主键
     * @return 合同基本信息
     */
    @Override
    public PsCompanyInfoVo queryById(Long id){
        QueryWrapper<PsCompanyInfo> lqw =  new QueryWrapper<PsCompanyInfo>();
        lqw.eq("com.id", id);
        List<PsCompanyInfoVo> psCompanyInfoVos = baseMapper.selectVoCustomManager(lqw, null);
        return psCompanyInfoVos.isEmpty() ? null : psCompanyInfoVos.get(0);
    }
    @Override
    public PsCompanyInfoVo queryVoAndProxyById(Long id, String contractCode){
        QueryWrapper<PsCompanyInfo> lqw =  new QueryWrapper<PsCompanyInfo>();
        lqw.eq("com.id", id);
        List<PsCompanyInfoVo> psCompanyInfoVos = baseMapper.selectVoCustomManager(lqw, contractCode);
        return psCompanyInfoVos.isEmpty() ? null : psCompanyInfoVos.get(0);
    }
    @Override
    public List<PsCompanyInfoVo> queryByIds(List<Long> ids){
        LambdaQueryWrapper<PsCompanyInfo> lqw = Wrappers.lambdaQuery();
        lqw.in(PsCompanyInfo::getId, ids);
        return baseMapper.selectVoCustomManager(lqw, null);
    }
    @Override
    public List<PsCompanyInfoVo> queryVoAndProxyByIds(List<Long> ids, String contractCode){
        QueryWrapper<PsCompanyInfo> lqw =  new QueryWrapper<PsCompanyInfo>();
        lqw.in("com.id", ids);
        return baseMapper.selectVoCustomManager(lqw, contractCode);
    }


    /**
     * 查询符合条件的公司信息列表
     *
     * @param bo 查询条件
     * @return 公司信息列表
     */
    @Override
    public List<PsCompanyInfoVo> queryList(PsCompanyInfoBo bo) {
        LambdaQueryWrapper<PsCompanyInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询符合条件的公司信息列表
     *
     * @param bo 查询条件
     * @return 公司信息列表
     */
    public TableDataInfo<PsCompanyInfoVo> queryPageList(PsCompanyQueryBo bo, PageQuery pageQuery){
        QueryWrapper<PsCompanyInfo> lqw = Wrappers.query();
        lqw.exists(StringUtils.isNotBlank(bo.getCustomManagerName()),"select 1 from sys_user su where su.user_id = cus.custom_manager and su.nick_name like '%"+bo.getCustomManagerName()+"%'");
        lqw.eq(bo.getId() != null,"com.id",bo.getId());
        lqw.like(bo.getCustomName() != null,"cus.custom_name",bo.getCustomName());
        lqw.like(bo.getCustomMobile() != null,"cus.custom_mobile",bo.getCustomMobile());
        lqw.like(bo.getCompanyName() != null,"com.company_name",bo.getCompanyName());
        lqw.like(bo.getCompanyName() != null,"com.company_name",bo.getCompanyName());
        lqw.like(bo.getCustomIntroducer() != null,"cusi.custom_name",bo.getCustomIntroducer());
        Page<PsCompanyInfoVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    /**
     * 查询符合条件的公司信息列表
     *
     * @param bo 查询条件
     * @return 公司信息列表
     */
    public TableDataInfo<PsCompanyInfoVo> queryServiceCompany(PsCompanyQueryBo bo, PageQuery pageQuery){
        QueryWrapper<PsCompanyInfo> lqw = Wrappers.query();
        lqw.exists(StringUtils.isNotBlank(bo.getCustomManagerName()),"select 1 from sys_user su where su.user_id = cus.custom_manager and su.nick_name like '%"+bo.getCustomManagerName()+"%'");
        lqw.eq(bo.getId() != null,"com.id", bo.getId());
        lqw.eq("com.company_type", "2");
        lqw.like(bo.getCustomName() != null,"cus.custom_name",bo.getCustomName());
        lqw.like(bo.getCustomMobile() != null,"cus.custom_mobile",bo.getCustomMobile());
        lqw.like(bo.getCompanyName() != null,"com.company_name",bo.getCompanyName());
        lqw.eq(bo.getServiceStatus() != null,"com.service_status",bo.getServiceStatus());
        lqw.exists(StringUtils.isNotBlank(bo.getUserName()),"select 1 from sys_user fsu where fsu.user_id = cf.user_id and fsu.nick_name like '%"+bo.getUserName()+"%'");

        StringBuilder sql = new StringBuilder("select 1 from ps_contract_business cb where cb.company_id = com.id ");
        if (bo.getType() == 2){  //非托管
            sql.append("and business_type != '2'");
        }else if (bo.getType() == 3){   //托管代账
            sql.append("and business_type = '2' and is_proxy = '1'");
        }else if (bo.getType() == 4){ //托管不代账
            sql.append("and business_type = '2' and is_proxy = '2'");
        }
        lqw.exists(bo.getType() != 1, sql.toString());
        Page<PsCompanyInfoVo> result = baseMapper.selectPageList2(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    public TableDataInfo<PsCompanyInfoVo> searchServiceCompany(String keyWorld){
        if (keyWorld == null || keyWorld.equals("")){
            return TableDataInfo.build();
        }
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageSize(10);
        QueryWrapper<PsCompanyInfo> lqw = Wrappers.query();
        lqw.like("company_name", keyWorld);
        lqw.eq("company_type", "2");
        Page<PsCompanyInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    private LambdaQueryWrapper<PsCompanyInfo> buildQueryWrapper(PsCompanyInfoBo bo) {
        LambdaQueryWrapper<PsCompanyInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, PsCompanyInfo::getId, bo.getId());
        lqw.eq(bo.getCustomId() != null, PsCompanyInfo::getCustomId, bo.getCustomId());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyName()), PsCompanyInfo::getCompanyName, bo.getCompanyName());
        lqw.eq( PsCompanyInfo::getDelFlag, "0");
        return lqw;
    }

    /**
     * 新增公司信息
     *
     * @param bo 公司信息
     * @return 是否新增成功
     */
    @Override
    public Boolean saveBo(PsCompanyInfoBo bo) {
//        if(bo.getId() == null){
//            //公司名称唯一
//            PsCompanyInfoBo query = new PsCompanyInfoBo();
//            query.setCompanyName(bo.getCompanyName());
//            query.setCustomId(bo.getCustomId());
//            List<PsCompanyInfoVo> list = this.queryList(bo);
//            //如果存在重复名称则修改
//            if(CollectionUtils.isNotEmpty(list)){bo.setId(list.get(0).getId());}
//        }
        //公司类型默认签约公司
        PsCompanyInfo add = MapstructUtils.convert(bo, PsCompanyInfo.class);
        //新增时公司类型默认为签约公司
        add.setCompanyType(add.getId() == null && StringUtils.isBlank(add.getCompanyType()) ? "1" : add.getCompanyType());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insertOrUpdate(add);
        if (flag) {
            bo.setId(add.getId());
            if(bo.getBusinessList() != null){//装填服务类型的公司id
                for (PsContractBusinessBo psContractBusinessBo : bo.getBusinessList()) {
                    psContractBusinessBo.setCompanyId(add.getId());
                }
            }
        }
        return flag;
    }

    /**
     * 保存公司合同关联表
     */
    public void saveContractCompany(List<PsCompanyInfoBo> list,String contractCode ){
        contractCompanyMapper.delete(Wrappers.<PsContractCompany>lambdaQuery().eq(PsContractCompany::getContractCode, contractCode));
        List <PsContractCompany> saveList = new ArrayList<>();
        for(PsCompanyInfoBo bo:list){
            PsContractCompany contractCompany = new PsContractCompany();
            contractCompany.setContractCode(contractCode);
            contractCompany.setCompanyId(bo.getId());
            saveList.add(contractCompany);
        }
        contractCompanyMapper.insertBatch(saveList);
    }
    /**
     * 批量新增公司信息
     *
     * @param bos 公司信息
     * @return 是否新增成功
     */
    public Boolean saveBatchBo(List<PsCompanyInfoBo> bos){
        List<PsCompanyInfo> adds = MapstructUtils.convert(bos, PsCompanyInfo.class);
        boolean flag = baseMapper.insertOrUpdateBatch(adds);
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PsCompanyInfo info){
        //新增公司时
        if(info.getId() == null && StringUtils.equals(info.getCompanyType(),"2")){
            Long count = baseMapper.selectCount(Wrappers.<PsCompanyInfo>lambdaQuery().eq(PsCompanyInfo::getCompanyType, "2")
                    .eq(PsCompanyInfo::getCompanyName, info.getCompanyName()).eq(PsCompanyInfo::getCustomerNum, info.getCustomerNum()));
            if(count>0){throw new ServiceException("公司："+info.getCompanyName()+";纳税人识别号："+info.getCustomerNum()+" 已存在，请进行选择后重新提交");}
        }
        //TODO 修改公司时需要校验公司下是否有合同状态
    }

    /**
     * 校验并批量删除公司信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            List<PsContractInfo> list = contractInfoMapper.selectList(Wrappers.<PsContractInfo>lambdaQuery().in(PsContractInfo::getCompanyId, ids).eq(PsContractInfo::getDelFlag, "0"));
            if(CollectionUtils.isNotEmpty(list)){throw new ServiceException("删除公司失败，已有合同使用");}
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据合同编码查询服务公司信息
     * @param controctCode
     * @return
     */
    public List<PsCompanyInfoVo> getServiceCompany(String controctCode){
        QueryWrapper<PsCompanyInfoVo> wq = Wrappers.<PsCompanyInfoVo>query().eq("pcc.del_flag", "0").eq("bus.del_flag","0")
                .eq("det.del_flag","0").eq("pcc.contract_code", controctCode);
        List<PsCompanyInfoVo> list = baseMapper.selectServiceCompanyList(wq);
        for (PsCompanyInfoVo psCompanyInfoVo : list) {
            psCompanyInfoVo.setStartServiceDate(psCompanyInfoVo.getBusinessVoList().get(0).getStartDate());
            psCompanyInfoVo.setEndServiceDate(psCompanyInfoVo.getBusinessVoList().get(0).getEndDate());
            psCompanyInfoVo.setIsOld(psCompanyInfoVo.getBusinessVoList().get(0).getIsOld());
            psCompanyInfoVo.setIsProxy(psCompanyInfoVo.getBusinessVoList().get(0).getIsProxy());
        }
        return list;
    }

    /**
     * 终止代账合作
     *
     * @param serviceCompanyId
     */
    public void terminationService(Long serviceCompanyId) {
        //发起审批
        ApproverService service = container.getService(ApproverTypeEnum.STOPACCOUNT.getCode());
        service.apply(serviceCompanyId + "", "",null, null);
    }
}
