package com.jeeplus.business.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.pubmodules.oss.domain.WorkAttachment;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OssService;



import com.jeeplus.business.workClientInfo.domain.JyWorkClientBank;
import com.jeeplus.business.workClientInfo.domain.JyWorkClientInfo;
import com.jeeplus.business.workClientInfo.domain.JyWorkClientJobTypeInfo;
import com.jeeplus.business.workClientInfo.domain.JyWorkClientLinkman;
import com.jeeplus.business.workClientInfo.domain.dto.JyWorkClientInfosDto;
import com.jeeplus.business.workClientInfo.mapper.JyWorkClientBankMapper;
import com.jeeplus.business.workClientInfo.mapper.JyWorkClientInfoMapper;
import com.jeeplus.business.workClientInfo.mapper.JyWorkClientJobTypeInfoMapper;
import com.jeeplus.business.workClientInfo.mapper.JyWorkClientLinkmanMapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IDictApi;
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 JyWorkClientService {

    @Resource
    private JyWorkClientInfoMapper jyWorkClientInfoMapper;

    @Resource
    private JyWorkClientBankMapper jyWorkClientBankMapper;

    @Resource
    private JyWorkClientLinkmanMapper jyWorkClientLinkmanMapper;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

    @Resource
    private JyWorkClientJobTypeInfoMapper jyWorkClientJobTypeInfoMapper;


//    @Resource
//    private OssService ossService;

    /**
     * 客户信息列表
     * @param
     * @return
     */
    public IPage<JyWorkClientInfo> list(Page<JyWorkClientInfo> page, QueryWrapper<JyWorkClientInfo> queryWrapper) {
        queryWrapper.eq("a.del_flag","0");
        IPage<JyWorkClientInfo> pageList = jyWorkClientInfoMapper.findPageList(page, queryWrapper);
        List<JyWorkClientInfo> list = pageList.getRecords();
        if (CollectionUtil.isNotEmpty(list)) {
            for (JyWorkClientInfo info : list) {
                LambdaQueryWrapper<JyWorkClientBank> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(JyWorkClientBank::getClientId, info.getId());
                List<JyWorkClientBank> banks = jyWorkClientBankMapper.selectList(wrapper);
                info.setBacks(banks);
                if (StringUtils.isBlank(info.getMobile())){
                    info.setMobile("");
                }
                //获取客户联系人
                JyWorkClientLinkman jyWorkClientLinkman = jyWorkClientLinkmanMapper.selectByClientId(info.getId());
                if (ObjectUtil.isNotEmpty(jyWorkClientLinkman)){
                    info.setLinkId(jyWorkClientLinkman.getId());
                    info.setClientName(jyWorkClientLinkman.getClientName());
                    info.setMobile(jyWorkClientLinkman.getLinkMobile());
                    info.setPhone(jyWorkClientLinkman.getLinkPhone());
                    info.setPosition(jyWorkClientLinkman.getPosition());
                }

            }


        }
        return pageList;
    }

    /**
     * 客户信息保存
     * @param workClientInfosDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String save(JyWorkClientInfosDto workClientInfosDto) {
        //获取当前登录人信息
        UserDTO dto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //客户信息处理
        String id = UUID.randomUUID().toString().replace("-", "");
        JyWorkClientInfo 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());
        jyWorkClientInfoMapper.insert(workClientInfo);
        //客户行业处理
        String deputy = workClientInfo.getDeputy();
        if (StringUtils.isNotEmpty(deputy)) {
            List<String> list = Arrays.asList(deputy.split(","));
            list.stream().forEach(i -> {
                JyWorkClientJobTypeInfo info = new JyWorkClientJobTypeInfo();
                info.setWorkClientId(id);
                info.setJobTypeId(i);
                jyWorkClientJobTypeInfoMapper.insert(info);
            });
        }
        //开户行信息处理
        List<JyWorkClientBank> 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);
                i.setDelFlag(0);
                jyWorkClientBankMapper.insert(i);
            });
        }
        //联系人信息处理
        List<JyWorkClientLinkman> 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);
                i.setDelFlag(0);
                jyWorkClientLinkmanMapper.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();

        //客户信息删除
        jyWorkClientInfoMapper.deleteById(id);
        //客户行业处理
        LambdaQueryWrapper<JyWorkClientJobTypeInfo> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(JyWorkClientJobTypeInfo::getWorkClientId, id);
        jyWorkClientJobTypeInfoMapper.delete(wrapper3);
        //客户关联开户行信息删除
        LambdaQueryWrapper<JyWorkClientBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JyWorkClientBank::getClientId, id);
        jyWorkClientBankMapper.delete(wrapper);
        //客户关联紧急联系人信息删除
        LambdaQueryWrapper<JyWorkClientLinkman> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(JyWorkClientLinkman::getClientId, id);
        jyWorkClientLinkmanMapper.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 JyWorkClientInfosDto findById (String id) {
        JyWorkClientInfosDto dto = new JyWorkClientInfosDto();
        JyWorkClientInfo workClientInfo = jyWorkClientInfoMapper.selectById(id);
        //从字典中找出客户性质名称
        String companyTypeName = SpringUtil.getBean ( IDictApi.class ).getDictLabel(workClientInfo.getCompanyType(), "customer_nature", "");
        workClientInfo.setCompanyTypeName(companyTypeName);
        //从字典中找出客户行业名称
        String companyIndustryName = SpringUtil.getBean ( IDictApi.class ).getDictLabel(workClientInfo.getCompanyIndustry(), "industry", "");
        workClientInfo.setCompanyIndustryName(companyIndustryName);
        //从字典中找出客户行业名称
        String clientTypeName = SpringUtil.getBean ( IDictApi.class ).getDictLabel(workClientInfo.getClientType(), "customer_type", "");
        workClientInfo.setClientTypeName(clientTypeName);
        //客户行业查询
        LambdaQueryWrapper<JyWorkClientJobTypeInfo> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(JyWorkClientJobTypeInfo::getWorkClientId, id);
        List<JyWorkClientJobTypeInfo> infos = jyWorkClientJobTypeInfoMapper.selectList(wrapper3);
        if (CollectionUtil.isNotEmpty(infos)) {
            String s = new String();
            for (JyWorkClientJobTypeInfo info : infos) {
                String jobTypeId = info.getJobTypeId();
                s = s + "," + jobTypeId;
            }
            String substring = s.substring(1, s.length());
            workClientInfo.setDeputy(substring);
        }
        //客户信息查询
        dto.setWorkClientInfo(workClientInfo);
        //客户关联开户行信息查询
        LambdaQueryWrapper<JyWorkClientBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JyWorkClientBank::getClientId, id);
        wrapper.orderByDesc(JyWorkClientBank::getUpdateTime);
        dto.setWorkClientBank(jyWorkClientBankMapper.selectList(wrapper));
        //客户关联紧急联系人信息查询
        LambdaQueryWrapper<JyWorkClientLinkman> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(JyWorkClientLinkman::getClientId, id);
        wrapper1.orderByDesc(JyWorkClientLinkman::getUpdateTime);
        dto.setWorkClientLinkman(jyWorkClientLinkmanMapper.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(JyWorkClientInfosDto workClientInfosDto) {
        //获取当前登录人信息
        UserDTO dto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //客户信息处理
        JyWorkClientInfo workClientInfo = workClientInfosDto.getWorkClientInfo();
        //客户行业处理
        LambdaQueryWrapper<JyWorkClientJobTypeInfo> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(JyWorkClientJobTypeInfo::getWorkClientId, workClientInfo.getId());
        jyWorkClientJobTypeInfoMapper.delete(wrapper3);
        String deputy = workClientInfo.getDeputy();
        if (StringUtils.isNotEmpty(deputy)) {
            List<String> list = Arrays.asList(deputy.split(","));
            list.stream().forEach(i -> {
                JyWorkClientJobTypeInfo info = new JyWorkClientJobTypeInfo();
                info.setWorkClientId(workClientInfo.getId());
                info.setJobTypeId(i);
                jyWorkClientJobTypeInfoMapper.updateById(info);
            });
        }
        workClientInfo.setUpdateById(dto.getId());
        workClientInfo.setUpdateTime(new Date());
        workClientInfo.setCompanyId(dto.getCompanyDTO().getId());
        workClientInfo.setOfficeId(dto.getOfficeDTO().getId());
        jyWorkClientInfoMapper.updateById(workClientInfo);
        //开户行信息处理(先删除原有数据，再进行数据添加)
        List<JyWorkClientBank> workClientBank = workClientInfosDto.getWorkClientBank();
        if (CollectionUtil.isNotEmpty(workClientBank)) {
            LambdaQueryWrapper<JyWorkClientBank> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JyWorkClientBank::getClientId, workClientInfo.getId());
            jyWorkClientBankMapper.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());
                jyWorkClientBankMapper.insert(i);
            });
        }
        //联系人信息处理
        List<JyWorkClientLinkman> workClientLinkman = workClientInfosDto.getWorkClientLinkman();
        if (CollectionUtil.isNotEmpty(workClientLinkman)) {
            LambdaQueryWrapper<JyWorkClientLinkman> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JyWorkClientLinkman::getClientId, workClientInfo.getId());
            jyWorkClientLinkmanMapper.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());
                jyWorkClientLinkmanMapper.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(JyWorkClientInfosDto workClientInfosDto){
        if(ObjectUtil.isNotEmpty(workClientInfosDto)){
            if(ObjectUtil.isNotEmpty(workClientInfosDto.getWorkClientInfo())){
                if(StringUtils.isNotBlank(workClientInfosDto.getWorkClientInfo().getId())){
                    List<JyWorkClientInfo> workClientInfos = jyWorkClientInfoMapper.selectList(new QueryWrapper<JyWorkClientInfo>().lambda()
                            .eq(JyWorkClientInfo::getName, workClientInfosDto.getWorkClientInfo().getName())
                            .ne(JyWorkClientInfo::getId, workClientInfosDto.getWorkClientInfo().getId())
                    );
                    if(CollectionUtil.isNotEmpty(workClientInfos)){
                        return false;
                    }
                }else{
                    List<JyWorkClientInfo> workClientInfos = jyWorkClientInfoMapper.selectList(new QueryWrapper<JyWorkClientInfo>().lambda()
                            .eq(JyWorkClientInfo::getName, workClientInfosDto.getWorkClientInfo().getName())
                    );
                    if(CollectionUtil.isNotEmpty(workClientInfos)){
                        return false;
                    }
                }
            }
        }
        return true;
    }

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

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

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

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

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