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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.common.util.BeanConverUtil;
import com.testor.module.contractor.common.model.constant.ContractorProcessStatus;
import com.testor.module.contractor.enums.ContractorFlowTypeEnum;
import com.testor.module.contractor.manage.dao.TContractorAcceptanceDao;
import com.testor.module.contractor.manage.model.domain.TContractorAcceptance;
import com.testor.module.contractor.manage.model.domain.TContractorAcceptanceChecklist;
import com.testor.module.contractor.manage.model.domain.TContractorAllow;
import com.testor.module.contractor.manage.model.dto.TContractorAcceptanceDTO;
import com.testor.module.contractor.manage.model.dto.TContractorAcceptanceParam;
import com.testor.module.contractor.manage.service.TContractorAcceptanceChecklistService;
import com.testor.module.contractor.manage.service.TContractorAcceptanceService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
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.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 承包商管理-验收交付Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-12-01 15:01:41
 */
@Service
public class TContractorAcceptanceServiceImpl extends SuperServiceImpl<TContractorAcceptanceDao, TContractorAcceptance> implements TContractorAcceptanceService
{
    @Autowired(required = false)
    private TContractorAcceptanceDao tContractorAcceptanceDao;

    @Autowired
    private TContractorAcceptanceChecklistService tContractorAcceptanceChecklistService;

    @Autowired
    private ProcessDefinitionController processDefinitionController;

    @Autowired
    private WfTaskController wfTaskController;

    @Override
    public Page<TContractorAcceptanceDTO> listEntity(TContractorAcceptanceParam 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<TContractorAcceptance> resultPage=new Page<>(page,limit);
        return tContractorAcceptanceDao.listEntity(resultPage, param);
    }

    @Override
    public List<TContractorAcceptance> listAllEntity(TContractorAcceptanceParam param) {
        QueryWrapper<TContractorAcceptance> queryWrapper=this.createQuery(param);
        return this.list(queryWrapper);
    }

    @Override
    public TContractorAcceptance addEntity(TContractorAcceptanceDTO addRequest) {
        // TODO 按需求添加数据去重，特殊值设定，业务异常
        String id = IdHelper.getId32bit();
        TContractorAcceptance data= BeanHelper.beanToBean(addRequest,  TContractorAcceptance.class);
        data.setId(id);
        this.save(data);
        List<TContractorAcceptanceChecklist> tContractorAcceptanceChecklists = addRequest.getTContractorAcceptanceChecklists();
        if (ObjectHelper.isNotEmpty(tContractorAcceptanceChecklists)) {
            for (TContractorAcceptanceChecklist tContractorAcceptanceChecklist : tContractorAcceptanceChecklists) {
                tContractorAcceptanceChecklist.setAcceptId(id);
                tContractorAcceptanceChecklistService.save(tContractorAcceptanceChecklist);
            }
        }
        return data;
    }

    @Override
    public void submit(TContractorAcceptanceDTO tContractorAcceptanceDTO) {
        ProcessDefStartParam processDefStartParam = new ProcessDefStartParam("contractor");
        processDefStartParam.setBizKey(tContractorAcceptanceDTO.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("type", ContractorFlowTypeEnum.ACCEPTANCE.getCode());
        if (tContractorAcceptanceDTO.getMap() != null){
            map.putAll(tContractorAcceptanceDTO.getMap());
        }
        processDefStartParam.setVariables(map);
        String result = processDefinitionController.startProcessIns(processDefStartParam).getData().getResult();
        TContractorAcceptance data= BeanHelper.beanToBean(tContractorAcceptanceDTO,  TContractorAcceptance.class);
        data.setProcessId(result);
        data.setProcessStatus(ContractorProcessStatus.UNDER_REVIEW.getValue());
        this.updateById(data);
    }

    @Override
    public void completeProcess(TContractorAcceptanceDTO tContractorAcceptanceDTO) {
        TContractorAcceptance tContractorAcceptance = this.getById(tContractorAcceptanceDTO.getId());
        String processStatus = tContractorAcceptanceDTO.getProcessStatus();
        CompleteTask completeTask = new CompleteTask();
        completeTask.setBizId(tContractorAcceptanceDTO.getId());
        completeTask.setTaskId(tContractorAcceptanceDTO.getTaskId());
        Map<String, Object> map = new HashMap<>();
        map.put("processStatus", processStatus);
        if (tContractorAcceptanceDTO.getMap() != null){
            map.putAll(tContractorAcceptanceDTO.getMap());
        }
        completeTask.setVars(map);
        wfTaskController.completeTask(completeTask).getData().getResult();
        // 创建一个TContractorBasicInfo对象
        tContractorAcceptance.setProcessStatus(processStatus);
        // 调用tContractorBasicInfoService的updateById方法，更新tContractorBasicInfo对象
        this.updateById(tContractorAcceptance);
    }

    @Override
    public TContractorAcceptance updateEntity(TContractorAcceptanceDTO updateRequest) {
        TContractorAcceptance data= BeanHelper.beanToBean(updateRequest,  TContractorAcceptance.class);
        boolean results = this.updateById(data);
        if (results) {
            tContractorAcceptanceChecklistService.remove(new LambdaQueryWrapper<TContractorAcceptanceChecklist>().eq(TContractorAcceptanceChecklist::getAcceptId, updateRequest.getId()));
            List<TContractorAcceptanceChecklist> tContractorAcceptanceChecklists = updateRequest.getTContractorAcceptanceChecklists();
            if (ObjectHelper.isNotEmpty(tContractorAcceptanceChecklists)) {
                for (TContractorAcceptanceChecklist tContractorAcceptanceChecklist : tContractorAcceptanceChecklists) {
                    tContractorAcceptanceChecklist.setAcceptId(updateRequest.getId());
                    tContractorAcceptanceChecklistService.save(tContractorAcceptanceChecklist);
                }
            }
        }

        return null;
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TContractorAcceptance> createQuery(TContractorAcceptanceParam queryParam){
        QueryWrapper<TContractorAcceptance> queryWrapper=new QueryWrapper<>();
        if(StringHelper.isNotEmpty(queryParam.getContractorId())){
            queryWrapper.eq(TContractorAcceptance.CONTRACTOR_ID,queryParam.getContractorId());
        }
        if(StringHelper.isNotEmpty(queryParam.getProjId())){
            queryWrapper.eq(TContractorAcceptance.PROJ_ID,queryParam.getProjId());
        }
        if(StringHelper.isNotEmpty(queryParam.getBizId())){
            queryWrapper.eq(TContractorAcceptance.BIZ_ID,queryParam.getBizId());
        }
        if(StringHelper.isNotEmpty(queryParam.getProcessId())){
            queryWrapper.eq(TContractorAcceptance.PROCESS_ID,queryParam.getProcessId());
        }
        if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
            queryWrapper.eq(TContractorAcceptance.PROCESS_STATUS,queryParam.getProcessStatus());
        }
        if(StringHelper.isNotEmpty(queryParam.getDepartmentMajor())){
            queryWrapper.eq(TContractorAcceptance.DEPARTMENT_MAJOR,queryParam.getDepartmentMajor());
        }
        if(StringHelper.isNotEmpty(queryParam.getDepartmentBelong())){
            queryWrapper.eq(TContractorAcceptance.DEPARTMENT_BELONG,queryParam.getDepartmentBelong());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getFinishDate())){
            queryWrapper.eq(TContractorAcceptance.FINISH_DATE,queryParam.getFinishDate());
        }
        if(StringHelper.isNotEmpty(queryParam.getOrgId())){
            queryWrapper.eq(TContractorAcceptance.ORG_ID,queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TContractorAcceptance.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TContractorAcceptance.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())){
            if(StringHelper.isNotEmpty(queryParam.getOrderType())
                    &&BizConstants.ASC.equals(queryParam.getOrderType())){
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            }else{
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        }else{
            queryWrapper.orderByDesc(TContractorAcceptance.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
