/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.bank.autodata.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.bank.autodata.dto.AutoDataDTO;
import org.springblade.bank.autodata.entity.ApproveBean;
import org.springblade.bank.autodata.entity.AutoData;
import org.springblade.bank.autodata.service.IAutoDataService;
import org.springblade.bank.autodata.vo.AutoDataVO;
import org.springblade.bank.autodata.wrapper.AutoDataWrapper;
import org.springblade.bank.autosetting.entity.AutoSetting;
import org.springblade.bank.autosetting.service.IAutoSettingService;
import org.springblade.bank.autostruct.entity.AutoStruct;
import org.springblade.bank.autostruct.service.IAutoStructService;
import org.springblade.bank.constant.*;
import org.springblade.bank.constant.Process;
import org.springblade.common.cache.UserCache;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-09-23
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/autodata")
@Api(value = "", tags = "接口")
public class AutoDataController extends BladeController {

	private final IAutoDataService autoDataService;
	private final IAutoStructService autoStructService;
	private final IDeptService deptService;
	private final IUserService userService;
	private final IAutoSettingService autoSettingService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入autoData")
	public R<AutoDataVO> detail(AutoData autoData) {
		AutoData detail = autoDataService.getOne(Condition.getQueryWrapper(autoData));
		return R.data(AutoDataWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入autoData")
	public R<IPage<AutoDataVO>> list(AutoData autoData, Query query) {
		IPage<AutoData> pages = autoDataService.page(Condition.getPage(query), Condition.getQueryWrapper(autoData));
		return R.data(AutoDataWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入autoData")
	public R<IPage<AutoDataVO>> page(AutoDataVO autoData, Query query) {
		BladeUser user = AuthUtil.getUser();
		//當前部門id
		Dept dept = deptService.getById(AuthUtil.getDeptId());
		if (dept.getOrgNo().startsWith("999")){
			List<Long> deptChildIds = deptService.getDeptChildIds(dept.getId());
			String[] deptArr = new String[deptChildIds.size()];
			for (int i = 0; i < deptChildIds.size(); i++) {
				deptArr[i] = deptChildIds.get(i) + "";
			}
			autoData.setUserDeptList(deptArr);
		}else{
			String[] deptArr = new String[1];
			deptArr[0] = AuthUtil.getDeptId();
			autoData.setUserDeptList(deptArr);
		}
//		autoData.setCurrentDeptId(AuthUtil.getDeptId());
		autoData.setCurrentuserId(AuthUtil.getUserId());

		Assert.isTrue(autoData.getTableId() != null, "表ID不能為空！");
		AutoStruct autoStruct = autoStructService.getById(autoData.getTableId());
		//多個角色問題
		String[] userRoles = user.getRoleId().split(",");
		autoData.setUserRoleList(userRoles);
		boolean isManageRole = false;
		for (int i = 0; i < userRoles.length; i++) {
			String roleId = userRoles[i];
			isManageRole = isManageRole || autoStruct.getManageRoleId().contains(roleId);
		}
		//是否管理員角色
		autoData.setIsManageRole(isManageRole);
		IPage<AutoDataVO> pages = autoDataService.selectAutoDataPage(Condition.getPage(query), autoData);
		List<AutoDataVO> records = pages.getRecords();
		List<AutoDataVO> list = new ArrayList<>();
		boolean flag = ApproveSwitch.OPEN.equals(autoStruct.getApproveSwitch()) && ApproveType.SERIAL.equals(autoStruct.getApproveType()) && SettingType.GRADUALLY.equals(autoStruct.getSettingType());
		for (int i = 0; i < records.size(); i++) {
			AutoDataVO autoDataVO = new AutoDataVO();
			BeanUtil.copyProperties(records.get(i), autoDataVO);
			User createUser = UserCache.getUser(autoDataVO.getCreateUser());
			if (createUser != null){
				autoDataVO.setCreateUserName(createUser.getName());
			}
			if (flag) {
				AutoSetting autoSetting = autoSettingService.getUserSettingByBusinessId(autoDataVO.getId());
				if (autoSetting != null) {
					autoDataVO.setCreateSettingType(autoSetting.getCreateSettingType());
					autoDataVO.setCreateSetting(autoSetting.getSetting());
				}
			}
			list.add(autoDataVO);
		}
		pages.setRecords(list);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入autoData")
	public R save(@Valid @RequestBody AutoDataDTO autoData) {
		autoDataService.save(autoData);
		autoData.setProcess(Process.FIRST);
		autoData.setProcessStatus(ProcessStatus.TOBEREVIEWED);

		Long tableId = autoData.getTableId();
		AutoStruct struct = autoStructService.getById(tableId);
//		if (struct.getApproveType().equals(1) && struct.getSettingType().equals(1)){
		if (ApproveSwitch.OPEN.equals(struct.getApproveSwitch())){
			JSONArray jsonArray = JSONUtil.parseArray(StringUtil.isBlank(struct.getSetting()) ? "[]" : struct.getSetting());
			// 串行 & 统一设置
			if (ApproveType.SERIAL.equals(struct.getApproveType())){
				if ( SettingType.UNIFIED.equals(struct.getSettingType())){
					// 取出下一個審批人
					Map<String, String > tobePerson = (Map<String, String>) jsonArray.get(0);
					autoData.setReceiverId(tobePerson.get("id"));
					autoData.setReceiverName(tobePerson.get("name"));
					autoData.setReceiverNo(tobePerson.get("ehr"));
				}else {
					// 逐級設置
					AutoSetting autoSetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
					if (autoSetting == null) {
						autoSetting = new AutoSetting();
						autoSetting.setTableId(tableId);
					}
					autoSetting.setCreateSettingType(autoData.getCreateSettingType());
					if (CreateSettingType.All.equals(autoData.getCreateSettingType())){
						autoSetting.setSetting(autoData.getCreateSetting());
						JSONArray settingArray = JSONUtil.parseArray(autoData.getCreateSetting());
						Map<String, String> receiverMap = (Map<String, String>) settingArray.get(0);
						autoData.setReceiverId(receiverMap.get("id"));
						autoData.setReceiverName(receiverMap.get("name"));
						autoData.setReceiverNo(receiverMap.get("ehr"));
					}else{
						JSONArray settingArray = new JSONArray();
						Map<String, String > tobePerson = new HashMap<>();
						tobePerson.put("id", autoData.getReceiverId());
						tobePerson.put("name", autoData.getReceiverName());
						tobePerson.put("ehr", autoData.getReceiverNo());
						settingArray.set(tobePerson);
						autoSetting.setSetting(settingArray.toJSONString(0));

						autoData.setReceiverId(autoData.getReceiverId());
						autoData.setReceiverName(autoData.getReceiverName());
						autoData.setReceiverNo(autoData.getReceiverNo());
					}
					autoSetting.setBusinessId(autoData.getId());
					autoSettingService.saveOrUpdate(autoSetting);
				}
			}
			// 并行
			if (ApproveType.PARALLEL.equals(struct.getApproveType())){
				List<String> idArr = new ArrayList<>();
				List<String> nameArr = new ArrayList<>();
				List<String> ehrArr = new ArrayList<>();
				for (int i = 0; i < jsonArray.size(); i++) {
					Map<String, String > person = (Map<String, String>) jsonArray.get(i);
					idArr.add(person.get("id"));
					nameArr.add(person.get("name"));
					ehrArr.add(person.get("ehr"));
				}
				autoData.setReceiverId(StringUtil.join(idArr, ","));
				autoData.setReceiverName(StringUtil.join(nameArr, ","));
				autoData.setReceiverNo(StringUtil.join(ehrArr, ","));
			}
			Assert.isTrue(!autoData.getReceiverId().contains(AuthUtil.getUserId()+""), "審批人不能為本人！");
		}

		return R.status(autoDataService.saveOrUpdate(autoData));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入autoData")
	public R update(@Valid @RequestBody AutoDataDTO autoData) {
		autoData.setProcess(Process.FIRST);
		autoData.setProcessStatus(ProcessStatus.TOBEREVIEWED);

		Long tableId = autoData.getTableId();
		AutoStruct struct = autoStructService.getById(tableId);
		if (ApproveSwitch.OPEN.equals(struct.getApproveSwitch())){
			JSONArray jsonArray = JSONUtil.parseArray(StringUtil.isBlank(struct.getSetting()) ? "[]" : struct.getSetting());
			// 串行 & 统一设置
			if (ApproveType.SERIAL.equals(struct.getApproveType())){
				if ( SettingType.UNIFIED.equals(struct.getSettingType())){
					// 取出下一個審批人
					Map<String, String > tobePerson = (Map<String, String>) jsonArray.get(0);
					autoData.setReceiverId(tobePerson.get("id"));
					autoData.setReceiverName(tobePerson.get("name"));
					autoData.setReceiverNo(tobePerson.get("ehr"));
				}else {
					// 逐級設置
					AutoSetting autoSetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
					if (autoSetting == null) {
						autoSetting = new AutoSetting();
						autoSetting.setTableId(tableId);
					}
					autoSetting.setCreateSettingType(autoData.getCreateSettingType());
					if (CreateSettingType.All.equals(autoData.getCreateSettingType())){
						autoSetting.setSetting(autoData.getCreateSetting());
						JSONArray settingArray = JSONUtil.parseArray(autoData.getCreateSetting());
						Map<String, String> receiverMap = (Map<String, String>) settingArray.get(0);
						autoData.setReceiverId(receiverMap.get("id"));
						autoData.setReceiverName(receiverMap.get("name"));
						autoData.setReceiverNo(receiverMap.get("ehr"));
					}else{
						JSONArray settingArray = new JSONArray();
						Map<String, String > tobePerson = new HashMap<>();
						tobePerson.put("id", autoData.getReceiverId());
						tobePerson.put("name", autoData.getReceiverName());
						tobePerson.put("ehr", autoData.getReceiverNo());
						settingArray.set(tobePerson);
						autoSetting.setSetting(settingArray.toJSONString(0));

						autoData.setReceiverId(autoData.getReceiverId());
						autoData.setReceiverName(autoData.getReceiverName());
						autoData.setReceiverNo(autoData.getReceiverNo());
					}
					autoSetting.setBusinessId(autoData.getId());
					autoSettingService.saveOrUpdate(autoSetting);
				}
			}
			// 并行
			if (ApproveType.PARALLEL.equals(struct.getApproveType())){
				List<String> idArr = new ArrayList<>();
				List<String> nameArr = new ArrayList<>();
				List<String> ehrArr = new ArrayList<>();
				for (int i = 0; i < jsonArray.size(); i++) {
					Map<String, String > person = (Map<String, String>) jsonArray.get(i);
					idArr.add(person.get("id"));
					nameArr.add(person.get("name"));
					ehrArr.add(person.get("ehr"));
				}
				autoData.setReceiverId(StringUtil.join(idArr, ","));
				autoData.setReceiverName(StringUtil.join(nameArr, ","));
				autoData.setReceiverNo(StringUtil.join(ehrArr, ","));
			}
			Assert.isTrue(!autoData.getReceiverId().contains(AuthUtil.getUserId()+""), "審批人不能為本人！");
		}

		return R.status(autoDataService.updateById(autoData));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入autoData")
	public R submit(@Valid @RequestBody AutoData autoData) {
		return R.status(autoDataService.saveOrUpdate(autoData));
	}


	/**
	 * 審批通過
	 */
	@PostMapping("/approveYes/{end}")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "審批通過", notes = "传入autoData")
	public R approveYes(@Valid @RequestBody AutoDataDTO autoData, @PathVariable("end") Boolean end) {
		Long tableId = autoData.getTableId();
		AutoStruct struct = autoStructService.getById(tableId);

		// 並行-直接把審批人信息追加到已審批人字段
		AutoData oldData = autoDataService.getById(autoData.getId());
		if (end){
			//逐級設置-清空節點審核人
			autoData.setProcessStatus(ProcessStatus.PASSED);
			/*if (struct.getSettingType().equals(SettingType.GRADUALLY)){
				AutoSetting autosetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
				autosetting.setSetting("");
				autoSettingService.updateById(autosetting);
			}*/
		} else {
			// 並行
			if (struct.getApproveType().equals(ApproveType.PARALLEL)){
				if (oldData.getApproveHistory() != null){
					JSONArray jsonArray = JSONUtil.parseArray(oldData.getApproveHistory());
					JSONArray jsonArray1 = JSONUtil.parseArray(struct.getSetting());
					if ((jsonArray.size()+1) == jsonArray1.size()){
						autoData.setProcessStatus(ProcessStatus.PASSED);
					}else{
						autoData.setProcessStatus(ProcessStatus.TOBEREVIEWED);
					}
				}
			}else {
				// 串行-統一設置-從設置中拿出相應位置的人員，填充到下一個審批人字段，process+1
				String settingStr = struct.getSetting();
				if (oldData.getProcess() < struct.getNum()){
					if (struct.getSettingType().equals(SettingType.UNIFIED)){
						JSONArray jsonArray = JSONUtil.parseArray(settingStr);
						// 取出下一個審批人
						Map<String, String > tobePerson = (Map<String, String>) jsonArray.get(oldData.getProcess());
						autoData.setReceiverId(tobePerson.get("id"));
						autoData.setReceiverName(tobePerson.get("name"));
						autoData.setReceiverNo(tobePerson.get("ehr"));
					}else {
						// 串行-逐級設置-把前端傳過來的審批人，保存到待審批人字段，保存，process+1
						AutoSetting autosetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
						Assert.notNull(autosetting, "找不到相應設置！");
						if (autosetting.getCreateSettingType().equals(CreateSettingType.All)){
							String setting = autosetting.getSetting();
							JSONArray settingArray = JSONUtil.parseArray(setting);
							Map<String, String > tobePerson = (Map<String, String>) settingArray.get(oldData.getProcess());
							autoData.setReceiverId(tobePerson.get("id"));
							autoData.setReceiverName(tobePerson.get("name"));
							autoData.setReceiverNo(tobePerson.get("ehr"));
						}else{
							Assert.isTrue(!autoData.getReceiverId().contains(AuthUtil.getUserId()+""), "審批人不能為本人！");
						}

						JSONArray jsonArray;
						if (StringUtil.isBlank(settingStr)){
							jsonArray = new JSONArray(1);
						}else{
							jsonArray = JSONUtil.parseArray(settingStr);
						}
						Map<String, String > tobePerson = new HashMap<>();
						tobePerson.put("id", autoData.getReceiverId());
						tobePerson.put("name", autoData.getReceiverName());
						tobePerson.put("ehr", autoData.getReceiverNo());
						jsonArray.set(tobePerson);
						String newSettingStr = jsonArray.toJSONString(0);
						struct.setSetting(newSettingStr);
						autoStructService.updateById(struct);
					}
				}

				autoData.setProcess(oldData.getProcess()+1);
				if (oldData.getProcess().equals(struct.getNum())){
					autoData.setProcessStatus(ProcessStatus.PASSED);
					/*if (struct.getSettingType().equals(SettingType.GRADUALLY)){
						AutoSetting autosetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
						autosetting.setSetting("");
						autoSettingService.updateById(autosetting);
					}*/
				}else{
					autoData.setProcessStatus(ProcessStatus.TOBEREVIEWED);
				}
			}
		}


		//審批記錄
		User user = userService.getById(AuthUtil.getUserId());
		if (StringUtil.isBlank(oldData.getApproveId())){
			autoData.setApproveId(user.getId()+"");
			autoData.setApproveName(user.getName());
			autoData.setApproveNo(user.getEhr());
		}else{
			autoData.setApproveId(oldData.getApproveId() + "," + user.getId());
			autoData.setApproveName(oldData.getApproveName() + "," + user.getName());
			autoData.setApproveNo(oldData.getApproveNo() + "," + user.getEhr());
		}
		ApproveBean approveBean = new ApproveBean();
		approveBean.setUserId(user.getId()+"");
		approveBean.setUserName(user.getName());
		approveBean.setUserEhr(user.getEhr());
		approveBean.setApprove(end ? Approve.AGREE_END : Approve.AGREE);
		approveBean.setRemark(autoData.getRemark());
		approveBean.setApproveTime(DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));

		String approveHistory = oldData.getApproveHistory();
		if (approveHistory == null){
			approveHistory = "[]";
		}
		JSONArray history = JSONUtil.parseArray(approveHistory);
		history.add(approveBean);
		autoData.setApproveHistory(history.toJSONString(0));

		return R.status(autoDataService.saveOrUpdate(autoData));
	}


	/**
	 * 審批駁回-退回
	 */
	@PostMapping("/approveReject")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "審批駁回-退回", notes = "传入autoData")
	public R approveReject(@Valid @RequestBody AutoDataDTO autoData) {
		AutoData oldData = autoDataService.getById(autoData.getId());
//		Assert.isTrue(!oldData.getProcess().equals(1), "無法駁回！因為已無路可退！");
		Long tableId = autoData.getTableId();
		AutoStruct struct = autoStructService.getById(tableId);
		User createUser = userService.getById(oldData.getCreateUser());

		//串行（並行無駁回）
		if (struct.getApproveType().equals(ApproveType.SERIAL)){
			// 串行-統一設置-從設置中拿出相應位置的人員，填充到下一個審批人字段，process-1
			//如果第一次审批就驳回
			autoData.setReceiverId(createUser.getId()+"");
			autoData.setReceiverName(createUser.getName());
			autoData.setReceiverNo(createUser.getEhr());

			if (struct.getSettingType().equals(SettingType.GRADUALLY)){
				// 逐級審批-需刪除之前所有審批人设置信息
				struct.setSetting(null);
				autoStructService.updateById(struct);
			}
			autoData.setProcess(Process.FIRST);
			autoData.setProcessStatus(ProcessStatus.REJECTED);

			//審批記錄
			User user = userService.getById(AuthUtil.getUserId());
			if (StringUtil.isBlank(oldData.getApproveId())){
				autoData.setApproveId(user.getId()+"");
				autoData.setApproveName(user.getName());
				autoData.setApproveNo(user.getEhr());
			}else{
				autoData.setApproveId(oldData.getApproveId() + "," + user.getId());
				autoData.setApproveName(oldData.getApproveName() + "," + user.getName());
				autoData.setApproveNo(oldData.getApproveNo() + "," + user.getEhr());
			}
			ApproveBean approveBean = new ApproveBean();
			approveBean.setUserId(user.getId()+"");
			approveBean.setUserName(user.getName());
			approveBean.setUserEhr(user.getEhr());
			approveBean.setApprove(Approve.REJECT);
			approveBean.setRemark(autoData.getRemark());
			approveBean.setApproveTime(DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));

			String approveHistory = oldData.getApproveHistory();
			if (approveHistory == null){
				approveHistory = "[]";
			}
			JSONArray history = JSONUtil.parseArray(approveHistory);
			history.add(approveBean);
			autoData.setApproveHistory(history.toJSONString(0));
		}

		return R.status(autoDataService.saveOrUpdate(autoData));
	}

	/**
	 * 審批不通过
	 */
	@PostMapping("/approveNo")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "審批不通过", notes = "传入autoData")
	public R approveNo(@Valid @RequestBody AutoDataDTO autoData) {
		Long tableId = autoData.getTableId();
		AutoStruct struct = autoStructService.getById(tableId);
		User user = userService.getById(AuthUtil.getUserId());

		// 並行-直接把審批人信息追加到已審批人字段
		AutoData oldData = autoDataService.getById(autoData.getId());
//		if (struct.getApproveType().equals(ApproveType.PARALLEL)) {
			if (StringUtil.isBlank(oldData.getApproveId())){
				autoData.setApproveId(user.getId()+"");
				autoData.setApproveName(user.getName());
				autoData.setApproveNo(user.getEhr());
			}else{
				autoData.setApproveId(oldData.getApproveId() + "," + user.getId());
				autoData.setApproveName(oldData.getApproveName() + "," + user.getName());
				autoData.setApproveNo(oldData.getApproveNo() + "," + user.getEhr());
			}
			autoData.setProcessStatus(ProcessStatus.FAIL);

			//審批記錄
			ApproveBean approveBean = new ApproveBean();
			approveBean.setUserId(user.getId()+"");
			approveBean.setUserName(user.getName());
			approveBean.setUserEhr(user.getEhr());
			approveBean.setApprove(Approve.DISAGREE);
			approveBean.setRemark(autoData.getRemark());
			approveBean.setApproveTime(DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));

			String approveHistory = oldData.getApproveHistory();
			if (approveHistory == null){
				approveHistory = "[]";
			}
			JSONArray history = JSONUtil.parseArray(approveHistory);
			history.add(approveBean);
			autoData.setApproveHistory(history.toJSONString(0));
//		}

		/*if (struct.getApproveType().equals(ApproveType.SERIAL)) {
			if (struct.getSettingType().equals(SettingType.GRADUALLY)){
				AutoSetting autosetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
				autosetting.setSetting("");
				autoSettingService.updateById(autosetting);
			}
		}*/

		return R.status(autoDataService.saveOrUpdate(autoData));
	}

	/**
	 * 直接結束流程
	 */
	@PostMapping("/setEnd")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "直接結束流程", notes = "传入id")
	public R setEnd(@ApiParam(value = "主键集合", required = true) @RequestParam String id) {
		AutoData autoData = autoDataService.getById(id);
		//審批記錄
		User user = userService.getById(AuthUtil.getUserId());
		ApproveBean approveBean = new ApproveBean();
		approveBean.setUserId(user.getId()+"");
		approveBean.setUserName(user.getName());
		approveBean.setUserEhr(user.getEhr());
		approveBean.setApprove(Approve.INTERRUPT_END);
//		approveBean.setRemark("管理員【" + user.getName() + "】"  + Approve.INTERRUPT_END);
		approveBean.setApproveTime(DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));

		String approveHistory = autoData.getApproveHistory();
		if (approveHistory == null){
			approveHistory = "[]";
		}
		JSONArray history = JSONUtil.parseArray(approveHistory);
		history.add(approveBean);
		autoData.setApproveHistory(history.toJSONString(0));

		// 逐級設置-清空節點審核人
		/*Long tableId = autoData.getTableId();
		AutoStruct struct = autoStructService.getById(tableId);
		if (struct.getApproveType().equals(ApproveType.SERIAL)) {
			if (struct.getSettingType().equals(SettingType.GRADUALLY)){
				AutoSetting autosetting = autoSettingService.getUserSettingByBusinessId(autoData.getId());
				autosetting.setSetting("");
				autoSettingService.updateById(autosetting);
			}
		}*/
		autoData.setProcessStatus(ProcessStatus.CLOSE);

		return R.status(autoDataService.saveOrUpdate(autoData));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(autoDataService.deleteLogic(Func.toLongList(ids)));
	}

}
