package com.fjhx.sale.service.intermediate.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.entity.corporation.po.Corporation;
import com.fjhx.common.service.corporation.CorporationService;
import com.fjhx.common.utils.Assert;
import com.fjhx.customer.service.customer.CustomerService;
import com.fjhx.flow.service.flow.FlowExampleService;
import com.fjhx.sale.entity.contract.vo.ContractPdfInfoVo;
import com.fjhx.sale.entity.contract.vo.ContractVo;
import com.fjhx.sale.entity.documents.po.Documents;
import com.fjhx.sale.entity.intermediate.dto.IntermediateContractDto;
import com.fjhx.sale.entity.intermediate.dto.IntermediateContractSelectDto;
import com.fjhx.sale.entity.intermediate.po.IntermediateContract;
import com.fjhx.sale.entity.intermediate.vo.IntermediateContractVo;
import com.fjhx.sale.mapper.intermediate.IntermediateContractMapper;
import com.fjhx.sale.service.contract.ContractService;
import com.fjhx.sale.service.documents.DocumentsService;
import com.fjhx.sale.service.intermediate.IntermediateContractService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 中间合同 服务实现类
 * </p>
 *
 * @author
 * @since 2023-06-28
 */
@Service
public class IntermediateContractServiceImpl extends ServiceImpl<IntermediateContractMapper, IntermediateContract> implements IntermediateContractService {

    @Autowired
    private DocumentsService documentsService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CorporationService corporationService;
    @Autowired
    private FlowExampleService flowExampleService;

    @Override
    public Page<IntermediateContractVo> getPage(IntermediateContractSelectDto dto) {
        if(ObjectUtil.isEmpty(dto.getIsSet())){
            throw new ServiceException("参数异常");
        }
        IWrapper<IntermediateContract> wrapper = getWrapper();
        //买方公司过滤
        wrapper.orderByDesc("d.create_time");
        wrapper.like(StringUtils.isNotEmpty(dto.getKeyword()),"c.code", dto.getKeyword());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBuyCorporationId()),"c.buy_corporation_id", dto.getBuyCorporationId());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getSellCorporationId()),"c.sell_corporation_id", dto.getSellCorporationId());
        Page<IntermediateContractVo> page;
        if(dto.getIsSet()==1){//未创建
            String ids = this.getAllIds();
            if(StringUtils.isNotEmpty(ids)){
                wrapper.notIn("d.id",Arrays.asList(ids.split(",")));
            }
            //卖方公司过滤
            page = this.baseMapper.getPage(dto.getPage(), wrapper);
        }else{//已创建
            wrapper.groupBy("t1.id");
            page = this.baseMapper.getPage2(dto.getPage(), wrapper);
        }

        List<IntermediateContractVo> records = page.getRecords();
        //赋值原买方公司名称 客户
        customerService.attributeAssign(records, IntermediateContractVo::getBuyCorporationId, (item, customer) -> {
            item.setBuyCorporationName(customer.getName());
        });
        //赋值原卖方公司名称 多公司
        corporationService.attributeAssign(records, IntermediateContractVo::getSellCorporationId, (item, corporation) -> {
            item.setSellCorporationName(corporation.getName());
        });
        // 赋值流程id
        List<IntermediateContractVo> collect = records.stream().filter(item -> Objects.isNull(item.getFlowId())).collect(Collectors.toList());
        flowExampleService.setFlowId(collect, 2,IntermediateContractVo::setFlowId);
        UserUtil.assignmentNickName(records, IntermediateContractVo::getCreateUser, IntermediateContractVo::setUserName);
        return page;
    }

    @Override
    public IntermediateContractVo detail(Long id) {
        IntermediateContract IntermediateContract = this.getById(id);
        IntermediateContractVo result = BeanUtil.toBean(IntermediateContract, IntermediateContractVo.class);
        return result;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void del(Long id) {
        this.removeById(id);
    }

    @Override
    public void edit(IntermediateContractDto intermediateContractDto) {
        intermediateContractDto.setId(null);
        Assert.notEmpty(intermediateContractDto.getDocumentsIds(), "单证id不能为空");
        IntermediateContract intermediateContract = this.getOne(q -> q.eq(IntermediateContract::getDocumentsIds, intermediateContractDto.getDocumentsIds()));
        if (ObjectUtil.isNotEmpty(intermediateContract)) {
            //编辑 赋值id
            intermediateContractDto.setId(intermediateContract.getId());
        }
        this.saveOrUpdate(intermediateContractDto);
    }

    /**
     * 获取中间合同历史联系方式
     */
    @Override
    public List<IntermediateContractVo> contactList(IntermediateContractDto dto) {
        IWrapper<IntermediateContract> wrapper = IWrapper.getWrapper();
        //根据卖方联系人名称/联系方式过滤
        if (ObjectUtil.isNotEmpty(dto.getSellContactName())) {
            wrapper.or().like(IntermediateContract::getSellContactName, dto.getSellContactName());
            wrapper.groupBy("sell_contact_name");
        }
        if (ObjectUtil.isNotEmpty(dto.getSellContactNumber())) {
            wrapper.or().like(IntermediateContract::getSellContactNumber, dto.getSellContactNumber());
            wrapper.groupBy("sell_contact_number");
        }
        //根据买方联系人名称/联系方式过滤
        if (ObjectUtil.isNotEmpty(dto.getBuyContactName())) {
            wrapper.or().like(IntermediateContract::getBuyContactName, dto.getBuyContactName());
            wrapper.groupBy("buy_contact_name");
        }
        if (ObjectUtil.isNotEmpty(dto.getBuyContactNumber())) {
            wrapper.or().like(IntermediateContract::getBuyContactNumber, dto.getBuyContactNumber());
            wrapper.groupBy("buy_contact_number");
        }
        List<IntermediateContractVo> list = baseMapper.contactList(wrapper);
        //赋值买方名称
        corporationService.attributeAssign(list, IntermediateContractVo::getBuyCorporationId, (item, corporation) -> {
            item.setBuyCorporationName(corporation.getName());
        });
        //赋值卖方名称
        corporationService.attributeAssign(list, IntermediateContractVo::getSellCorporationId, (item, corporation) -> {
            item.setSellCorporationName(corporation.getName());
        });
        return list;
    }

    /**
     * 获取打印信息
     *
     * @return
     */
    @Override
    public IntermediateContract getPrintInfo(IntermediateContractDto dto) {
        Assert.notEmpty(dto.getId(), "参数异常");
        IntermediateContract in = this.getById(dto.getId());
        if(ObjectUtil.isEmpty(in)){
            throw new ServiceException("合同不存在");
        }
        IntermediateContractVo vo = new IntermediateContractVo();
        BeanUtils.copyProperties(in,vo);
        //赋值买方卖方公司名称
        List<Long> corporationIds = Arrays.asList(in.getBuyCorporationId(), in.getSellCorporationId());
        Map<Long, Corporation> corporationMap = corporationService.mapKEntity(Corporation::getId, q -> q.in(Corporation::getId, corporationIds));
        Corporation buyCorporation = corporationMap.get(in.getBuyCorporationId());
        //赋值买方信息
        vo.setBuyContactNumber(in.getBuyContactNumber());
        vo.setBuyContactName(in.getBuyContactName());
        if (ObjectUtil.isNotEmpty(buyCorporation)) {
            vo.setBuyCorporationName(buyCorporation.getNameEn());
            //赋值买方国家省市详细地址信息
            vo.setBuyCountryName(buyCorporation.getCountryEnStr());
            vo.setBuyProvinceName(buyCorporation.getProvinceEnStr());
            vo.setBuyCityName(buyCorporation.getCityEnStr());
            vo.setBuyDetailedAddress(buyCorporation.getAddressEn());
        }
        Corporation sellCorporation = corporationMap.get(in.getSellCorporationId());
        //赋值卖方信息
        vo.setSellContactNumber(in.getSellContactNumber());
        vo.setSellContactName(in.getSellContactName());
        if (ObjectUtil.isNotEmpty(sellCorporation)) {
            vo.setSellCorporationNameEn(sellCorporation.getNameEn());
            //赋值卖方国家省市详细地址信息
            vo.setSellCountryName(sellCorporation.getCountryEnStr());
            vo.setSellProvinceName(sellCorporation.getProvinceEnStr());
            vo.setSellCityName(sellCorporation.getCityEnStr());
            vo.setSellDetailedAddress(sellCorporation.getAddressEn());
        }
        //查询最新的一条单证信息
        Documents documents = documentsService.getOne(Wrappers.<Documents>query().lambda().in(Documents::getId,Arrays.asList(in.getDocumentsIds().split(","))).orderByDesc(Documents::getCreateTime).last("limit 1"));
        Assert.notEmpty(documents, "查询不到单证信息");
        List<Documents> documentsList = documentsService.list(Wrappers.<Documents>query().lambda().in(Documents::getId,Arrays.asList(in.getDocumentsIds().split(","))));
        //查询合同
        Map<String,Object> contractMap = contractService.getDocumentaryPdf(documents.getContractId(),documentsList.stream().map(Documents::getContractId).collect(Collectors.toList()));
        vo.setContractMap(contractMap);
        return vo;
    }

    /**
     * 获取所有单证ID
     * @return
     */
    @Override
    public String getAllIds() {
        return baseMapper.getAllIds();
    }

}
