package com.jeeplus.finance.ccpm.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jeeplus.finance.ccpm.enums.TaskAliasEnum;
import com.jeeplus.finance.ccpm.vo.TranspondDTO;
import com.jeeplus.finance.ccpm.vo.WorkInvoiceDetailVo;
import com.jeeplus.finance.ccpm.vo.WorkInvoiceVo;
import com.jeeplus.finance.invoice.domain.CwFinanceInvoice;
import com.jeeplus.finance.invoice.service.CwFinanceInvoiceService;
import com.jeeplus.finance.invoice.service.dto.CwFinanceInvoiceDTO;
import com.jeeplus.finance.invoice.service.dto.CwFinanceInvoiceDetailDTO;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class TranspondService {

    @Autowired
    private CwFinanceInvoiceService cwFinanceInvoiceService;

    public Map<String,Object> auditDistribute(TranspondDTO transpondDTO) {
        Map<String,Object> result = new HashMap<>();
        result.put("success", null);
        if (Objects.nonNull(transpondDTO) && StringUtils.isNotBlank(transpondDTO.getId()) && StringUtils.isNotBlank(transpondDTO.getFlag()) && StringUtils.isNotBlank(transpondDTO.getProcessDefKey())) {
            String id = transpondDTO.getId(); // 报销数据id
            String flag = transpondDTO.getFlag(); // 审核标记  yes通过  no驳回
            WorkInvoiceVo workInvoiceVo = transpondDTO.getWorkInvoice();
            //将审核中新增的信息转为本系统中的数据
            CwFinanceInvoiceDTO cwFinanceInvoiceDTO=transportToCenter(workInvoiceVo);
            TaskAliasEnum taskAliasEnum = TaskAliasEnum.getByCcpmContains(transpondDTO.getProcessDefKey()); // 获取流程key枚举
            if (ObjectUtil.isNotEmpty(taskAliasEnum)) {
                if (TaskAliasEnum.REIMBURSEMENT.getCpaTaskAlias().equals(taskAliasEnum.getCpaTaskAlias())) { // 评估-报销流程
                    CwFinanceInvoiceDTO financeInvoice = cwFinanceInvoiceService.queryById(id);
                    if (Objects.nonNull(financeInvoice) && StringUtils.isNotBlank(financeInvoice.getStatus()) && "2".equals(financeInvoice.getStatus())) { // 确保当时数据处于“待审核”状态
                        if ( StringUtils.isNotBlank(financeInvoice.getProcInsId())) {
                            try {
                                CwFinanceInvoiceDTO upStatusParam = new CwFinanceInvoiceDTO();
                                BeanUtils.copyProperties(financeInvoice,upStatusParam);
                                upStatusParam.setBillingDate(cwFinanceInvoiceDTO.getBillingDate());
                                upStatusParam.setCollectDate(cwFinanceInvoiceDTO.getCollectDate());
                                upStatusParam.setFinanceInvoiceDetailDTOList(cwFinanceInvoiceDTO.getFinanceInvoiceDetailDTOList());
                                if ("yes".equals(flag)) {
                                    String currentTaskName = SpringUtil.getBean(IFlowableApi.class).getCurrentTaskName(financeInvoice.getProcInsId());
                                    if (StringUtils.isNotBlank(currentTaskName) && "发票管理员审核".equals(currentTaskName)) {
                                        // “公司领导审批” 节点审核通过时，才会将审核状态改为 “审核通过”
                                        upStatusParam.setStatus("5"); // 审核状态设置为审核完成
                                    }
                                } else {
                                    upStatusParam.setStatus("4"); // 审核状态设置为审核驳回
                                }
                                cwFinanceInvoiceService.saveForm(upStatusParam); // 修改数据的审核状态
                                SpringUtil.getBean(IFlowableApi.class).auditByProcInsIdAndFlag(financeInvoice.getProcInsId(), flag, "", transpondDTO.getComment());
                                result.put("success", "false");
                                result.put("message", "操作成功");
                            }catch (Exception e) {
                                e.printStackTrace();
                                result.put("success", "false");
                                result.put("message", "操作失败");
                            }
                        }
                    } else {
                        result.put("success", "false");
                        result.put("message", "操作失败，数据已发生改变或不存在，请刷新数据");
                    }
                }
            }
        }
        if (ObjectUtil.isEmpty(result.get("success"))) {
            result.put("success", "false");
            result.put("message", "操作失败");
        }
        return result;
    }

    //将审核中添加的数据转为本系统中的数据
    private CwFinanceInvoiceDTO transportToCenter(WorkInvoiceVo workInvoiceVo) {
        CwFinanceInvoiceDTO cwFinanceInvoiceDTO = new CwFinanceInvoiceDTO();
        //开票时间
        cwFinanceInvoiceDTO.setBillingDate(workInvoiceVo.getInvoiceDate());
        //领票时间
        cwFinanceInvoiceDTO.setCollectDate(workInvoiceVo.getTakeDate());
        //发票明细
        ArrayList<CwFinanceInvoiceDetailDTO> cwFinanceInvoiceDetailDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(workInvoiceVo.getWorkAccountList())){
            for (WorkInvoiceDetailVo workInvoiceDetailVo : workInvoiceVo.getWorkAccountList()) {
                CwFinanceInvoiceDetailDTO cwFinanceInvoiceDetailDTO = new CwFinanceInvoiceDetailDTO();
                cwFinanceInvoiceDetailDTO.setCode(workInvoiceDetailVo.getCode());
                cwFinanceInvoiceDetailDTO.setNumber(workInvoiceDetailVo.getNumber());
                cwFinanceInvoiceDetailDTO.setAccount(workInvoiceDetailVo.getTotalMoney());
                cwFinanceInvoiceDetailDTO.setRate(workInvoiceDetailVo.getTax());
                cwFinanceInvoiceDetailDTO.setAmount(workInvoiceDetailVo.getTaxMoney());
                cwFinanceInvoiceDetailDTO.setTax(workInvoiceDetailVo.getTaxRate());
                cwFinanceInvoiceDetailDTOS.add(cwFinanceInvoiceDetailDTO);
            }
            cwFinanceInvoiceDTO.setFinanceInvoiceDetailDTOList(cwFinanceInvoiceDetailDTOS);
        }
        return cwFinanceInvoiceDTO;
    }

}
