package com.yh.saas.platform.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsea.svc.base.workflow.entity.WorkflowHistoricTask;
import com.yh.saas.platform.service.IBillOperateHisService;
import com.yh.saas.plugin.base.entity.CommonBillOperateHis;
import com.yh.saas.plugin.base.service.ICommonBillOperateHisService;
import com.yh.saas.toolkit.workflow.service.IWorkflowHistoryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BillOprateHisImpl implements IBillOperateHisService {

    @Autowired
    private ICommonBillOperateHisService billOperateHisService;

    @Autowired
    private IWorkflowHistoryService workflowHistoryService;

    @Override
    public List<CommonBillOperateHis> getBillOperateHis(String id, String billType) {
        Wrapper<CommonBillOperateHis> wrapper = new EntityWrapper<>();
        wrapper.eq(CommonBillOperateHis.QueryFields.BILL_ID, id);
        if (StringUtils.isNotBlank(billType)) {
            wrapper.eq(CommonBillOperateHis.QueryFields.BILL_TYPE, billType);
        }
        wrapper.orderBy(CommonBillOperateHis.QueryFields.OPERATE_DATE, false);
        List<CommonBillOperateHis> list = billOperateHisService.selectList(wrapper);

        // 采购询价单特殊处理
        if ("PURCHASE-MAT-TYPE-ENQUIRY".equals(billType) || "PURCHASE-MAP-TYPE-ENQUIRY".equals(billType)
                || "PURCHASE-SP-TYPE-ENQUIRY".equals(billType)) {
            return list;
        }
        List<WorkflowHistoricTask> historicTasks = this.workflowHistoryService.getInstanceHistories(id);
        if (CollectionUtils.isNotEmpty(historicTasks)) {
            historicTasks
                    .forEach(
                            histortyTask -> list.add(CommonBillOperateHis.getInstance(histortyTask.getOperatorName(),
                                    histortyTask.getClaimTime(),
                                    histortyTask.getApproved() ? "1" : "0", histortyTask.getTaskName(),
                                    histortyTask.getTaskNameEn(), histortyTask.getOperatorMajorRoleName(),
                                    histortyTask.getAuditMind())));
        }
        return list.stream().sorted(Comparator.comparing(CommonBillOperateHis::getOperateDate).reversed())
                .collect(Collectors.toList());
    }

}
