package com.testor.module.duty.controller;

/**
 * @title ApplicationController
 * @description <TODO description class purpose>
 * @Author: qiao
 * @version:1.0.0
 * @create：4/18/23 10:20 AM
 */

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.workflow.apis.application.model.dto.MyApplicationsListRequest;
import com.tongtech.tfw.workflow.apis.application.model.dto.MyApplicationsListResponse;
import com.tongtech.tfw.workflow.apis.definition.model.domain.ActReProcdef;
import com.tongtech.tfw.workflow.apis.definition.service.ActReProcdefService;
import com.tongtech.tfw.workflow.apis.instance.model.domain.ActHiProcinst;
import com.tongtech.tfw.workflow.apis.instance.service.ActHiProcinstService;
import com.tongtech.tfw.workflow.service.TfwCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ActivityInstance;
import org.flowable.engine.runtime.ActivityInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(value = "TApplication Controller", tags = {"我的申请管理"})
@RequestMapping({"/t/application"})
public class TApplicationController extends SuperController {
    @Autowired
    private ActHiProcinstService actHiProcinstService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TfwCommonService tfwCommonService;
    @Autowired
    private ActReProcdefService actReProcdefService;


    @ApiOperation(
            value = "我的申请-列表",
            notes = "List My Application"
    )
    @GetMapping({"/my/list"})
    public BaseResponse<BaseResponseList<MyApplicationsListResponse>> processInsList(MyApplicationsListRequest processInsListRequest) {
        BaseResponse<BaseResponseList<MyApplicationsListResponse>> baseResponse = new BaseResponse();
        BaseResponseList<MyApplicationsListResponse> responseListBaseResponse = new BaseResponseList();
        Long page = StringHelper.isEmpty(processInsListRequest.getPage()) ? BizConstants.PAGE : Long.valueOf(processInsListRequest.getPage());
        Long limit = StringHelper.isEmpty(processInsListRequest.getLimit()) ? BizConstants.LIMIT : Long.valueOf(processInsListRequest.getLimit());
        QueryWrapper<ActHiProcinst> queryWrapper = new QueryWrapper();
        queryWrapper.eq("START_USER_ID_", this.getUserId());
        if (StringHelper.isNotBlank(processInsListRequest.getProcessDefinitionName())&&(processInsListRequest.getProcessDefinitionName().contains("安全巡检") || processInsListRequest.getProcessDefinitionName().contains("危险作业"))) {
            responseListBaseResponse.setData(null);
            responseListBaseResponse.setTotal(0);
            baseResponse.setData(responseListBaseResponse);
            return baseResponse;
        }

        //todo 查询PROC_DEF_ID_
        List<String> ids =
                actReProcdefService.list(new QueryWrapper<ActReProcdef>().notLike("NAME_", "安全巡检").notLike("NAME_", "危险作业"))
                .stream().map(ActReProcdef::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ids)&& !StringHelper.isNotBlank(processInsListRequest.getProcessDefinitionName())) {
            queryWrapper.in("PROC_DEF_ID_", ids);
        }
        if ("巡检".equals(processInsListRequest.getProcessDefinitionName())) {
            processInsListRequest.setProcessDefinitionName("巡检延期");
        }
        if (StringHelper.isNotBlank(processInsListRequest.getProcessDefinitionName())) {
            queryWrapper.in("PROC_DEF_ID_", this.tfwCommonService.queryDefId(processInsListRequest.getProcessDefinitionName()));
        }

        queryWrapper.orderByDesc("START_TIME_");
        Page<ActHiProcinst> resultPage = new Page(page, limit);
        Page<ActHiProcinst> resultList = (Page)this.actHiProcinstService.page(resultPage, queryWrapper);
        List<MyApplicationsListResponse> result = new ArrayList(resultList.getRecords().size());

        MyApplicationsListResponse myApplicationsListResponse;
        for(Iterator var9 = resultList.getRecords().iterator(); var9.hasNext(); result.add(myApplicationsListResponse)) {
            ActHiProcinst actHiProcinst = (ActHiProcinst)var9.next();
            myApplicationsListResponse = new MyApplicationsListResponse(actHiProcinst);
            myApplicationsListResponse.setStartUser(this.tfwCommonService.queryUserName(myApplicationsListResponse.getStartUser()));
            ActReProcdef actReProcdef = (ActReProcdef)this.actReProcdefService.getOne((Wrapper)(new QueryWrapper()).eq("ID_", actHiProcinst.getProcDefId()));
            myApplicationsListResponse.setProcessDefinitionName(actReProcdef.getName());
            myApplicationsListResponse.setProcessDefinitionDescription(actReProcdef.getDescription());
            if (ObjectHelper.isEmpty(actHiProcinst.getEndTime())) {
                List<ActivityInstance> actList = ((ActivityInstanceQuery)this.runtimeService.createActivityInstanceQuery().processInstanceId(actHiProcinst.getProcInstId()).activityType("userTask").orderByActivityInstanceStartTime().desc()).list();
                if (!actList.isEmpty()) {
                    ActivityInstance activityInstance = (ActivityInstance)actList.get(0);
                    myApplicationsListResponse.setExecutionId(activityInstance.getExecutionId());
                    myApplicationsListResponse.setCurrentTaskName(activityInstance.getActivityName());
                    if (StringHelper.isNotBlank(activityInstance.getAssignee())) {
                        myApplicationsListResponse.setAssigneeName(this.tfwCommonService.queryUserName(activityInstance.getAssignee()));
                    }
                }
            }
        }


        responseListBaseResponse.setData(result);
        responseListBaseResponse.setTotal(resultList.getTotal());
        baseResponse.setData(responseListBaseResponse);
        return baseResponse;
    }
}