package com.tofly.flow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;

import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.flow.dto.FormDataDto;
import com.tofly.flow.dto.ProcessInfoDto;
import com.tofly.flow.dto.ProcessInstanceDto;
import com.tofly.flow.dto.ProcessNodeInfoDto;
import com.tofly.flow.dto.ProcessTemplateNodeInfoDto;
import com.tofly.flow.entity.FormData;
import com.tofly.flow.entity.FormInstance;
import com.tofly.flow.entity.ProcessInstance;
import com.tofly.flow.entity.ProcessInstanceNodeInfo;
import com.tofly.flow.entity.ProcessTemplate;
import com.tofly.flow.entity.ProcessTemplateNode;
import com.tofly.flow.service.FormDataService;
import com.tofly.flow.service.FormInstanceService;
import com.tofly.flow.service.IFileInfoService;
import com.tofly.flow.service.ProcessInstanceNodeInfoService;
import com.tofly.flow.service.ProcessInstanceService;
import com.tofly.flow.service.ProcessTemplateNodeService;
import com.tofly.flow.service.ProcessTemplateService;
import com.tofly.flow.vo.ApprovalNodeInfoVo;

import lombok.AllArgsConstructor;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;


import java.util.*;

/**
 * 流程表单接口
 *
 * @author zhoux
 */
@RestController
@AllArgsConstructor
@RequestMapping("/form")
@Api(tags="表单管理接口")
public class FormController {
 
    private final  FormDataService formDataService;
    
    private final  FormInstanceService formInstanceService;
    
    private final  IFileInfoService fileInfoService;
   
    /**
     * 表单赋值
     * @return ResultRespone
     */
    @ApiOperation(value = "表单赋值  listJson对象")
    @PostMapping("/formAssign")
    public ResultRespone formAssign(@RequestBody String objects) {    	
    	try {
    		List<FormData> dataList = JSONObject.parseArray(objects,FormData.class);
    		for(FormData formData:dataList) {
    			FormData data = formDataService.getOne(Wrappers.<FormData>lambdaQuery()
        				.eq(FormData::getFieldName,formData.getFieldName())
        				.eq(FormData::getFormId,formData.getFormId()));    		
        		if(null==data) {
        			formDataService.save(formData);
        		}else {
        			formData.setId(data.getId());
        			formDataService.updateById(formData);
        		}
    		}
        	return ResultRespone.success("赋值成功");
    	}catch (Exception e) {
    		e.printStackTrace();
    		return ResultRespone.failed(e.getMessage());
		}
    }
    
    
    /**
     * 附件传值
     * @return ResultRespone
     */
    @ApiOperation(value = "附件传值")
    @PostMapping("/formFilesAssign")
    public ResultRespone formFilesAssign(FormDataDto formDataDto,
    		@RequestPart(required = false) @ApiParam("附件列表") List<MultipartFile> files) {    	
    	try {
    	    		
    		FormData data = formDataService.getOne(Wrappers.<FormData>lambdaQuery()
    				.eq(FormData::getFieldName,formDataDto.getFieldName())
    				.eq(FormData::getFormId,formDataDto.getFormId()));   
    		if(null==data) {
    			FormData saveData =new FormData();
    			saveData.setFormId(formDataDto.getFormId());
    			saveData.setFieldName(formDataDto.getFieldName());		
    			
    			List<HashMap> fileList = null;
    			
    			if(StringUtil.isEmpty(formDataDto.getFieldValue())) {
    				fileList = new ArrayList<HashMap>();
    			}else {
    				fileList = JSONObject.parseArray(formDataDto.getFieldValue(), HashMap.class);  
    			}    			
    			  			
    			String fileUploadString = fileInfoService.uploadFiles(files,saveData.getFieldDataValue()
    	                ,saveData.getFieldDataValue(),"/dcsw/flow/files/","TF_YWPN_APPLY_INSTALL");    			
    			List<HashMap> fileUploadList = JSONObject.parseArray(fileUploadString, HashMap.class);			
    			fileList.addAll(fileUploadList);
    			saveData.setFieldDataValue(JSON.toJSONString(fileList));			
    			formDataService.save(saveData);
    		}else {
    			formDataService.removeById(data.getId());
    			
    			FormData saveData =new FormData();
    			saveData.setId(data.getId());
    			saveData.setFormId(formDataDto.getFormId());
    			saveData.setFieldName(formDataDto.getFieldName());
    			List<HashMap> fileList = null;
    			
    			if(StringUtil.isEmpty(formDataDto.getFieldValue())) {
    				fileList = new ArrayList<HashMap>();
    			}else {
    				fileList = JSONObject.parseArray(formDataDto.getFieldValue(), HashMap.class);  
    			}    	  			
    			String fileUploadString = fileInfoService.uploadFiles(files,saveData.getFieldDataValue()
    	                ,saveData.getFieldDataValue(),"/dcsw/flow/files/","TF_YWPN_APPLY_INSTALL");    			
    			List<HashMap> fileUploadList = JSONObject.parseArray(fileUploadString, HashMap.class);			
    			fileList.addAll(fileUploadList);
    			saveData.setFieldDataValue(JSON.toJSONString(fileList));	
    			formDataService.save(saveData);
    		}
        	return ResultRespone.success("附件保存成功");
    	}catch (Exception e) {
    		e.printStackTrace();
    		return ResultRespone.failed(e.getMessage());
		}
    }
       
    /**
     * 获取表单实例ID获取相应表单内容和对应的值
     * @return ResultRespone
     */
    @ApiOperation(value = "获取表单实例ID获取相应表单和对应的值")
    @GetMapping("/queryFormData/{id}")
    public ResultRespone queryProcessTemplateList(@PathVariable("id") Long formInstanceId) {    	
    	try {
    		List<Map<String,Object>> dataList= formInstanceService.getFormData(formInstanceId);
        	return ResultRespone.success(dataList);
    	}catch (Exception e) {
    		return ResultRespone.failed(e.getMessage());
		}
    }
}