package com.testor.module.contractor.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.common.constant.StatusEnum;
import com.testor.module.contractor.common.model.constant.ContractorProcessStatus;
import com.testor.module.contractor.enums.ContractorFlowTypeEnum;
import com.testor.module.contractor.enums.GeneralFlagEnum;
import com.testor.module.contractor.enums.ProcessStatusEnum;
import com.testor.module.contractor.ledger.model.domain.TContractorInfo;
import com.testor.module.contractor.ledger.model.domain.TContractorLedger;
import com.testor.module.contractor.ledger.service.TContractorInfoService;
import com.testor.module.contractor.ledger.service.TContractorLedgerService;
import com.testor.module.contractor.manage.dao.TContractorBlacklistDao;
import com.testor.module.contractor.manage.model.domain.TContractorBlacklist;
import com.testor.module.contractor.manage.model.domain.TContractorBlacklist;
import com.testor.module.contractor.manage.model.dto.ContractorBlacklistDto;
import com.testor.module.contractor.manage.model.dto.TContractorBlacklistParam;
import com.testor.module.contractor.manage.service.TContractorBlacklistService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import com.tongtech.tfw.workflow.apis.definition.controller.ProcessDefinitionController;
import com.tongtech.tfw.workflow.apis.definition.model.dto.ProcessDefStartParam;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
import com.tongtech.tfw.workflow.apis.task.model.dto.CompleteTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 承包商管理-考核评价-黑名单Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-12-01 11:15:44
 */
@Service
public class TContractorBlacklistServiceImpl extends SuperServiceImpl<TContractorBlacklistDao, TContractorBlacklist> implements TContractorBlacklistService
{
    @Autowired(required = false)
    private TContractorBlacklistDao tContractorBlacklistDao;

    @Autowired
    private ProcessDefinitionController processDefinitionController;

    @Autowired
    private WfTaskController wfTaskController;

    @Autowired
    private TContractorLedgerService tContractorLedgerService;

    @Autowired
    private TContractorInfoService tContractorInfoService;

    @Override
    public Page<ContractorBlacklistDto> pageList(TContractorBlacklistParam param) {
        Long page=
                StringHelper.isEmpty(param.getPage())? BizConstants.PAGE:Long.valueOf(param.getPage());
        Long limit=
                StringHelper.isEmpty(param.getLimit())?BizConstants.LIMIT:Long.valueOf(param.getLimit());
        Page<TContractorBlacklist> resultPage  = new Page<>(page,limit);
        UserInfo loginUser = ContextUtils.getLoginUser();
        param.setOrgId(loginUser.getOrgId());
        return tContractorBlacklistDao.pageList(resultPage,param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startProcess(TContractorBlacklistParam updateRequest) {
        // 创建一个ProcessDefStartParam对象，并设置流程定义的key为"contractor"
        ProcessDefStartParam processDefStartParam = new ProcessDefStartParam("contractor");
        // 创建一个TContractorBasicInfo对象
        TContractorBlacklist tContractorBlacklist = BeanHelper.beanToBean(updateRequest, TContractorBlacklist.class);
        // 如果是新增提交，则先保存数据，再执行后续逻辑
        if(StringHelper.isBlank(tContractorBlacklist.getId())){
            tContractorBlacklist.setId(IdHelper.getId32bit());
            this.save(tContractorBlacklist);
        }
        // 设置业务主键为updateRequest的id
        processDefStartParam.setBizKey(tContractorBlacklist.getId());
        // 创建一个Map对象，并设置type为"blacklist"
        Map<String, Object> map = new HashMap<>();
        map.put("type", ContractorFlowTypeEnum.BLACKLIST.getCode());
        // 将Map对象设置到processDefStartParam的variables属性中
        processDefStartParam.setVariables(map);
        // 调用processDefinitionController的startProcessIns方法，并获取返回结果
        String result = processDefinitionController.startProcessIns(processDefStartParam).getData().getResult();
        // 设置processId为result
        tContractorBlacklist.setProcessId(result);
        // 设置processStatus为待审核
        tContractorBlacklist.setProcessStatus(ContractorProcessStatus.UNDER_REVIEW.getValue());
        // 调用tContractorBlacklistService的updateById方法，更新tContractorBlacklist对象
        this.updateById(tContractorBlacklist);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeProcess(TContractorBlacklistParam updateRequest) {
        String processStatus = updateRequest.getProcessStatus();
        CompleteTask completeTask = new CompleteTask();
        completeTask.setBizId(updateRequest.getId());
        completeTask.setTaskId(updateRequest.getTaskId());
        // 创建一个vars参数
        Map<String, Object> vars = StringHelper.isEmpty(updateRequest.getVars()) ? new HashMap<>() : updateRequest.getVars();
        if(!vars.containsKey("processStatus")) {
            vars.put("processStatus", processStatus);
        }
        completeTask.setVars(vars);
        wfTaskController.completeTask(completeTask).getData().getResult();
        // 创建一个TContractorBlacklist对象
        TContractorBlacklist tContractorBlacklist = new TContractorBlacklist();
        // 设置id为updateRequest的id
        tContractorBlacklist.setId(updateRequest.getId());
        // 设置processStatus
        tContractorBlacklist.setProcessStatus(processStatus);
        if(ContractorProcessStatus.REJECTED.getValue().equals(processStatus)){
            String rejectOpinion = vars.get("rejectOpinion") == null ? "" : vars.get("rejectOpinion").toString();
            tContractorBlacklist.setRejectOpinion(rejectOpinion);
        }
        // 调用tContractorBlacklistService的updateById方法，更新tContractorBlacklist对象
        boolean result = this.updateById(tContractorBlacklist);

        // 如果审核通过，则更新承包商台账对应的承包商信息为黑名单
        if(result && processStatus.equals(ContractorProcessStatus.APPROVED.getValue())){
            tContractorBlacklist = this.getById(updateRequest.getId());
            TContractorLedger contractorLedger =
                    tContractorLedgerService.getById(tContractorBlacklist.getContractorId());
            // 更新承包商信息为黑名单
            if(contractorLedger != null){
                TContractorInfo tContractorInfo = new TContractorInfo();
                tContractorInfo.setId(contractorLedger.getInfoId());
                tContractorInfo.setIsBlacklist(GeneralFlagEnum.YES.getCode());
                tContractorInfoService.updateById(tContractorInfo);
            }
        }
    }

    @Override
    public TContractorBlacklist getByContractorId(String contractorId) {
        QueryWrapper<TContractorBlacklist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TContractorBlacklist.CONTRACTOR_ID, contractorId);
        queryWrapper.ne(TContractorBlacklist.STATUS, StatusEnum.DELETE.getCode());
        TContractorBlacklist tContractorBlacklist = this.getOne(queryWrapper, false);
        
        return tContractorBlacklist;
    }

    /**
     * 根据承包商id查询承包商是否进入黑名单
     *
     * @param contractorId
     * @return
     */
    @Override
    public boolean existBlacklist(String contractorId) {
        QueryWrapper<TContractorBlacklist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TContractorBlacklist.CONTRACTOR_ID, contractorId);
        queryWrapper.eq(TContractorBlacklist.PROCESS_STATUS, ContractorProcessStatus.APPROVED.getValue());
        TContractorBlacklist tContractorBlacklist = this.getOne(queryWrapper.last("limit 1"), false);
        if(tContractorBlacklist != null){
            return true;
        }
        return false;
    }

    /**
     * 查询进入黑名单的承包商id集合
     *
     * @return
     */
    @Override
    public List<String> getBlacklistContractorIds() {
        QueryWrapper<TContractorBlacklist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TContractorBlacklist.PROCESS_STATUS, ContractorProcessStatus.APPROVED.getValue());
        List<TContractorBlacklist> tContractorBlacklists = this.list(queryWrapper);
        if(tContractorBlacklists != null && tContractorBlacklists.size() > 0){
            return tContractorBlacklists.stream().map(TContractorBlacklist::getContractorId).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}
