package com.lz.modules.performance.controller;


import com.lz.common.emun.ChartOptType;
import com.lz.common.utils.R;
import com.lz.modules.app.dto.StaffSimpleDto;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.entity.FlowChart;
import com.lz.modules.flow.entity.FlowChartDetailRecord;
import com.lz.modules.flow.entity.FlowChartRole;
import com.lz.modules.flow.entity.FlowManager;
import com.lz.modules.flow.model.*;
import com.lz.modules.flow.req.FlowChartDetailRecordListReq;
import com.lz.modules.flow.req.FlowChartDetailRecordSimpleReq;
import com.lz.modules.flow.service.FlowChartDetailRecordService;
import com.lz.modules.flow.service.FlowChartRoleService;
import com.lz.modules.flow.service.FlowChartService;
import com.lz.modules.flow.service.FlowManagerService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/flowChart")
@Api(tags={"考核节点"})
@Slf4j
public class FlowChartController {


    @Autowired
    private FlowChartService flowChartService;

    @Autowired
    private FlowManagerService flowManagerService;

    @Autowired
    private FlowChartDetailRecordService flowChartDetailRecordService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private FlowChartRoleService flowChartRoleService;

    @GetMapping("/getByFlowManagerId")
    @ApiOperation("获取大流程节点")
    @ApiResponses({@ApiResponse(code = 200,message = "成功",response = FlowChartDto.class)})
    public R getByFlowManagerId(@RequestParam @ApiParam("流程id，绩效请传1")  Long id, @RequestParam @ApiParam(value = "考评组id，新建时传0", defaultValue = "0") Long groupId) {
        FlowManager flowManager = flowManagerService.selectFlowManagerById(id);
        if(flowManager != null){
            List<FlowChartDto> flowChartDtos = flowChartService.selectFlowChartDtoByFlowManagerId(flowManager.getId());
            for (FlowChartDto dto:flowChartDtos
                 ) {
                List<FlowChartRoleDto> flowChartRoles = flowChartService.selectCanSetChartRoleByChartId(dto.getId());
                dto.setRoleDtos(flowChartRoles);
                if(groupId > 0){
                    //获取节点已保存的数据
                    FlowChartDetailRecordListDto flowChartDetailRecordListDto = new FlowChartDetailRecordListDto();
                    flowChartDetailRecordListDto.setEvaluationGroupId(groupId);
                    flowChartDetailRecordListDto.setId(dto.getId());
                    List<FlowChartDetailRecordSimpleDto> recordSimpleDtos = new ArrayList<>();
                    List<FlowChartDetailRecord> flowChartDetailRecords =
                            flowChartDetailRecordService.selectFlowChartDetailRecordByGroupIdAndChartId(groupId, dto.getId());

                    for (FlowChartDetailRecord record:flowChartDetailRecords
                    ) {
                        flowChartDetailRecordListDto.setStatus(record.getStatus());
                        FlowChartDetailRecordSimpleDto detailRecordSimpleDto = new FlowChartDetailRecordSimpleDto();

                        BeanUtils.copyProperties(record, detailRecordSimpleDto);
                        if(record.getOptType().intValue() == ChartOptType.APPOINT.getCode()
                                && record.getOptIds() != null
                                && record.getOptIds().length() > 0){
                            List<Long> ids = Arrays.stream(record.getOptIds().split(",")).map(new Function<String, Long>() {
                                @Override
                                public Long apply(String s) {
                                    return Long.parseLong(s);
                                }
                            }).collect(Collectors.toList());

                            //指定人员，搜索人员信息
                            List<StaffSimpleDto> staffSimpleDtos = staffService.selectStaffSimpleInfoByIds(ids);
                            detailRecordSimpleDto.setStaffs(staffSimpleDtos);

                        }
                        recordSimpleDtos.add(detailRecordSimpleDto);

                    }
                    flowChartDetailRecordListDto.setRecordSimpleDtos(recordSimpleDtos);
                    dto.setChartDetails(flowChartDetailRecordListDto);
                }
            }

            return R.ok().put("data",flowChartDtos);
        }
        return R.error("无相关流程");
    }

    /*@GetMapping("/getRoleByChatId")
    @ApiOperation("根据流程节点 Id获取相关权限")
    @ApiImplicitParam(name = "id",value = "节点id", required = true, dataType = "String",paramType = "query")
    @ApiResponses({@ApiResponse(code = 200,message = "成功",response = FlowChartRoleDto.class)})
    public R getRoleByChatId(@RequestParam Long id) {

        List<FlowChartRoleDto> flowCharts = flowChartService.selectChartRoleByChartId(id);
        return R.ok().put("data",flowCharts);
    }*/



     @PostMapping("/getById")
     public R getById(@RequestBody @ApiParam FlowChart flowChart) {
        flowChart = flowChartService.selectFlowChartById(flowChart.getId());
        return R.ok().put("data",flowChart);
     }

     @RequestMapping("/update")
     public R update(@RequestBody FlowChart flowChart) {
         flowChartService.updateFlowChartById(flowChart);
        return R.ok();
     }


     /*@PostMapping("/saveDetailProc")
     @ApiOperation("保存流程节点小流程")
     @ApiResponses({@ApiResponse(code = 200, message = "成功", response = FlowChartDetailRecord.class)})
     public R saveDetailProc(@RequestBody @ApiParam FlowChartDetailRecord flowChartDetailRecord) {
        if(flowChartDetailRecord.getId() != null && flowChartDetailRecord.getId().intValue() > 0){
            return updateDetailProc(flowChartDetailRecord);
        }
        flowChartDetailRecordService.insertFlowChartDetailRecord(flowChartDetailRecord);
        return R.ok().put("data", flowChartDetailRecord);
     }*/

    @PostMapping("/saveDetailProcs")
    @ApiOperation("保存流程节点小流程列表")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = FlowChartDetailRecord.class)})
    public R saveDetailProcs(@RequestBody @ApiParam FlowChartDetailRecordListReq flowChartDetailRecordListReq) {
        log.info("保存流程小结点接受的数据{}", flowChartDetailRecordListReq);
        if(flowChartDetailRecordListReq.getRecordSimpleDtos() != null && flowChartDetailRecordListReq.getRecordSimpleDtos().size() > 0){
            List<FlowChartDetailRecord> inserts = new ArrayList<>();
            List<FlowChartDetailRecord> updaes = new ArrayList<>();

            int index = 0;
            for (FlowChartDetailRecordSimpleReq req:flowChartDetailRecordListReq.getRecordSimpleDtos()
            ) {
                FlowChartDetailRecord flowChartDetailRecord = new FlowChartDetailRecord();
                BeanUtils.copyProperties(req, flowChartDetailRecord);
                flowChartDetailRecord.setChartId(flowChartDetailRecordListReq.getId());



                flowChartDetailRecord.setEvaluationGroupId(flowChartDetailRecordListReq.getEvaluationGroupId());
                flowChartDetailRecord.setStepIndex(index);
                if(flowChartDetailRecord.getStepType() == null){//添加时默认没有设置步骤类型，那么设置成一次
                    flowChartDetailRecord.setStepType(0);
                }
                flowChartDetailRecord.setStatus(flowChartDetailRecordListReq.getStatus());
                if(flowChartDetailRecord.getId() != null && flowChartDetailRecord.getId().intValue() > 0){
                    updaes.add(flowChartDetailRecord);
                }else{

                    inserts.add(flowChartDetailRecord);
                }
                if(flowChartDetailRecord.getIsDelete() == null || flowChartDetailRecord.getIsDelete().intValue() == 0){
                    //本节点没有删除，那么顺序++
                    index++;
                }

            }
            if(inserts.size() > 0){
                flowChartDetailRecordService.insertFlowChartDetailRecords(inserts);
            }
            if(updaes.size() > 0){
                flowChartDetailRecordService.updateBatchById(updaes);//.updateCoverFlowChartDetailRecordByIds(updaes);
            }
        }


        return R.ok();
    }

    @PostMapping("/updateDetailProc")
    public R updateDetailProc(@RequestBody @ApiParam FlowChartDetailRecord flowChartDetailRecord) {
        flowChartDetailRecordService.updateFlowChartDetailRecordById(flowChartDetailRecord);
        return R.ok();
    }

    @GetMapping("/deleteDetailProc")
    @ApiOperation("删除流程节点小流程")
    public R deleteDetailProc(@RequestParam @ApiParam(value = "节点流程id", name = "id") Long id) {
        flowChartDetailRecordService.deleteFlowChartDetailRecordById(id);
        return R.ok();
    }

   /* @GetMapping("/getDetailProc")
    @ApiOperation("获取已保存的考核节点详情")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = FlowChartDetailRecordDto.class)})
    public R getDetailProc(@RequestParam @ApiParam("考核组id") Long groupId, @RequestParam @ApiParam("节点id") Long chartId) {

        return R.ok().put("data", flowChartDetailRecordDtos);
    }

    private List<FlowChartDetailRecordDto> getChartDetailRecort(Long chartId, Long groupId){
        List<FlowChartDetailRecord> flowChartDetailRecords = flowChartDetailRecordService.selectFlowChartDetailRecordByGroupIdAndChartId(groupId, chartId);
        List<FlowChartDetailRecordDto> flowChartDetailRecordDtos = new ArrayList<>();
        for (FlowChartDetailRecord record:flowChartDetailRecords
        ) {
            FlowChartDetailRecordDto dto = new FlowChartDetailRecordDto();
            BeanUtils.copyProperties(record, dto);
            if(record.getOptType().intValue() == ChartOptType.APPOINT.getCode()
                    && record.getOptIds() != null
                    && record.getOptIds().length() > 0){
                List<Long> ids = Arrays.stream(record.getOptIds().split(",")).map(new Function<String, Long>() {
                    @Override
                    public Long apply(String s) {
                        return Long.parseLong(s);
                    }
                }).collect(Collectors.toList());

                //指定人员，搜索人员信息
                List<StaffSimpleDto> staffSimpleDtos = staffService.selectStaffSimpleInfoByIds(ids);
                dto.setStaffs(staffSimpleDtos);
            }
            flowChartDetailRecordDtos.add(dto);
        }
        return flowChartDetailRecordDtos;
    }*/

    @RequestMapping("/delete")
    public R list(@RequestBody Long id) {
        flowChartService.deleteFlowChartById(id);
        return R.ok();
     }
}
