package com.jeeplus.modules.API.works.leavemobliecontroller;

import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.oa.entity.Leave;
import com.jeeplus.modules.oa.service.LeaveService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workapprovalcopy.entity.ApprovalCopy;
import com.jeeplus.modules.workapprovalcopy.service.ApprovalCopyService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 请假流程
 */
@RequestMapping(value = "${frontPath}/leave/leave")
@Controller
public class LeaveMobileController  extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    protected LeaveService leaveService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private PushinfoService pushinfoService;

    @RequestMapping(value = "cesi", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson saveLeave(String approverId,HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        User approver =UserUtils.get(approverId);
        if(approver==null || approver.getName()==null){
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2003);
            ajaxJson.setMsg("请假申请流程失败,审批人不能为空");
            return ajaxJson;
        }
        ajaxJson.setMsg("zzz");
        return ajaxJson;
    }
    /**
     * 启动请假流程
     * @param
     */
    @Transactional
    @RequestMapping(value = "saveLeave", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveLeave(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            HashMap<String, String> requestMap = findRequestMap(request);
            logger.info("requestMap="+requestMap);
            Map<String, Object> variables = Maps.newHashMap();
            Leave leave=new Leave();
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            /*Date startTime = sdf.parse(start);//格式化时间2017-07-22 13:15:16
            Date endTime = sdf.parse(end);//格式化时间*/
            String start = URLDecoder.decode(requestMap.get("startTime")==null?"":requestMap.get("startTime"), "UTF-8");
            String end = URLDecoder.decode(requestMap.get("endTime")==null?"":requestMap.get("endTime"), "UTF-8");
            logger.info("start="+start);
            logger.info("end="+end);
            String id = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String reason = URLDecoder.decode(requestMap.get("reason")==null?"":requestMap.get("reason"), "UTF-8");
            String leaveTime = URLDecoder.decode(requestMap.get("leaveTime")==null?"":requestMap.get("leaveTime"), "UTF-8");
            String leaveType = URLDecoder.decode(requestMap.get("leaveType")==null?"":requestMap.get("leaveType"), "UTF-8");
            String leaveDays = URLDecoder.decode(requestMap.get("leaveDays")==null?"":requestMap.get("leaveDays"), "UTF-8");
            String approverId = URLDecoder.decode(requestMap.get("approverId")==null?"":requestMap.get("approverId"), "UTF-8");
            String CCId = URLDecoder.decode(requestMap.get("CCId")==null?"":requestMap.get("CCId"), "UTF-8");

            String delFlag="0"; //审核流程状态标记 0 待审核 1 审核完成
            User user = new User();
            String type = "1";
            String alias = "1";
            List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
            if(approverId!=null && !approverId.equals("")) {
                if (approverId.contains(UserUtils.getUser().getId())){
                    ajaxJson.setMsg("请假申请失败,审批人不能为本人");
                    ajaxJson.setErrorCode(ErrorCode.code_2003);
                    ajaxJson.setSuccess(false);
                    return ajaxJson;
                }
                String[] approverIds = approverId.split(",");
                for (int i =0 ;i<approverIds.length;i++){
                    assigneeList.add(approverIds[i]);
                    /*String key = "auditUserId"+ (i+1);
                    variables.put(key, approverIds[i]);*/
                }
                type = approverIds.length+"";
                alias = approverIds[0];
            }
            variables.put("assigneeList", assigneeList);
            variables.put("count",assigneeList.size());
            User CC = new User();
            CC.setId(CCId);
            user.setId(id);
            leave.setUser(user);
            leave.setReason(reason);
            leave.setStartTime(start);
            leave.setEndTime(end);
            leave.setLeaveTime(leaveTime);
            leave.setLeaveDays(leaveDays);
            leave.setLeaveType(leaveType);
            leave.setCreateBy(user);
            leave.setUpdateBy(user);
            leave.setStatus("1");
            leave.setDelFlag(delFlag);
            leave.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            leave.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            leaveService.save(leave, variables,type);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(id);
            approvalCopy.setType("leave");
            approvalCopy.setApprovalId(leave.getId());
            approvalCopy.setRemarks(reason);
            approvalCopy.setApproverId(approverId);
            approvalCopy.setReadFlag("0");
            approvalCopyService.save(approvalCopy);

            //给抄送人、审批人发送通知
            if(approvalCopy!=null && StringUtils.isNotBlank(approvalCopy.getId())){
                String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
                String shenpiIds = alias;//给审批流程的第一个人发送通知
                leaveService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                UserUtils.pushIm(shenpiIds," 申请人:\" + user.getName() + \",请假申请 待审批!");
                /*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(shenpiIds);
                for (WebSocket toUserConn:toUserConns) {
                    String message = "{\"to\":\""+alias+"\"," +
                            "\"msg\":\"审批信息 申请人:" + user.getName() + ",请假申请 待审批!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                }*/
            }

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的请假申请需要你审批";
            String status = "待审批";
            if (leaveType.equals("1")){
                //1:事假、2:病假、3:调休、4:年假、5:婚假、6:产假、7:其他
                leaveType = "事假";
            }else if (leaveType.equals("2")){
                leaveType = "病假";
            }else if (leaveType.equals("3")){
                leaveType = "调休";
            }else if (leaveType.equals("4")){
                leaveType = "年假";
            }else if (leaveType.equals("5")){
                leaveType = "婚假";
            }else if (leaveType.equals("6")){
                leaveType = "产假";
            }else if (leaveType.equals("7")){
                leaveType = "其他";
            }
            String remarks = "请假类型："+leaveType+ "\n"
                    +"开始时间："+start+ "\n"
                    +"结束时间："+end;
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", leave.getId());
            extras.put("procDefKey", "leave");

            boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
            Pushinfo pushinfo = new Pushinfo();
            pushinfo.setCurrentUser(UserUtils.getUser());
            pushinfo.setRemarks(remarks);
            pushinfo.setUserId(UserUtils.getUser().getId());
            pushinfo.setType("4001");
            pushinfo.setPushId(leave.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setStatus(status);
            pushinfo.setAddcontent("leave");
            pushinfo.setPushUserId(alias);
            pushinfo.setParentType("singleApproval");
            pushinfo.setMobile("ios,android");
            pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            pushinfoService.save(pushinfo);
            if (b){
                ajaxJson.setSuccess(true);
                ajaxJson.setErrorCode(ErrorCode.code_1004);
                ajaxJson.setMsg("请假申请已经提交");
                ajaxJson.put("id", leave.getId());
            }else {
                ajaxJson.setMsg("请假申请推送失败");
                ajaxJson.setErrorCode(ErrorCode.code_2006);
                ajaxJson.setSuccess(false);
            }
        } catch (Exception e) {
            logger.error("启动请假流程失败：", e);
            ajaxJson.setSuccess(false);
            ajaxJson.setErrorCode(ErrorCode.code_2004);
            ajaxJson.setMsg("启动请假流程失败");
        }
        return ajaxJson;
    }


    /**
     * 查看待审批列表
     * @param
     * @return
     * */
    @RequestMapping(value = "todoList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson todoList(String userId,HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Leave> list = new ArrayList<Leave>();
        if(userId!=null){
            list = leaveService.findTodoTasks(userId);
        }else if(UserUtils.getUser()!=null){
            list = leaveService.findTodoTasks(UserUtils.getUser().getId());
        }

        AjaxJson json=new AjaxJson();
        try {
            LinkedHashMap<String, Object> map=new LinkedHashMap();
            json.setSuccess(true);
            json.setErrorCode(ErrorCode.code_1004);
            map.put("data",list);
            json.setBody(map);
        } catch (Exception e) {
            logger.error("查看待审批列表失败：", e);
            json.setSuccess(false);
            json.setErrorCode(ErrorCode.code_2004);
            json.setMsg("查看待审批列表失败");
        }
        return json;
    }

    /**
     * 保存附件
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveFile",method=RequestMethod.POST)
    public AjaxJson saveFile(MultipartHttpServletRequest multiRequest,HttpServletRequest servletRequest) throws Exception{
        AjaxJson j=new AjaxJson();
        try {
            String id = multiRequest.getParameter("id");
            Leave leave =  leaveService.getById(id);
            OSSClientUtil ossUtil =new OSSClientUtil();

            Iterator<String> fileNames = multiRequest.getFileNames();
            String thisFiles = leave.getFiles();
            String filePaths= "";
            System.out.println("-----------开始------------------");
            while(fileNames.hasNext()){

                //取得上传文件
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if(file != null){
                    OSSClientUtil ossClientUtil = new OSSClientUtil();
                    String filePath= leaveService.uploadFile(ossClientUtil,file,leave,"71");
                    //取得当前上传文件的文件名称
                    //String filePath= ossUtil.uploadFile2OSS(file, "leave");
                    filePaths = filePath;
                }
            }
            /*if(thisFiles==null || thisFiles.equals("")){
                if(filePaths.contains(",")){
                    leave.setFiles(filePaths.substring(1, filePaths.length() - 1));
                }else {
                    leave.setFiles(filePaths);
                }
            }else{
                filePaths = thisFiles+","+filePaths;
                leave.setFiles(filePaths);
            }
            leaveService.saveFile(leave);
            */
            System.out.println("-----------结束------------------");

            j.put("filePath",filePaths);
            j.setSuccess(true);
            j.setErrorCode(ErrorCode.code_1004);
            j.setMsg("上传成功！");
        }catch (Exception e){
            j.put("filePath","");
            j.setSuccess(false);
            j.setMsg("上传失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }finally {
            return j;
        }
    }

    /**
     * 获取详情
     * @param
     * @return
     */
    @RequestMapping(value = "getLeaveById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getLeaveById(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = leaveService.getLeaveById(id,type);
        if( map==null){
            j.setSuccess(false);
            j.setMsg("获取请假详情失败");
            j.setErrorCode(ErrorCode.code_2005);
            j.put("data",map);
        }
        else{
            j.put("data", map);
            j.setMsg("获取请假详情成功");
            j.setErrorCode(ErrorCode.code_1004);
        }

        return j;
    }

}
