package com.ankaibei.workFlow.webadmin.ankaibei.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ankaibei.workFlow.common.core.object.ResponseResult;
import com.ankaibei.workFlow.common.core.object.TokenData;
import com.ankaibei.workFlow.common.flow.constant.FlowConstant;
import com.ankaibei.workFlow.common.flow.constant.FlowTaskStatus;
import com.ankaibei.workFlow.common.flow.dto.FlowTaskCommentDto;
import com.ankaibei.workFlow.common.flow.model.FlowEntry;
import com.ankaibei.workFlow.common.flow.model.FlowEntryPublish;
import com.ankaibei.workFlow.common.flow.online.controller.FlowOnlineOperationController;
import com.ankaibei.workFlow.common.flow.util.FlowOperationHelper;
import com.ankaibei.workFlow.common.flow.vo.TaskInfoVo;
import com.ankaibei.workFlow.webadmin.ankaibei.entity.*;
import com.ankaibei.workFlow.webadmin.ankaibei.enums.CodeEnum;
import com.ankaibei.workFlow.webadmin.ankaibei.mapper.*;
import com.ankaibei.workFlow.webadmin.ankaibei.service.ManHourService;
import com.ankaibei.workFlow.webadmin.ankaibei.utils.FlowTaskStart;
import com.ankaibei.workFlow.webadmin.ankaibei.vo.ManHourInfoVo;
import com.ankaibei.workFlow.webadmin.ankaibei.vo.ResMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lwq
 * @version 1.0
 * @description:
 * @date 2022/9/21 15:33
 */
@Service
public class ManHourServiceImpl implements ManHourService {

    @Resource
    private ManHourMapper manHourMapper;
    @Autowired
    private FlowTaskStart flowTaskStart;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private ManHourJobMapper manHourJobMapper;
    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Override
    public ResMsg findManHourAll(Integer pageIndex, Integer pageSize, ManHourInfoEntity manHourInfoEntity) {
        Pageable page = PageRequest.of(pageIndex - 1, pageSize);
        String endDate = null;
        if (manHourInfoEntity.getEndDate() != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            endDate = dateFormat.format(manHourInfoEntity.getEndDate()) + " 23:59:59";
        }

        Page<Map<String, String>> manHourAll = manHourMapper.findManHourAll(manHourInfoEntity.getFlowTaskStatus(), manHourInfoEntity.getCreateDate(), endDate, page);
        return new ResMsg(CodeEnum.OK, ResMsg.getMap(manHourAll.map(map -> {
            Map<Object, Object> map1 = new HashMap<>();
            map1.putAll(map);
            String projectId = map.get("projectName");
            Optional<ProjectInfoEntity> byId = projectInfoMapper.findById(Integer.valueOf(projectId));
            map1.put("projectName", byId.orElse(null) != null ? byId.orElse(null).getProjectName() : null);
            return map1;
        }).getContent(), manHourAll.getTotalElements()));
    }

    @Override
    public ResMsg addManHour(String projectId, ManHourInfoEntity manHourInfoEntity, List<ManHourJobInfo> manHours) {
        Optional<UserInfoEntity> byId1 = userInfoMapper.findById(manHourInfoEntity.getCreateUser());
        manHourInfoEntity.setProjectName(projectId);
        manHourInfoEntity.setProjectUser(byId1.orElse(null) != null ? byId1.orElse(null).getShowName() : null);
        //manHourInfoEntity.setManStatus("1");

        /**
         * 调用人员工时申请流程的启动
         * 获取流程开始节点之后的第一个任务节点的数据
         * param processDefinitionKey 项目人员工时接口审批流程--流程标识。
         */
        String processDefinitionKey = "manHourCountApply";
        ResponseResult<FlowEntry> flowEntryResult = flowTaskStart.verifyAndGetFlowEntry(processDefinitionKey);
        if (!flowEntryResult.isSuccess()) {
            return ResMsg.newInstance(CodeEnum.FAIL, flowEntryResult);
        }
        FlowEntryPublish flowEntryPublish = flowEntryResult.getData().getMainFlowEntryPublish();
        String initTaskInfo = flowEntryPublish.getInitTaskInfo();
        com.ankaibei.workFlow.common.flow.vo.TaskInfoVo taskInfo = StrUtil.isBlank(initTaskInfo)
                ? null : JSON.parseObject(initTaskInfo, TaskInfoVo.class);
        if (taskInfo != null) {
            String loginName = TokenData.takeFromRequest().getLoginName();
            taskInfo.setAssignedMe(StrUtil.equalsAny(
                    taskInfo.getAssignee(), loginName, FlowConstant.START_USER_NAME_VAR));
        }
        //用户在表单页面配置的操作按钮
        FlowTaskCommentDto flowTaskCommentDto = new FlowTaskCommentDto();
        //提交后进行到第二个节点
        flowTaskCommentDto.setApprovalType("agree");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("project_user", manHourInfoEntity.getProjectUser());
        stringObjectHashMap.put("project_name", manHourInfoEntity.getProjectName());
        stringObjectHashMap.put("man_hour", "总计**时");
        stringObjectHashMap.put("create_date", manHourInfoEntity.getCreateDate());
        stringObjectHashMap.put("create_user", manHourInfoEntity.getCreateUser());
        stringObjectHashMap.put("man_id", manHourInfoEntity.getManId());
        JSONObject masterData = (JSONObject) JSONObject.toJSON(stringObjectHashMap);
        Map<String, String> map = flowTaskStart.startAndTakeUserTaskSS(processDefinitionKey, flowTaskCommentDto, null, masterData, null, null).getData();

        manHourInfoEntity.setProcessInstanceId(map.get("processInstanceId"));
        manHourInfoEntity.setProcessDefinitionId(map.get("processDefinitionId"));
        manHourInfoEntity.setFlowTaskStatus(FlowTaskStatus.SUBMITTED);
        BigDecimal day = new BigDecimal(0);
        for (ManHourJobInfo manHour : manHours) {
            day = day.add(manHour.getDay());
        }
        manHourInfoEntity.setManHour(day);
        manHourInfoEntity.setCreateTime(new Date());
        ManHourInfoEntity save = manHourMapper.save(manHourInfoEntity);
        for (ManHourJobInfo manHour : manHours) {
            manHour.setManId(save.getManId());
            manHourJobMapper.save(manHour);
        }

        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public ResMsg deleteManHour(List<ManHourInfoVo> manHourInfoVos) {

        for (ManHourInfoVo info : manHourInfoVos) {
            manHourMapper.deleteById(info.getManId());
            manHourJobMapper.deleteByManIdEquals(info.getManId());
        }

        return null;
    }

}
