package com.jeeplus.test.materialManagement.contract.service;

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.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jeeplus.test.cw.contractRegistration.service.ContractInfoService;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jeeplus.test.materialManagement.contract.domain.Contract;
import com.jeeplus.test.materialManagement.contract.domain.ContractUser;
import com.jeeplus.test.materialManagement.contract.mapper.ContractMapper;
import com.jeeplus.test.materialManagement.contract.mapper.ContractUserMapper;
import com.jeeplus.test.materialManagement.contract.service.dto.ContractInfoDto;
import com.jeeplus.test.materialManagement.purchase.mapper.MaterialDetailedMapper;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.program.configuration.projectList.service.dto.ContractDto;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
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 ContractService {

    @Resource
    private ContractMapper contractMapper;

    @Resource
    private ContractUserMapper contractUserMapper;

    @Resource
    private MaterialDetailedMapper detailedMapper;

    @Resource
    private OssServiceMapper ossServiceMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private ContractInfoService infoService;

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

    public void updateStatusById(ContractInfoDto dto) {
        contractMapper.updateStatusById(dto.getId(), dto.getStatus());
    }

    public ContractInfoDto findById(String id) {
        ContractInfoDto dto = new ContractInfoDto();
        // 查询基础信息表
        Contract info = contractMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(info)) {
            BeanUtils.copyProperties(info, dto);
            //将采购详情数据查出
            List<ContractUser> detailedList = contractUserMapper.getByContId(id);
            dto.setCwProjectClientContactDTOList(detailedList);
            //附件信息
            List<WorkAttachmentDto> files = detailedMapper.getByAttachmentId(info.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentDto i : files) {
                    i.setCreateBy(UserUtils.get(i.getBy()));
                }
            }
            dto.setFiles(files);
        }
        return dto;
    }

    /**
     * 列表查询
     */
    public IPage<ContractInfoDto> list(Page<ContractInfoDto> page , ContractInfoDto dto) throws Exception{
        QueryWrapper<ContractInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, ContractInfoDto.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 contractMapper.findList(page, queryWrapper);
    }

    public String save(ContractInfoDto dto) throws Exception{
        // 获取当前登录人信息
        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(ContractInfoDto dto, UserDTO userDTO) {
        // 修改基础信息
        Contract info = new Contract();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        contractMapper.updateById(info);
        //当一开始保存的联系人数据在修改的时候被删除时
        List<String> idList = contractUserMapper.getByContractId(info.getId());
        for (ContractUser 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->{
                contractUserMapper.deleteById(id);
            });
        }
        // 修改客户联系人信息
        if (CollectionUtils.isNotEmpty(dto.getCwProjectClientContactDTOList())) {
            for (ContractUser user : dto.getCwProjectClientContactDTOList()) {
                //根据id去客户联系人表中查是否有对应数据  有则修改，无则添加
                ContractUser contractUser = contractUserMapper.selectById(user.getId());
                if (null == contractUser) {
                    // 生成id
                    String detailId = UUID.randomUUID().toString().replace("-", "");
                    user.setId(detailId);
                    user.setCreateBy(userDTO.getId());
                    user.setCreateDate(new Date());
                    user.setUpdateBy(userDTO.getId());
                    user.setUpdateDate(new Date());
                    user.setDelFlag(0);
                    user.setContractId(info.getId());
                    contractUserMapper.insert(user);
                } else {
                    user.setUpdateBy(userDTO.getId());
                    user.setUpdateDate(new Date());
                    contractUserMapper.updateById(user);
                }
            }
        }
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            infoService.updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return dto.getId();
    }

    public String add(ContractInfoDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE);
        // 保存基础信息表信息
        Contract info = new Contract();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
        info.setContractNo(no);
        info.setCreateBy(userDTO.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        info.setDelFlag(0);
        contractMapper.insert(info);
        //保存客户联系人信息
        if (CollectionUtils.isNotEmpty(dto.getCwProjectClientContactDTOList())) {
            for (ContractUser user : dto.getCwProjectClientContactDTOList()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                user.setId(detailId);
                user.setCreateBy(userDTO.getId());
                user.setCreateDate(new Date());
                user.setUpdateBy(userDTO.getId());
                user.setUpdateDate(new Date());
                user.setDelFlag(0);
                user.setContractId(info.getId());
                contractUserMapper.insert(user);
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            infoService.saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }
}
