package com.sckw.contract.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.contract.dao.KwcContractLogisticsTrackMapper;
import com.sckw.contract.dao.KwcContractTradeMapper;
import com.sckw.contract.dao.KwcContractTradeTrackMapper;
import com.sckw.contract.dao.KwcContractTradeUnitMapper;
import com.sckw.contract.model.entity.*;
import com.sckw.contract.model.vo.res.ContractTrackResVo;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.ContractTrackEnum;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author PC
* @description 针对表【kwc_contract_trade_track(交易合同（采购合同/销售合同）-交易订单（采购订单/销售订单）)】的数据库操作Service实现
* @createDate 2023-07-13 13:36:19
*/
@Service
public class KwcContractTradeTrackService {

    @Autowired
    private KwcContractTradeTrackMapper kwcContractTradeTrackMapper;

    @Autowired
    private KwcContractTradeMapper kwcContractTradeMapper;

    @Autowired
    private KwcContractTradeUnitMapper kwcContractTradeUnitMapper;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    public void saveContractTradeTrack(Long contractId, Integer status) {
        Date date = new Date();
        date = DateUtil.offsetSecond(date, Global.NUMERICAL_TWO);
        KwcContractTradeTrack kwcContractTradeTrack = new KwcContractTradeTrack();
        kwcContractTradeTrack.setId(new IdWorker(1L).nextId());
        kwcContractTradeTrack.setContractId(contractId);
        kwcContractTradeTrack.setType(status);
        kwcContractTradeTrack.setRemark("");
        kwcContractTradeTrack.setStatus(Global.NO);
        kwcContractTradeTrack.setCreateBy(LoginUserHolder.getUserId());
        kwcContractTradeTrack.setCreateTime(date);
        kwcContractTradeTrack.setUpdateBy(LoginUserHolder.getUserId());
        kwcContractTradeTrack.setUpdateTime(date);
        kwcContractTradeTrack.setDelFlag(Global.NO);
        if (kwcContractTradeTrackMapper.insert(kwcContractTradeTrack) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }
    }

    /**
     * @param id 合同id
     * @return List<ContractTrackResVo>
     * @desc: 根据合同id查流程
     * @author: czh
     * @date: 2023/7/31
     */
    public List<ContractTrackResVo> queryContractTrackByContractId(Long id) {
        LambdaQueryWrapper<KwcContractTradeTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwcContractTradeTrack::getContractId, id).
                eq(KwcContractTradeTrack::getDelFlag, Global.NO).
                orderByDesc(KwcContractTradeTrack::getCreateTime);
        List<KwcContractTradeTrack> kwcContractTradeTracks = kwcContractTradeTrackMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(kwcContractTradeTracks)) {
            return Collections.emptyList();
        }

        KwcContractTrade kwcContractTrade = kwcContractTradeMapper.selectById(id);
        if (Objects.isNull(kwcContractTrade)) {
            return Collections.emptyList();
        }

        Long entId = kwcContractTrade.getEntId();
        LambdaQueryWrapper<KwcContractTradeUnit> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(KwcContractTradeUnit::getContractId, id).
                eq(KwcContractTradeUnit::getDelFlag, Global.NO);
        List<KwcContractTradeUnit> kwcContractTradeUnits = kwcContractTradeUnitMapper.selectList(wrapper2);
        if (CollectionUtils.isEmpty(kwcContractTradeUnits)) {
            return Collections.emptyList();
        }

        String initiateEntName = "";
        String targetEntName  = "";
        for (KwcContractTradeUnit kwcContractTradeUnit : kwcContractTradeUnits) {
            if (kwcContractTradeUnit.getEntId().equals(entId)) {
                initiateEntName = kwcContractTradeUnit.getFirmName();
            } else {
                targetEntName = kwcContractTradeUnit.getFirmName();
            }
        }

        List<ContractTrackResVo> list = new ArrayList<>();
        for (KwcContractTradeTrack item : kwcContractTradeTracks) {
            ContractTrackResVo contractTrackResVo = new ContractTrackResVo();
            contractTrackResVo.setCreateTime(item.getCreateTime());
            contractTrackResVo.setTrackName(ContractTrackEnum.getName(item.getType()).getName());
            if (ContractTrackEnum.SIGNING.getCode() == item.getType()) {
                contractTrackResVo.setEntName(initiateEntName);
            } else if (ContractTrackEnum.SIGNED.getCode() == item.getType()) {
                contractTrackResVo.setEntName(targetEntName);
            } else {
                UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(item.getCreateBy());
                contractTrackResVo.setEntName(userCacheResDto.getEntInfo().getFirmName());
            }
            list.add(contractTrackResVo);
        }
        return list;
    }
}




