/*
 *      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.business.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springblade.business.entity.UserOpinion;
import org.springblade.business.service.IUserOpinionService;
import org.springblade.business.vo.UserOpinionFlowVO;
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.DateUtil;
import org.springblade.manager.dto.SaveUserInfoByProjectDTO;
import org.springblade.manager.feign.ProjectAssignmentUserClient;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import org.springblade.business.entity.UserOpinionFlow;
import org.springblade.business.service.IUserOpinionFlowService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 用户意见处理流程表 控制器
 *
 * @author BladeX
 * @since 2022-05-25
 */
@RestController
@AllArgsConstructor
@RequestMapping("/userOpinionFlow")
@Api(value = "用户意见处理流程表", tags = "用户意见处理流程表接口")
public class UserOpinionFlowController extends BladeController {

	private final IUserOpinionFlowService userOpinionFlowService;

	private final IUserOpinionService userOpinionService;

	private final ProjectAssignmentUserClient projectAssignmentUserClient;

	private final IUserClient userClient;

	/**
	 * 统合接口
	 * @param oldEndFlow 流程图的最后一个节点ID
	 * @param userOpinionId 工单的最后一个节点ID
	 * @param type 所选类型，1满意，2不满意并再次提交，3不满意并投诉
	 */
	@PostMapping("/disposeUserOpinionFeedback")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "统合处理意见接口")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "oldEndFlow", value = "流程图的最后一个节点ID", required = true),
			@ApiImplicitParam(name = "userOpinionId", value = "工单的ID", required = true),
			@ApiImplicitParam(name = "type", value = "所选类型，1满意，2不满意并再次提交，3不满意并投诉", required = true)
	})
	public R<Boolean> disposeUserOpinionFeedback(@RequestParam String oldEndFlow, @RequestParam String userOpinionId, @RequestParam Integer type){
		switch (type){
			case 1:
				//满意
				return this.updateCurrentUserOpinionFlow(oldEndFlow, 1);
			case 2:
				//不满意并再次提交
				return this.saveNewCurrentUserOpinionFlow(userOpinionId, oldEndFlow);
			case 3:
				return this.updateCurrentUserOpinionFlow(oldEndFlow, 3);
			default:
				break;
		}
		return R.data(false);
	}

	/**
	 * 处理满意或不满意并投诉
	 * @param oldEndFlow 当前流程的最后一个节点ID
	 * @return 修改结果
	 */
	private R<Boolean> updateCurrentUserOpinionFlow(String oldEndFlow, Integer type){
		UserOpinionFlow oldFlow = this.userOpinionFlowService.getById(oldEndFlow);
		oldFlow.setEvaluation(type);
		return R.data(this.userOpinionFlowService.updateById(this.setUserData(oldFlow, false)));
	}

	/**
	 * 新增当前工单的新处理流程（即触发不满意并再次提交解决）
	 * @param userOpinionId 工单ID
	 * @param oldEndFlow 当前流程的最后一个节点ID
	 * @return 新增结果
	 */
	private R<Boolean> saveNewCurrentUserOpinionFlow(String userOpinionId, String oldEndFlow){

		if(StringUtils.isNotEmpty(userOpinionId)){
			//修改上一环节的evaluation,更改为2（不满意并再次提交）
			UserOpinionFlow oldFlow = this.userOpinionFlowService.getById(oldEndFlow);
			oldFlow.setEvaluation(2);
			this.setUserData(oldFlow, false);

			//获取工单信息，增加处理流程次数
			UserOpinion userOpinion = this.userOpinionService.getById(userOpinionId);
			Integer newNumber = userOpinion.getNumber() + 1;
			userOpinion.setNumber(newNumber);

			//获取前一个流程的维护人员
			UserOpinionFlow leftFlow = this.userOpinionFlowService.queryLeftFlowManageUser(newNumber - 1, userOpinionId);

			String manageUserName = "admin", manegeUserPhone = "";
			Long manageUser = 1123598821738675201L;
			if(leftFlow != null){
				manageUser = leftFlow.getManageUser();
				manageUserName = leftFlow.getManageUserName();
				manegeUserPhone = leftFlow.getManageUserPhone();
			}

			//生成新流程
			List<UserOpinionFlow> saveFlowList = new ArrayList<>();
			String manageTime = DateUtil.format(DateUtils.addDays(new Date(), 5), "yyyy-MM-dd");
			//提交成功环节
			saveFlowList.add(this.setUserData(new UserOpinionFlow(Long.parseLong(userOpinionId), 2, newNumber, 1, "已提交", "已成功提交您的工单信息", manageTime, manageUser, manageUserName, manegeUserPhone), true));
			//分配维护人员环节
			saveFlowList.add(this.setUserData(new UserOpinionFlow(Long.parseLong(userOpinionId), 1, newNumber, 2, "已分配专属客服", "客服："+manageUserName+"<br>电话：" + manegeUserPhone, manageTime, manageUser, manageUserName, manegeUserPhone), true));
			//进入人工预处理环节
			saveFlowList.add(this.setUserData(new UserOpinionFlow(Long.parseLong(userOpinionId), 0, newNumber, 3, "进入人工预处理环节", "预计" + manageTime + "之前完成", manageTime, manageUser, manageUserName, manegeUserPhone), true));
			//问题已解决
			saveFlowList.add(this.setUserData(new UserOpinionFlow(Long.parseLong(userOpinionId), 0, newNumber, 4, "问题已解决", null, manageTime, manageUser, manageUserName, manegeUserPhone), true));

			//修改流程
			this.userOpinionFlowService.updateById(oldFlow);
			//新增流程
			this.userOpinionFlowService.saveBatch(saveFlowList);
			//修改主表数据
			return R.data(this.userOpinionService.updateById(userOpinion));
		}

		return R.data(false);
	}

	/**
	 * 获取当前工单的最新流程
	 * @param userOpinionId 用户工单ID
	 * @return 最新流程集合
	 */
	@GetMapping("/queryCurrentUserOpinionFlowByUserOpinionId")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取当前工单的最新流程")
	public R<List<UserOpinionFlowVO>> queryCurrentUserOpinionFlowByUserOpinionId(@RequestParam String userOpinionId){
		if(StringUtils.isNotEmpty(userOpinionId)){
			//获取当前工单的最新流程次数
			UserOpinion userOpinion = this.userOpinionService.getById(userOpinionId);

			return R.data(this.userOpinionFlowService.queryCurrentUserOpinionFlowByUserOpinionId(userOpinionId, userOpinion.getNumber()));
		}
		return R.data(null);
	}

	//设置登录用户信息
	private UserOpinionFlow setUserData(UserOpinionFlow userOpinionFlow, boolean isCreate){
		//获取当前登录人
		BladeUser user = AuthUtil.getUser();
		//记录操作人信息
		if(isCreate){
			userOpinionFlow.setCreateUser(user.getUserId());
			userOpinionFlow.setCreateDept(user.getDeptId().contains(",") ? Long.parseLong(user.getDeptId().split(",")[0]) : Long.parseLong(user.getDeptId()));
		} else {
			userOpinionFlow.setUpdateUser(user.getUserId());
			userOpinionFlow.setUpdateTime(new Date());
		}
		return userOpinionFlow;
	}

}
