package com.jeeplus.assess.workClientInfo.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.assess.workClientInfo.domain.WorkClientBank;
import com.jeeplus.assess.workClientInfo.domain.WorkClientInfo;
import com.jeeplus.assess.workClientInfo.domain.WorkClientJobTypeInfo;
import com.jeeplus.assess.workClientInfo.domain.WorkClientLinkman;
import com.jeeplus.assess.workClientInfo.domain.dto.WorkClientInfosDto;
import com.jeeplus.assess.workClientInfo.mapper.WorkClientBankMapper;
import com.jeeplus.assess.workClientInfo.mapper.WorkClientInfoMapper;
import com.jeeplus.assess.workClientInfo.mapper.WorkClientJobTypeInfoMapper;
import com.jeeplus.assess.workClientInfo.mapper.WorkClientLinkmanMapper;
import com.jeeplus.assess.workContract.service.WorkContractService;
import com.jeeplus.assess.workContract.service.dto.WorkContractInfoDto;
//import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OssService;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.DictUtils;
//import com.jeeplus.sys.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WorkClientService {

    @Resource
    private WorkClientInfoMapper workClientInfoMapper;

    @Resource
    private WorkClientBankMapper workClientBankMapper;

    @Resource
    private WorkClientLinkmanMapper workClientLinkmanMapper;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

    @Resource
    private WorkClientJobTypeInfoMapper workClientJobTypeInfoMapper;

    @Resource
    private WorkContractService workContractService;

//    @Resource
//    private OssService ossService;

    /**
     * 客户信息列表
     * @param
     * @return
     */
    public IPage<WorkClientInfo> list(Page<WorkClientInfo> page, QueryWrapper<WorkClientInfo> queryWrapper) {
        queryWrapper.eq("a.del_flag","0");
        IPage<WorkClientInfo> pageList = workClientInfoMapper.findPageList(page, queryWrapper);
        List<WorkClientInfo> list = pageList.getRecords();
        if (CollectionUtil.isNotEmpty(list)) {
            for (WorkClientInfo info : list) {
                LambdaQueryWrapper<WorkClientBank> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(WorkClientBank::getClientId, info.getId());
                List<WorkClientBank> banks = workClientBankMapper.selectList(wrapper);
                info.setBacks(banks);
            }
        }
        return pageList;
    }

    /**
     * 客户信息保存
     * @param workClientInfosDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String save(WorkClientInfosDto workClientInfosDto) {
        //获取当前登录人信息
        UserDTO dto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //客户信息处理
        String id = UUID.randomUUID().toString().replace("-", "");
        WorkClientInfo workClientInfo = workClientInfosDto.getWorkClientInfo();
        workClientInfo.setId(id);
        workClientInfo.setCreateById(dto.getId());
        workClientInfo.setCreateTime(new Date());
        workClientInfo.setUpdateById(dto.getId());
        workClientInfo.setUpdateTime(new Date());
        workClientInfo.setCompanyId(dto.getCompanyDTO().getId());
        workClientInfo.setOfficeId(dto.getOfficeDTO().getId());
        workClientInfoMapper.insert(workClientInfo);
        //客户行业处理
        String deputy = workClientInfo.getDeputy();
        if (StringUtils.isNotEmpty(deputy)) {
            List<String> list = Arrays.asList(deputy.split(","));
            list.stream().forEach(i -> {
                WorkClientJobTypeInfo info = new WorkClientJobTypeInfo();
                info.setWorkClientId(id);
                info.setJobTypeId(i);
                workClientJobTypeInfoMapper.insert(info);
            });
        }
        //开户行信息处理
        List<WorkClientBank> workClientBank = workClientInfosDto.getWorkClientBank();
        if (CollectionUtil.isNotEmpty(workClientBank)) {
            workClientBank.stream().forEach(i -> {
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateById(dto.getId());
                i.setCreateTime(new Date());
                i.setUpdateById(dto.getId());
                i.setUpdateTime(new Date());
                i.setClientId(id);
                workClientBankMapper.insert(i);
            });
        }
        //联系人信息处理
        List<WorkClientLinkman> workClientLinkman = workClientInfosDto.getWorkClientLinkman();
        if (CollectionUtil.isNotEmpty(workClientLinkman)) {
            workClientLinkman.stream().forEach(i -> {
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateById(dto.getId());
                i.setCreateTime(new Date());
                i.setUpdateById(dto.getId());
                i.setUpdateTime(new Date());
                i.setClientId(id);
                workClientLinkmanMapper.insert(i);
            });
        }
        //附件信息处理
        List<WorkAttachmentInfo> workAttachments = workClientInfosDto.getWorkAttachments();
        if (CollectionUtil.isNotEmpty(workAttachments)) {
            int j = 1;
            for (WorkAttachmentInfo i : workAttachments) {
                i.setId(UUID.randomUUID().toString().replace("-", ""));

                //文件类型处理
                List<String> strings = Arrays.asList(i.getAttachmentName().split("\\."));
                if (CollectionUtil.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setDelFlag(0);

                UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
                i.setCreateTime(new Date());
                i.setUpdateTime(new Date());
                i.setAttachmentId(id);
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
                j++;
            }
        }
        return "添加完成!";
    }

    /**
     * 客户信息删除
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> removeById (String id) {
        Map<String,Object> map = new HashMap();
        //判断客户是否被合同调用
        List<WorkContractInfoDto> contractInfoDtoList = workContractService.getInfoByClientId(id);
        if(null != contractInfoDtoList && contractInfoDtoList.size()>0){
            map.put("success",false);
            map.put("message","客户已被引用，无法删除！");
            return map;
        }

        //客户信息删除
        workClientInfoMapper.deleteById(id);
        //客户行业处理
        LambdaQueryWrapper<WorkClientJobTypeInfo> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(WorkClientJobTypeInfo::getWorkClientId, id);
        workClientJobTypeInfoMapper.delete(wrapper3);
        //客户关联开户行信息删除
        LambdaQueryWrapper<WorkClientBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkClientBank::getClientId, id);
        workClientBankMapper.delete(wrapper);
        //客户关联紧急联系人信息删除
        LambdaQueryWrapper<WorkClientLinkman> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(WorkClientLinkman::getClientId, id);
        workClientLinkmanMapper.delete(wrapper1);
        //客户关联附件信息删除
//        LambdaQueryWrapper<WorkAttachmentInfo> wrapper2 = new LambdaQueryWrapper<>();
//        wrapper2.eq(WorkAttachmentInfo::getAttachmentId, id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        map.put("success",true);
        map.put("message","删除成功！");
        return map;
    }

    /**
     * 客户信息查询
     * @param id
     * @return
     */
    public WorkClientInfosDto findById (String id) {
        WorkClientInfosDto dto = new WorkClientInfosDto();
        WorkClientInfo workClientInfo = workClientInfoMapper.selectById(id);
        //客户行业查询
        LambdaQueryWrapper<WorkClientJobTypeInfo> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(WorkClientJobTypeInfo::getWorkClientId, id);
        List<WorkClientJobTypeInfo> infos = workClientJobTypeInfoMapper.selectList(wrapper3);
        if (CollectionUtil.isNotEmpty(infos)) {
            String s = new String();
            for (WorkClientJobTypeInfo info : infos) {
                String jobTypeId = info.getJobTypeId();
                s = s + "," + jobTypeId;
            }
            String substring = s.substring(1, s.length());
            workClientInfo.setDeputy(substring);
        }
        //客户信息查询
        dto.setWorkClientInfo(workClientInfo);
        //客户关联开户行信息查询
        LambdaQueryWrapper<WorkClientBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkClientBank::getClientId, id);
        wrapper.orderByDesc(WorkClientBank::getUpdateTime);
        dto.setWorkClientBank(workClientBankMapper.selectList(wrapper));
        //客户关联紧急联系人信息查询
        LambdaQueryWrapper<WorkClientLinkman> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(WorkClientLinkman::getClientId, id);
        wrapper1.orderByDesc(WorkClientLinkman::getUpdateTime);
        dto.setWorkClientLinkman(workClientLinkmanMapper.selectList(wrapper1));
        //客户关联附件信息查询
//        LambdaQueryWrapper<WorkAttachmentInfo> wrapper2 = new LambdaQueryWrapper<>();
//        wrapper2.eq(WorkAttachmentInfo::getAttachmentId, id);
//        wrapper2.orderByAsc(WorkAttachmentInfo::getSort);
        dto.setWorkAttachments(SpringUtil.getBean ( IWorkAttachmentApi.class ).selectListByAttachmentId(id));
        return dto;
    }

    /**
     * 客户信息更新
     * @param workClientInfosDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(WorkClientInfosDto workClientInfosDto) {
        //获取当前登录人信息
        UserDTO dto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //客户信息处理
        WorkClientInfo workClientInfo = workClientInfosDto.getWorkClientInfo();
        //客户行业处理
        LambdaQueryWrapper<WorkClientJobTypeInfo> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(WorkClientJobTypeInfo::getWorkClientId, workClientInfo.getId());
        workClientJobTypeInfoMapper.delete(wrapper3);
        String deputy = workClientInfo.getDeputy();
        if (StringUtils.isNotEmpty(deputy)) {
            List<String> list = Arrays.asList(deputy.split(","));
            list.stream().forEach(i -> {
                WorkClientJobTypeInfo info = new WorkClientJobTypeInfo();
                info.setWorkClientId(workClientInfo.getId());
                info.setJobTypeId(i);
                workClientJobTypeInfoMapper.insert(info);
            });
        }
        workClientInfo.setUpdateById(dto.getId());
        workClientInfo.setUpdateTime(new Date());
        workClientInfo.setCompanyId(dto.getCompanyDTO().getId());
        workClientInfo.setOfficeId(dto.getOfficeDTO().getId());
        workClientInfoMapper.updateById(workClientInfo);
        //开户行信息处理(先删除原有数据，再进行数据添加)
        List<WorkClientBank> workClientBank = workClientInfosDto.getWorkClientBank();
        if (CollectionUtil.isNotEmpty(workClientBank)) {
            LambdaQueryWrapper<WorkClientBank> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WorkClientBank::getClientId, workClientInfo.getId());
            workClientBankMapper.delete(wrapper);
            workClientBank.stream().forEach(i -> {
                i.setId(UUID.randomUUID().toString().replace("-",""));
                i.setCreateById(dto.getId());
                i.setCreateTime(new Date());
                i.setUpdateById(dto.getId());
                i.setUpdateTime(new Date());
                i.setClientId(workClientInfo.getId());
                workClientBankMapper.insert(i);
            });
        }
        //联系人信息处理
        List<WorkClientLinkman> workClientLinkman = workClientInfosDto.getWorkClientLinkman();
        if (CollectionUtil.isNotEmpty(workClientLinkman)) {
            LambdaQueryWrapper<WorkClientLinkman> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WorkClientLinkman::getClientId, workClientInfo.getId());
            workClientLinkmanMapper.delete(wrapper);
            workClientLinkman.stream().forEach(i -> {
                i.setId(UUID.randomUUID().toString().replace("-",""));
                i.setCreateById(dto.getId());
                i.setCreateTime(new Date());
                i.setUpdateById(dto.getId());
                i.setUpdateTime(new Date());
                i.setClientId(workClientInfo.getId());
                workClientLinkmanMapper.insert(i);
            });
        }
        //附件信息处理
        List<WorkAttachmentInfo> workAttachments = workClientInfosDto.getWorkAttachments();
        List<String> collect = workAttachments.stream().distinct().filter(item -> {
            if (StringUtils.isNotBlank(item.getId())) {
                return true;
            }
            return false;
        }).map(WorkAttachmentInfo::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(workAttachments)) {
            if(CollectionUtil.isNotEmpty(collect)){
                SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentIdNotInIds(workClientInfo.getId(),collect);
//                ossService.remove(new QueryWrapper<WorkAttachmentInfo>().lambda()
//                        .eq(WorkAttachmentInfo::getAttachmentId,workClientInfo.getId())
//                        .notIn(WorkAttachmentInfo::getId,collect));
            }
            workAttachments.stream().forEach(i -> i.setAttachmentId(workClientInfo.getId()));
            Map<String,String> map = new HashMap<>();
            map.put("workAttachments",JSON.toJSONString(workAttachments));
            map.put("currentToken", TokenProvider.getCurrentToken());
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveMsg2(map);
        } else{
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(workClientInfo.getId());
//            ossService.remove(new QueryWrapper<WorkAttachmentInfo>().lambda().eq(WorkAttachmentInfo::getAttachmentId,workClientInfo.getId()));
        }
        return "更新完成!";
    }

    /**
     * 新建或修改  判断客户是否重复
     * @param workClientInfosDto
     * @return
     */
    public boolean haveWorkClient(WorkClientInfosDto workClientInfosDto){
        if(ObjectUtil.isNotEmpty(workClientInfosDto)){
            if(ObjectUtil.isNotEmpty(workClientInfosDto.getWorkClientInfo())){
                if(StringUtils.isNotBlank(workClientInfosDto.getWorkClientInfo().getId())){
                    List<WorkClientInfo> workClientInfos = workClientInfoMapper.selectList(new QueryWrapper<WorkClientInfo>().lambda()
                            .eq(WorkClientInfo::getName, workClientInfosDto.getWorkClientInfo().getName())
                            .ne(WorkClientInfo::getId, workClientInfosDto.getWorkClientInfo().getId())
                    );
                    if(CollectionUtil.isNotEmpty(workClientInfos)){
                        return false;
                    }
                }else{
                    List<WorkClientInfo> workClientInfos = workClientInfoMapper.selectList(new QueryWrapper<WorkClientInfo>().lambda()
                            .eq(WorkClientInfo::getName, workClientInfosDto.getWorkClientInfo().getName())
                    );
                    if(CollectionUtil.isNotEmpty(workClientInfos)){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 新建或修改  判断统一社会信用代码是否重复
     * @param workClientInfosDto
     * @return
     */
    public boolean haveUscCode(WorkClientInfosDto workClientInfosDto){
        if(ObjectUtil.isNotEmpty(workClientInfosDto)){
            if(ObjectUtil.isNotEmpty(workClientInfosDto.getWorkClientInfo())){
                if(StringUtils.isNotBlank(workClientInfosDto.getWorkClientInfo().getId())){
                    List<WorkClientInfo> workClientInfos = workClientInfoMapper.selectList(new QueryWrapper<WorkClientInfo>().lambda()
                            .eq(WorkClientInfo::getUscCode, workClientInfosDto.getWorkClientInfo().getUscCode())
                            .ne(WorkClientInfo::getId, workClientInfosDto.getWorkClientInfo().getId())
                    );
                    if(CollectionUtil.isNotEmpty(workClientInfos)){
                        return false;
                    }
                }else{
                    List<WorkClientInfo> workClientInfos = workClientInfoMapper.selectList(new QueryWrapper<WorkClientInfo>().lambda()
                            .eq(WorkClientInfo::getUscCode, workClientInfosDto.getWorkClientInfo().getUscCode())
                    );
                    if(CollectionUtil.isNotEmpty(workClientInfos)){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 根据名称模糊搜索客户信息
     * @param name
     * @return
     */
    public List<WorkClientInfo> findListByName(String name) {
        LambdaQueryWrapper<WorkClientInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(WorkClientInfo::getName, name);
        List<WorkClientInfo> workClientInfos = workClientInfoMapper.selectList(wrapper);
        return workClientInfos;
    }

    public Integer isExist(String param) {
        return workClientInfoMapper.isExist(param);
    }

    /**
     * 客户信息列表-组件使用
     * @param
     * @return
     */
    public IPage<WorkClientInfo> componentList(Page<WorkClientInfo> page, QueryWrapper<WorkClientInfo> queryWrapper) {
        queryWrapper.eq("a.del_flag","0");
        IPage<WorkClientInfo> pageList = workClientInfoMapper.findPageList(page, queryWrapper);
        return pageList;
    }

    /**
     * 客户信息查询-组件使用
     * @param id
     * @return
     */
    public WorkClientInfo componentById (String id) {
        WorkClientInfo workClientInfo = workClientInfoMapper.selectById(id);
        return workClientInfo;
    }
}
