package com.boman.web.core.service.jflow.impl;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.exception.CustomException;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.redis.RedisKey;
import com.boman.domain.GenTable;
import com.boman.domain.GenTableColumn;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.FormDataDto;
import com.boman.domain.dto.TaskDto;
import com.boman.domain.jflow.ProcessNodeCandidator;
import com.boman.jflow.api.RemoteJflowTaskService;
import com.boman.web.core.domain.RowResult;
import com.boman.web.core.mapper.JFTaskBusinessMapper;
import com.boman.web.core.service.TableServiceCmdService;
import com.boman.web.core.service.jflow.JFlowTaskService;
import com.boman.web.core.service.select.IBaseSelectService;
import com.boman.web.core.utils.IdUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class JFlowTaskServiceImpl implements JFlowTaskService {

    @Autowired
    private RemoteJflowTaskService remoteJflowTaskService;
    @Autowired
    private JFTaskBusinessMapper jfTaskBusinessMapper;
    @Autowired
    private TableServiceCmdService tableServiceCmdService;
    @Resource
    private IBaseSelectService selectService;

    @Override
    public AjaxResult historyLoad(TaskDto taskDto) {
        return remoteJflowTaskService.historySearchInPage(taskDto);
    }

    @Override
    public AjaxResult pendingTaskSearch(TaskDto taskDto) {
        return remoteJflowTaskService.pendingTaskSearch(taskDto);
    }

    @Override
    public AjaxResult pagePass(TaskDto taskDto) {
        return remoteJflowTaskService.pagePass(taskDto);
    }

    @Override
    public AjaxResult pageDeny(TaskDto taskDto) {
        return remoteJflowTaskService.pageDeny(taskDto);
    }

    @Override
    public JSONObject approvalStatistics(TaskDto taskDto) {
        return remoteJflowTaskService.approvalStatistics(taskDto);
    }

    @Override
    public AjaxResult pageDetail(TaskDto taskDto) {
        return remoteJflowTaskService.pageDetail(taskDto);
    }

    /**
     * 设置审核人节点信息
     *
     * @param taskDto
     * @return
     */
    @Override
    public AjaxResult setCandiditors(TaskDto taskDto) {
        String candidatorTableName = taskDto.getCandidatorTableName();
        List<RowResult> result = Lists.newArrayListWithCapacity(1);
        GenTable genTable = tableServiceCmdService.getTableFromRedisByTableName(RedisKey.TABLE_INFO, candidatorTableName);
        String pkName = IdUtils.getPkName(genTable.getColumns());
        try {
            String candidatorId = taskDto.getCandidatorId();
            // 这个是如果没有设置审核人，先去主表数据中获取
            if(StringUtils.isEmpty(candidatorId)) {
                candidatorId = jfTaskBusinessMapper.selectBusinessCheckUserId(taskDto.getTableName(), taskDto.getBusinessCode());
            }
            if(StringUtils.isEmpty(candidatorId)) {
                return AjaxResult.error("没有设置审核人", result);
            }
            // 先查看是否已经存在节点对应的数据审核数据
            ProcessNodeCandidator candidator = jfTaskBusinessMapper.selectData(candidatorTableName, taskDto.getBusinessCode(), taskDto.getModuleId(), taskDto.getNodeId());
            JSONObject model = new JSONObject();
            if(candidator != null) {
                model.put("candidator_id", candidatorId);
                jfTaskBusinessMapper.updateByIdList(taskDto.getCandidatorTableName(), pkName, Arrays.asList(candidator.getId()), model);
            }else {
                model.put("id", IdUtils.getMaxId(candidatorTableName, pkName));
                model.put("module_id", taskDto.getModuleId());
                model.put("business_code", taskDto.getBusinessCode());
                model.put("node_id", taskDto.getNodeId());
                model.put("candidator_id", candidatorId);
                jfTaskBusinessMapper.insert(taskDto.getCandidatorTableName(), model);
            }
        }catch (CustomException e) {
            return AjaxResult.error("设置扩展节点审核人异常", result);
        }

        return AjaxResult.success(result);
    }

    /**
     * 功能描述: 获取单表单所有数据
     *
     * @param dto condition
     * @return com.boman.domain.dto.AjaxResult
     */
    @Override
    public AjaxResult getBusinessCandidators(FormDataDto dto) {
        String tableName = dto.getCandidatorTableName();
        GenTable genTable = tableServiceCmdService.getTableFromRedisByTableName(RedisKey.TABLE_INFO, tableName);
        List<GenTableColumn> columns = genTable.getColumns();
        // 获取候选人字段
        JSONObject jsonObject = jfTaskBusinessMapper.selectNodeData(tableName, dto.getId(), dto.getModuleId(), dto.getNodeId());
        if(jsonObject == null) {
            return AjaxResult.error(-1, "没有候选人或者组！");
        }
        String candidator = "";
        String candidatorDepart = "";
        for (GenTableColumn column : columns) {
            String columnName = column.getColumnName();
            if(columnName.equals("candidator_id")) {
                candidator = jsonObject.getString(column.getColumnName());
                break;
            }
            if(columnName.equals("check_group_id")) {
                candidatorDepart = jsonObject.getString(column.getColumnName());
                break;
            }
        }
        if(StringUtils.isEmpty(candidator) && StringUtils.isEmpty(candidatorDepart)) {
            return AjaxResult.error(-1, "没有候选人或者组！");
        }
        int type =  0;
        List<Long> ids = new ArrayList<>();
        // 候选人
        if(StringUtils.isNotEmpty(candidator)) {
            type = 1;
            String[] idArrs = candidator.split(",");
            for(String idArr : idArrs) {
                ids.add(Long.valueOf(idArr));
            }
        }
        // 候选组
        if(StringUtils.isNotEmpty(candidatorDepart)) {
            type = 2;
            String[] idArrs = candidatorDepart.split(",");
            for(String idArr : idArrs) {
                ids.add(Long.valueOf(idArr));
            }
        }

        List<JSONObject> jsonObjects = null;
        if(type == 1) {
            jsonObjects = selectService.selectCandidatorsById("sys_user", IdUtils.getPkName(genTable.getColumns()), ids, type);
        }
        JSONObject result = new JSONObject();
        if( jsonObjects == null) {
            return AjaxResult.error(-1, "没有候选人或组！");
        }
        result.put("approvers", jsonObjects);
        return new AjaxResult(1, 0, "", result);

    }
}
