package com.jeeplus.finance.projectReportArchive.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.finance.projectReportArchive.domain.CwProjectReportBorrow;
import com.jeeplus.finance.projectReportArchive.domain.CwProjectReportBorrowMessage;
import com.jeeplus.finance.projectReportArchive.mapper.CwProjectReportArchiveMapper;
import com.jeeplus.finance.projectReportArchive.mapper.CwProjectReportBorrowMapper;
import com.jeeplus.finance.projectReportArchive.mapper.CwProjectReportBorrowMessageMapper;
import com.jeeplus.finance.projectReportArchive.service.dto.CwProjectReportArchiveDTO;
import com.jeeplus.finance.projectReportArchive.service.dto.CwProjectReportBorrowDto;
import com.jeeplus.finance.projectReportArchive.service.dto.WorkAttachmentArchiveDto;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.feign.IDictApi;
import com.jeeplus.sys.feign.ITenantApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: 王强
 * @create: 2022-11-27 13:51
 **/
@Service
public class CwProjectReportBorrowService {

    @Resource
    private CwProjectReportArchiveMapper cwProjectReportArchiveMapper;

    @Resource
    private CwProjectReportBorrowMapper borrowMapper;

    @Resource
    private CwProjectReportBorrowMessageMapper messageMapper;

    @Resource
    private CwProjectReportArchiveMapper infoMapper;

    @Resource
    private IFlowableApi flowTaskService;

    public String saveInfo(CwProjectReportBorrowDto workContractBorrowDto) throws Exception {
        if (StringUtils.isNotEmpty(workContractBorrowDto.getId())) {
            CwProjectReportBorrow info = borrowMapper.selectById( workContractBorrowDto.getId());
            if (info != null) {
                infoMapper.updateBorrowTypeById(info.getArchiveId(),workContractBorrowDto.getBorrowType());
                return update(workContractBorrowDto, info.getArchiveId());
            }
        }
        return add(workContractBorrowDto);
    }

    /**
     * 报告借用新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(CwProjectReportBorrowDto workContractBorrowDto) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        String id = UUID.randomUUID().toString().replace("-", "");
        CwProjectReportBorrow borrow = new CwProjectReportBorrow();
        BeanUtils.copyProperties(workContractBorrowDto, borrow);
        borrow.setId(id);
        borrow.setArchiveId(workContractBorrowDto.getId());
        borrow.setCreateById(userDTO.getId());
        borrow.setCreateTime(new Date());
        borrow.setUpdateById(userDTO.getId());
        borrow.setUpdateTime(new Date());
        borrowMapper.insert(borrow);
        //借用记录信息
        this.saveMessage(workContractBorrowDto, id);
        return id;
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(CwProjectReportBorrowDto workContractBorrowDto, String id) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        CwProjectReportBorrow borrow = new CwProjectReportBorrow();
        BeanUtils.copyProperties(workContractBorrowDto, borrow);
        borrow.setArchiveId(id);
        borrow.setUpdateById(userDTO.getId());
        borrow.setUpdateTime(new Date());
        borrowMapper.updateById(borrow);
        //借用记录信息
        this.saveMessage(workContractBorrowDto, workContractBorrowDto.getId());
        return borrow.getId();
    }
    /**
     * 根据id修改status
     */
    public void updateStatusById(CwProjectReportBorrowDto workContractBorrowDto) {
        borrowMapper.updateStatusById(workContractBorrowDto.getId(), workContractBorrowDto.getBorrowType());
    }

    public void updateStatusByContractInfoId(CwProjectReportBorrowDto workContractBorrowDto) {
        infoMapper.updateBorrowTypeById(workContractBorrowDto.getId(),workContractBorrowDto.getBorrowType());
        borrowMapper.updateStatusByContractInfoId(workContractBorrowDto.getId(), workContractBorrowDto.getBorrowType());
    }

    public CwProjectReportBorrow findById(String id) {
        CwProjectReportBorrow borrow = borrowMapper.selectById(id);
        if (borrow == null) {
            LambdaQueryWrapper<CwProjectReportBorrow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CwProjectReportBorrow::getArchiveId, id);
            borrow = borrowMapper.selectOne(wrapper);
        }
        if (null != borrow){
            List<WorkAttachmentArchiveDto> fileList = Lists.newArrayList();
            // 查询附件信息
            List<WorkAttachmentArchiveDto> dtos = cwProjectReportArchiveMapper.findDtos(borrow.getArchiveId());
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentArchiveDto i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            fileList.addAll(dtos);
            borrow.setWorkAttachmentDtoList(fileList);
        }
        return borrow;
    }

    public CwProjectReportBorrow findByContractInfoId(String id) {
        return borrowMapper.selectFileByContractInfoId(id);
    }

    /**
     * 借用记录保存
     * @param workContractBorrowDto
     * @param id
     * @return
     */
    public void saveMessage (CwProjectReportBorrowDto workContractBorrowDto, String id) {
        //保存借用信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        CwProjectReportBorrowMessage message = new CwProjectReportBorrowMessage();
        BeanUtils.copyProperties(workContractBorrowDto, message);
        String messageId = UUID.randomUUID().toString().replace("-", "");
        message.setId(messageId);
        message.setCreateById(userDTO.getId());
        message.setCreateTime(new Date());
        message.setUpdateById(userDTO.getId());
        message.setUpdateTime(new Date());
        message.setProjectReportBorrowId(id);
        message.setBorrowType(workContractBorrowDto.getBorrowType());
        messageMapper.insert(message);
    }

    /**
     * 根据contractBorrowId修改borrowType
     */
    public void updateMessageByBorrowId(CwProjectReportBorrowDto workContractBorrowDto, String type) {
        if ("reture".equals(type)) {
            CwProjectReportBorrow borrow = borrowMapper.selectFileByContractInfoId(workContractBorrowDto.getId());
            if (borrow != null) {
                borrowMapper.updateMessageByBorrowId(borrow.getId(), workContractBorrowDto.getBorrowType(), type);
            }
        } else {
            borrowMapper.updateMessageByBorrowId(workContractBorrowDto.getId(), workContractBorrowDto.getBorrowType(), null);
        }
    }

    public void deleteById(String id) {
        LambdaQueryWrapper<CwProjectReportBorrow> wrapper = new LambdaQueryWrapper<CwProjectReportBorrow>();
        wrapper.eq(CwProjectReportBorrow::getArchiveId, id);
        CwProjectReportBorrow borrow = borrowMapper.selectOne(wrapper);
        if (borrow != null) {
            borrowMapper.deleteMessageById(borrow.getId());
        }
    }

    public List<CwProjectReportBorrowMessage> findMessageList(String id) {
        CwProjectReportBorrow borrow = findByContractInfoId(id);
        if (borrow != null) {
            return borrowMapper.findMessageList(borrow.getId());
        }
        return null;
    }

    /**
     * 查询临期合同借用信息
     * @return
     */
    public List<CwProjectReportBorrowMessage> getAdventMessageList() {
        String adventDay = SpringUtil.getBean ( IDictApi.class ).getDictLabel("advent_day", "cw_borrow_advent", "");
//        String adventDay = DictUtils.getDictLabel("advent_day", "cw_borrow_advent", "");
        adventDay = "-" + adventDay;
        List<CwProjectReportBorrowMessage> adventMessageList = borrowMapper.getAdventMessageList(adventDay);
        if(null != adventMessageList && adventMessageList.size()>0){
            for (CwProjectReportBorrowMessage info : adventMessageList) {
                String taskName = null;
                String titleStr = null;

                //如果当前时间大于过期时间
                //Date类的一个方法，如果info.getAdventDateDate()早于 new Date() 返回true，否则返回false
                if(info.getBorrowRetData().before(new Date())){
                    taskName = "合同【"+ info.getProjectName()+"】借用已超期";
                    titleStr = "合同【"+ info.getProjectName()+"】借用已超期。超期时间："+dateToString(info.getBorrowRetData()) +"。";
                }else{
                    taskName = "合同【"+ info.getProjectName()+"】即将借用超期";
                    titleStr = "合同【"+ info.getProjectName()+"】即将借用超期。超期时间："+dateToString(info.getBorrowRetData());
                }


                //计算两日期之间的天数
                Integer interval = Integer.valueOf(this.getInterval(info.getBorrowRetData(), new Date()));
                if(interval > 0){
                    titleStr = titleStr + "已超期：" + interval + "天。请尽快归还";
                }

                Set<String> noticeUserSet = new HashSet<String>();
                if(StringUtils.isNotBlank(info.getBorrowName())){
                    String tenantId = SpringUtil.getBean ( ITenantApi.class ).getCurrentTenantId ( );
                    UserDTO borrowUser = SpringUtil.getBean ( IUserApi.class ).getByLoginName(info.getBorrowName(),tenantId);
                    if(null != borrowUser && StringUtils.isNotBlank(borrowUser.getId())){
                        noticeUserSet.add(borrowUser.getId());
                    }
                }
                if(StringUtils.isNotBlank(info.getContractCreateById())){
                    noticeUserSet.add(info.getContractCreateById());
                }
            }
        }
        return null;
    }


    /**
     * 计算两日期相差天数
     * @param beginDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public String getInterval(Date beginDate, Date endDate){
        long day = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            if(beginDate != null){
                String begin = sdf.format(beginDate);
                beginDate  = sdf.parse(begin);
            }
            if(endDate!= null){
                String end= sdf.format(endDate);
                endDate= sdf.parse(end);
            }
        } catch (Exception e){
            e.getMessage();
        }
        day = (endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
        return String.valueOf(day);
    }
    public static String dateToString(Date date) {
        SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式

        String s = sformat.format(date);

        return s;
    }

}
