package com.jeeplus.psimanage.contract.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.psimanage.contract.domain.PsiContract;
import com.jeeplus.psimanage.contract.domain.PsiContractUser;
import com.jeeplus.psimanage.contract.mapper.PsiContractMapper;
import com.jeeplus.psimanage.contract.mapper.PsiContractUserMapper;
import com.jeeplus.psimanage.contract.service.dto.PsiContractInfoDto;
import com.jeeplus.psimanage.purchase.mapper.PsiMaterialDetailedMapper;
import com.jeeplus.psimanage.oss.domain.PsiWorkAttachment;
import com.jeeplus.psimanage.oss.mapper.PsiOssServiceMapper;
import com.jeeplus.psimanage.oss.service.PsiOssService;
import com.jeeplus.psimanage.oss.service.dto.WorkAttachmentDto;
import com.jeeplus.psimanage.serialNumTpl.service.PsiSerialnumTplService;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jeeplus.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: 王强
 * @create: 2023-01-13 14:11
 **/
@Service
@Transactional
public class PsiContractService {

    @Resource
    private PsiContractMapper psiContractMapper;

    @Resource
    private PsiContractUserMapper psiContractUserMapper;

    @Resource
    private PsiMaterialDetailedMapper psiDetailedMapper;

    @Resource
    private PsiOssServiceMapper psiOssServiceMapper;

    @Resource
    private PsiOssService psiOssService;

    @Resource
    private PsiSerialnumTplService psiSerialnumTplService;

//    @Resource
//    private ContractInfoService infoService;

    public String remove(String id) {
        // 删除基础信息表
        psiContractMapper.deleteById(id);
        // 删除详情列表 及对应附件信息
        List<PsiContractUser> detailedList = psiContractUserMapper.getByContId(id);
        if (null != detailedList){
            detailedList.forEach(de->{
                psiDetailedMapper.deleteById(de.getId());
            });
        }
        // 删除附件信息
        LambdaQueryWrapper<PsiWorkAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PsiWorkAttachment::getAttachmentId, id);
        psiOssServiceMapper.delete(wrapper);
        return "操作成功";
    }

    public void updateStatusById(PsiContractInfoDto dto) {
        psiContractMapper.updateStatusById(dto.getId(), dto.getStatus());
    }

    public PsiContractInfoDto findById(String id) {
        PsiContractInfoDto dto = new PsiContractInfoDto();
        // 查询基础信息表
        PsiContract info = psiContractMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(info)) {
            BeanUtils.copyProperties(info, dto);
            //将采购详情数据查出
            List<PsiContractUser> detailedList = psiContractUserMapper.getByContId(id);
            dto.setCwProjectClientContactDTOList(detailedList);
            //附件信息
            List<WorkAttachmentDto> files = psiDetailedMapper.getByAttachmentId(info.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentDto i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
//                    i.setCreateBy(UserUtils.get(i.getBy()));
                }
            }
            dto.setFiles(files);
        }
        return dto;
    }

    /**
     * 列表查询
     */
    public IPage<PsiContractInfoDto> list(Page<PsiContractInfoDto> page , PsiContractInfoDto dto) throws Exception{
        QueryWrapper<PsiContractInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, PsiContractInfoDto.class);

        queryWrapper.eq("a.del_flag", "0");

        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like("a.name", dto.getName());
        }
        if (StringUtils.isNotEmpty(dto.getContractName())) {
            queryWrapper.like("a.contract_name", dto.getContractName());
        }
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.like("a.status", dto.getStatus());
        }
        String[] effectiveDates = dto.getEffectiveDates();
        if (effectiveDates != null) {

            queryWrapper.between("a.effective_date", effectiveDates[0], effectiveDates[1]);
        }

        return psiContractMapper.findList(page, queryWrapper);
    }

    public String save(PsiContractInfoDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        if (StringUtils.isNotEmpty(dto.getId()) && !dto.getId().equals("false")) {
            return update(dto, userDTO);
        } else {
            return add(dto, userDTO);
        }
    }

    public String update(PsiContractInfoDto dto, UserDTO userDTO) {
        // 修改基础信息
        PsiContract info = new PsiContract();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        psiContractMapper.updateById(info);
        //当一开始保存的联系人数据在修改的时候被删除时
        List<String> idList = psiContractUserMapper.getByContractId(info.getId());
        for (PsiContractUser detailInfo : dto.getCwProjectClientContactDTOList()) {
            //删除多余的领用详情
            //根据基础表id获取所有的详情表id
            if (null != idList) {
                if (idList.contains(detailInfo.getId())){
                    idList.remove(detailInfo.getId());
                }
            }
        }
        if (null != idList & idList.size()>0) {
            idList.forEach(id->{
                psiContractUserMapper.deleteById(id);
            });
        }
        // 修改客户联系人信息
        if (CollectionUtils.isNotEmpty(dto.getCwProjectClientContactDTOList())) {
            for (PsiContractUser user : dto.getCwProjectClientContactDTOList()) {
                //根据id去客户联系人表中查是否有对应数据  有则修改，无则添加
                PsiContractUser contractUser = psiContractUserMapper.selectById(user.getId());
                if (null == contractUser) {
                    // 生成id
                    String detailId = UUID.randomUUID().toString().replace("-", "");
                    user.setId(detailId);
                    user.setCreateById(userDTO.getId());
                    user.setCreateTime(new Date());
                    user.setUpdateById(userDTO.getId());
                    user.setUpdateTime(new Date());
                    user.setDelFlag(0);
                    user.setContractId(info.getId());
                    psiContractUserMapper.insert(user);
                } else {
                    user.setUpdateById(userDTO.getId());
                    user.setUpdateTime(new Date());
                    psiContractUserMapper.updateById(user);
                }
            }
        }
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            psiOssService.saveOrUpdateFileList(dto.getFiles(),dto.getId(),"procureContract",TokenProvider.getCurrentToken ( ));
//            infoService.updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return dto.getId();
    }

    public String add(PsiContractInfoDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = psiSerialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE,TokenProvider.getCurrentToken());
        // 保存基础信息表信息
        PsiContract info = new PsiContract();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
        info.setContractNo(no);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        psiContractMapper.insert(info);
        //保存客户联系人信息
        if (CollectionUtils.isNotEmpty(dto.getCwProjectClientContactDTOList())) {
            for (PsiContractUser user : dto.getCwProjectClientContactDTOList()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                user.setId(detailId);
                user.setCreateById(userDTO.getId());
                user.setCreateTime(new Date());
                user.setUpdateById(userDTO.getId());
                user.setUpdateTime(new Date());
                user.setDelFlag(0);
                user.setContractId(info.getId());
                psiContractUserMapper.insert(user);
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            psiOssService.saveOrUpdateFileList(dto.getFiles(),dto.getId(),"procureContract",TokenProvider.getCurrentToken ( ));
//            infoService.saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }
}
