package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.hygf.api.entity.FinancingInfo;
import com.yeejoin.amos.boot.module.hygf.api.entity.FinancingRegional;
import com.yeejoin.amos.boot.module.hygf.api.entity.PeasantHousehold;
import com.yeejoin.amos.boot.module.hygf.api.mapper.FinancingRegionalMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IFinancingRegionalService;
import com.yeejoin.amos.boot.module.hygf.api.dto.FinancingRegionalDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

/**
 * 融资机构区域公司绑定表服务实现类
 *
 * @author system_generator
 * @date 2024-09-19
 */
@Service
public class FinancingRegionalServiceImpl extends BaseService<FinancingRegionalDto,FinancingRegional,FinancingRegionalMapper> implements IFinancingRegionalService {
    @Autowired
    private  FinancingInfoServiceImpl financingInfoService;
    /**
     * 分页查询
     */
    public Page<FinancingRegional> queryForFinancingRegionalPage(int current,int size,String regionalCompaniesName, String province)   {
        Page<FinancingRegional> page = new Page<>();
        PageHelper.startPage(current,size);
        List<FinancingRegional> list = this.getBaseMapper().queryDataForPage(regionalCompaniesName,province);

        PageInfo<FinancingRegional> pageInfo = new PageInfo<>(list);
        page.setSize(pageInfo.getSize());
        page.setCurrent(pageInfo.getPageNum());
        page.setTotal(pageInfo.getTotal());
        page.setRecords(list);

        return page;
    }

    /**
     * 列表查询 示例
     */
    public List<FinancingRegionalDto> queryForFinancingRegionalList()   {
        return this.queryForList("" , false);
    }

    public void saveModel(FinancingRegionalDto model) {


        List<String> ids = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> exitNames = new ArrayList<>();
        ids.addAll(model.getFinancing());
        ids.addAll(model.getRegionalCompanies());

        List<FinancingRegional> models = new ArrayList<>();

        List<Map<String, Object>> orgInfo = financingInfoService.getBaseMapper().selectCompany(ids);
        model.getFinancing().forEach(f->{
            List<Map<String, Object>> map = orgInfo.stream().filter(b ->String.valueOf(b.get("SEQUENCE_NBR")) .equals(f)).collect(Collectors.toList());
            map.forEach(a->{
              names.add(a.get("COMPANY_NAME").toString());
            });
        });

        model.getRegionalCompanies().forEach(e->{
            FinancingRegional financingRegional = new FinancingRegional();
            financingRegional.setFinancingId(String.join(",",String.join(",",model.getFinancing())));
            financingRegional.setFinancingName(String.join(",",names));

            orgInfo.stream().filter(b->String.valueOf(b.get("SEQUENCE_NBR")).equals(e)).forEach(a->{
                financingRegional.setRegionalCompaniesSeq(String.valueOf(a.get("SEQUENCE_NBR")));
                financingRegional.setRegionalCompaniesName(a.get("COMPANY_NAME").toString());
                financingRegional.setRegionalCompaniesCode(a.get("ORG_CODE").toString());
            });

            LambdaQueryWrapper<FinancingRegional> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FinancingRegional::getRegionalCompaniesSeq,e);
            wrapper.eq(BaseEntity::getIsDelete,0);
            List<FinancingRegional> financingRegionals = this.getBaseMapper().selectList(wrapper);
            if (CollectionUtil.isNotEmpty(financingRegionals)){
                exitNames.add(financingRegional.getRegionalCompaniesName());
            }
            financingRegional.setProvince(model.getProvince());

            models.add(financingRegional);
        });
        if (CollectionUtil.isNotEmpty(exitNames)) {
            throw new BadRequest(String.join(",",exitNames)+"与融资机构已存在质押关系，请去编辑操作。");
        }
        this.saveBatch(models);
    }

    public void removeModel(Long sequenceNbr) {
        FinancingRegionalDto financingRegionalDto = this.queryBySeq(sequenceNbr);

        LambdaQueryWrapper<FinancingInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FinancingInfo::getRegionalCompaniesSeq,financingRegionalDto.getRegionalCompaniesSeq());
        wrapper.ne(FinancingInfo::getStatus,"放款完成");
        List<FinancingInfo> financingInfos = financingInfoService.getBaseMapper().selectList(wrapper);

        if (CollectionUtil.isNotEmpty(financingInfos)){
            throw new BadRequest("该区域公司存在正在进行中的投融业务，不可删除");
        }
        this.removeById(sequenceNbr);
    }

    public void updateModel(FinancingRegionalDto model) {
        FinancingRegionalDto financingRegionalDto = this.queryBySeq(model.getSequenceNbr());
        List<String> ids = new ArrayList<>();
        List<String> names = new ArrayList<>();
        ids.addAll(model.getFinancing());

        List<Map<String, Object>> orgInfo = financingInfoService.getBaseMapper().selectCompany(ids);
        model.getFinancing().forEach(f->{
            orgInfo.stream().filter(b->String.valueOf(b.get("SEQUENCE_NBR")).equals(f)).forEach(a->{
                names.add(a.get("COMPANY_NAME").toString());
            });
        });

        List<String> oldIds = new ArrayList<>(Arrays.asList(financingRegionalDto.getFinancingId().split(",")));
        oldIds.removeAll(ids);
        if (CollectionUtil.isNotEmpty(oldIds)){
            oldIds.forEach(e->{
                LambdaQueryWrapper<FinancingInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(FinancingInfo::getRegionalCompaniesSeq,financingRegionalDto.getRegionalCompaniesSeq());
                wrapper.eq(FinancingInfo::getFinancingCompaniesSeq,e);
                wrapper.ne(FinancingInfo::getStatus,"放款完成");
                List<FinancingInfo> financingInfos = financingInfoService.getBaseMapper().selectList(wrapper);

                if (CollectionUtil.isNotEmpty(financingInfos)){
                    throw new BadRequest("无法解绑投融业务进行中的融资机构");
                }
            });
        }
        model.setFinancingId(String.join(",",model.getFinancing()));
        model.setFinancingName(String.join(",",names));
        this.updateWithModel(model);

    }
}