package org.linlinjava.jz.admin.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.jz.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.jz.admin.service.AdminCustomerOrderService;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.db.domain.CustomerOrder;
import org.linlinjava.jz.db.domain.HmButlerTaskParent;
import org.linlinjava.jz.db.domain.HmNotice;
import org.linlinjava.jz.db.domain.JzDmTicketResult;
import org.linlinjava.jz.db.domain.JzTicket;
import org.linlinjava.jz.db.dto.hm.ButlerTaskTeachAddDto;
import org.linlinjava.jz.db.dto.hm.HmTaskListData;
import org.linlinjava.jz.db.dto.hm.HmbutlerTaskClockDto;
import org.linlinjava.jz.db.service.JzDmTicketResultService;
import org.linlinjava.jz.db.service.JzSkillGroupService;
import org.linlinjava.jz.db.service.hm.HmButlerTaskChildService;
import org.linlinjava.jz.db.service.hm.HmButlerTaskTeachService;
import org.linlinjava.jz.db.service.hm.HmNoticeService;
import org.linlinjava.jz.db.util.HmResponseUtil;
import org.linlinjava.jz.db.util.TicketStatusConstant;
import org.linlinjava.jz.db.util.hm.HmNoticeEnum;
import org.linlinjava.jz.db.util.hm.HmTicketActionContans;
import org.linlinjava.jz.dto.AddTicketActionDto;
import org.linlinjava.jz.dto.HmNoticeDto;
import org.linlinjava.jz.dto.TicketAction;
import org.linlinjava.jz.service.HmButlerTaskClockService;
import org.linlinjava.jz.service.HmButlerTaskParentService;
import org.linlinjava.jz.service.HmSmsLogService;
import org.linlinjava.jz.service.HmTaskCenterService;
import org.linlinjava.jz.service.NoticeService;
import org.linlinjava.jz.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * 管家 任务，拜访，跟进类
 * 
 * @author lu
 */
@Api(value = "AdminCustomerTaskController", description = "管家 任务，拜访，跟进类操作")
@RestController
@RequestMapping("/admin/customerTask")
@Validated
public class AdminCustomerTaskController {
	private final Log logger = LogFactory.getLog(AdminCustomerTaskController.class);

	@Autowired
	private HmButlerTaskParentService paskParentService;

	@Autowired
	HmButlerTaskChildService hmButlerTaskChildService;

	@Autowired
	HmButlerTaskClockService hmButlerTaskClockService;

	@Autowired
	HmButlerTaskTeachService hmButlerTaskTeachService;

	@Autowired
	HmSmsLogService hmSmsLogService;

	@Autowired
	AdminCustomerOrderService adminCustomerOrderService;

	@Autowired
	HmTaskCenterService hmTaskCenterService;

	@Autowired
	HmNoticeService hmNoticeService;

	@Autowired
	NoticeService noticeService;

	@Autowired
	private TicketService ticketService;

	@Autowired
	private JzSkillGroupService skillGroupService;

	@Autowired
	private JzDmTicketResultService jzDmTicketResultService;
	
	@ApiOperation(value = "首页保姆任务", notes = "首页保姆任务")
	@GetMapping(value = "servantTaskCount")
	public Object servantTaskCount(@NotNull @RequestParam Integer userId) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("taskTimeout", paskParentService.getTaskTimeout(userId)); //所有已超时任务
		data.put("unfinished", paskParentService.getTaskUnfinished(userId)); //所有未完成任务
		data.put("twentyFourBefore", paskParentService.getTaskTwentyFourBefore(userId));//距离24小时内的任务 
		return ResponseUtil.ok(data);
	}

	@RequiresPermissions("admin:customerTask:visitList")
	@RequiresPermissionsDesc(menu = { "订单中心", "管家拜访任务" }, button = "查询")
	@ApiOperation("订单中心-管家拜访任务")
	@GetMapping("/visitList")
	public Object visitList(@NotNull @RequestParam Long orderId,Long parentTaskId) {
		CustomerOrder customerOrder = adminCustomerOrderService.selectById(orderId);
		if (null == customerOrder) {
			return ResponseUtil.badArgumentValue();
		}
		return ResponseUtil.ok(paskParentService.getButlerTaskParentList(customerOrder.getOrderNo(),parentTaskId));
	}

//    @ApiOperation(value = "管家拜访类-任务详情", notes = "管家拜访类-任务详情parentTaskId主任务id")
//	@GetMapping(value = "info")
//	public Object statistics(Long parentTaskId) {
//		Map<String, Object> data = hmButlerTaskChildService.selectByTaskParentId(parentTaskId);
//		return ResponseUtil.ok(data);
//	}

	@ApiOperation(value = "管家拜访类-主任务完成", notes = "管家拜访类-主任务完成,taskParentId主任务id")
	@GetMapping(value = "completeParentTask")
	public Object completeParentTask(Long parentTaskId) {
		paskParentService.completeParentTask(parentTaskId);
		return ResponseUtil.ok();
	}

	@ApiOperation(value = "管家拜访类-修改拜访时间", notes = "管家拜访类-修改拜访时间taskChildId 子任务id，date年月日")
	@GetMapping(value = "updateVisitTime")
	public Object updateVisitTime(@NotNull @RequestParam Long taskChildId, @NotNull @RequestParam String date) {
		hmButlerTaskChildService.updateVisitTime(taskChildId, date);
		return ResponseUtil.ok();
	}

	@ApiOperation(value = "管家拜访类-跟教保姆记录查看", notes = "管家拜访类-跟教保姆记录查看")
	@GetMapping(value = "getServantTaskTeach")
	public Object getServantTaskTeach(Long taskChildId) {
		Map<String, Object> data = hmButlerTaskTeachService.getServantTaskTeach(taskChildId);
		return ResponseUtil.ok(data);
	}

	@ApiOperation(value = "管家拜访类-跟教保姆记录--录入", notes = "管家拜访类-跟教保姆记录--录入")
	@PostMapping(value = "addServantTaskTeach")
	public Object addServantTaskTeach(@RequestBody @Valid ButlerTaskTeachAddDto dto) {
		hmButlerTaskTeachService.addServantTaskTeach(dto);
		return ResponseUtil.ok();
	}

	@ApiOperation(value = "管家邀请主顾双方使用小程序，发送短信", notes = "管家邀请主顾双方使用小程序，发送短信")
	@GetMapping(value = "invitationUseApp")
	public Object invitationUseApp(Long taskChildId) {
		String invitationUseApp = hmSmsLogService.invitationUseApp(taskChildId);
		if (null == invitationUseApp) {
			return ResponseUtil.ok();
		}
		return ResponseUtil.fail(-1, invitationUseApp);
	}

	@ApiOperation(value = "管家邀请主顾双方使用小程序，从订单发起", notes = "管家邀请主顾双方使用小程序，从订单发起")
	@GetMapping(value = "invitationUseAppByOrder")
	public Object invitationUseAppByOrder(String orderNo) {
		String invitationUseApp = hmSmsLogService.invitationUseApps(orderNo);
		if (null == invitationUseApp) {
			return ResponseUtil.ok();
		}
		return ResponseUtil.fail(-1, invitationUseApp);
	}

	// --------------------------------跟进类------------------------------
	// --------------------------------------------------------------------
	@ApiOperation(value = "详细信息-管家工单", notes = "详细信息-管家工单")
	@GetMapping(value = "getTaskList")
	public Object getTaskList(int page, int limit, Long orderId,Long noticeId) {
		CustomerOrder customerOrder = adminCustomerOrderService.selectById(orderId);
		if (null == customerOrder) {
			return ResponseUtil.badArgumentValue();
		}
		List<HmNotice> list = hmNoticeService.getNoticeByButler(customerOrder.getOrderNo(),noticeId, page, limit);
		return ResponseUtil.okList(list);
	}

	@ApiOperation(value = "跟进类，添加跟进记录", notes = "跟进类，添加跟进记录")
	@PostMapping(value = "addTicketAction")
	public Object addTicketAction(@RequestBody @Valid AddTicketActionDto dto) {

		ticketService.addActionHm(dto);
		return ResponseUtil.ok();
	}

	@ApiOperation(value = "跟进类，创建新的任务", notes = "跟进类，创建新的任务")
	@PostMapping(value = "createNewTicket")
	public Object createNewTicket(@RequestBody @Valid HmNoticeDto dto) {

		// dto.setEmployRelationId(dto.getEmployRelationId());//三者关系id
		// dto.setCreateUserId(dto.getCreateUserId());// 登录的用户id

		// dto.setRType(HmNoticeEnum.NOTICE_NUM_10.getType());//通知枚举类型
		// dto.setRId("");//关联业务关系id
		// dto.setTaskSourceType(taskSourceType);//任务来源
		// HmNoticeEnum.getTaskSourceTypeList()
		dto.setNoticeUserType(HmNoticeEnum.getNoticeUserTypeByType(dto.getRtype()));// 获取需要通知几方
		dto.setAppUserId(hmNoticeService.getNoticeUserId(dto.getEmployRelationId(), dto.getNoticeUserType()));// 具体被通知的人

		noticeService.create(dto);
		return ResponseUtil.ok();
	}

	@ApiOperation(value = "跟进类，跟进记录，创建任务的字典数据", notes = "跟进类，跟进记录，创建任务的字典数据")
	@GetMapping(value = "getTicketTaskDict")
	public Object getTicketTaskDict() {
		Map<String, Object> data = new HashMap<String, Object>();

		// 添加任务类
		data.put("taskType", HmNoticeEnum.getTaskTypeList());// 任务类型 jz_campaign
		data.put("taskSourceType", HmNoticeEnum.getTaskSourceTypeList());// 任务来源 jz_dm_ticket_consult_type

		// 跟进记录类型
		data.put("followType", HmTicketActionContans.getFollowTypeList());

		return ResponseUtil.ok(data);
	}

	@ApiOperation(value = "工单完成", notes = "工单完成")
	@PostMapping("/ticketCompleted")
	public Object ticketCompleted(@RequestBody TicketAction action) {
		// action.setAdminId(adminId);//从登陆的用户id获取 前端传
		// action.setId(id);//工单id 前端传task的id
		// action.setMemo(remark);//完成内容 前端传
		// action.setResult(result);//ticketResult内容
		// action.setSkillGroupId(skillGroupId);//技能组 sql查询，默认取一个
		ticketService.completed(action);
		// 完成了通知盒马小程序用户
		String resultName=jzDmTicketResultService.findById(action.getResult()).getName();
		String comment="处理结果："+resultName+"；备注："+action.getMemo();
		noticeService.addNoticeUsers(action.getId(), comment,
				TicketStatusConstant.STATUS_COMPLETED.toString());
		// 通知评论
		return ResponseUtil.ok();
	}

	@ApiOperation(value = "工单完成-查询处理参数", notes = "工单完成-查询处理参数")
	@GetMapping("/ticketCompletedResult")
	public Object ticketCompleted(@NotNull @RequestParam Integer ticketId, @NotNull @RequestParam Integer userId) {

		// 工单信息
		JzTicket ticket = ticketService.getTicketById(ticketId);
		if (ticket == null) {
			return ResponseUtil.badArgument();
		}

		// 获取当前人的技能组
		Integer skillGroupId = skillGroupService.getSkillGroupIdByUserId(userId);

		// 获取工单的处理结果
		List<JzDmTicketResult> ticketResult = jzDmTicketResultService.queryByType(ticket.getTicketType().shortValue());

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("ticket", ticket);
		data.put("skillGroupId", skillGroupId);
		data.put("ticketResult", ticketResult);

		return ResponseUtil.ok(data);
	}

	@PostMapping("/ticketUpgrade")
	@ApiOperation(value = "工单流转，升级", notes = "工单流转，升级")
	public Object ticketUpgrade(@RequestBody TicketAction action) {
//		action.setAdminId(adminId);//从登陆的用户id获取 前端传
		// action.setId(id);//工单id 前端传工单的id
		// action.setMemo(remark);//完成内容 前端传
		// action.setResult(result);//ticketResult内容
		// action.setSkillGroupId(skillGroupId);//技能组 sql查询，默认取一个
		ticketService.upgrade(action);
		// 流转升级是crm内部通知，小程序用户不用知道
		return ResponseUtil.ok();
	}

	@GetMapping("/getSkillGroupUser")
	@ApiOperation(value = "获取技能组下的用户", notes = "获取技能组下的用户")
	public Object getSkillGroupUser() {
		List<org.linlinjava.jz.db.dto.SkillGroupUserVo> allUsers = skillGroupService.getSkillSysUser();
		return ResponseUtil.ok(allUsers);
	}

}
