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

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.oa_evection.entity.oa_evection.OaEvection;
import com.jeeplus.modules.oa_evection.service.oa_evection.OaEvectionService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.dao.UserDao;
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.java_websocket.WebSocket;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 出差流程
 */
@RequestMapping(value = "${frontPath}/oaevection/oaevection")
@Controller
public class OaEvectionMobileController extends BaseController {
    @Autowired
    private OaEvectionService oaEvectionService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动出差申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveOaEvection", method = RequestMethod.POST)
    public AjaxJson oaEvection(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        AjaxJson json = new AjaxJson();
        try {
            Map<String, Object> variables = Maps.newHashMap();
            HashMap<String, String> requestMap = findRequestMap(request);
           /* if(requestMap.get("startTime").equals("") || requestMap.get("endTime").equals("")
                    || requestMap.get("userId").equals("")|| requestMap.get("address").equals("")
                    || requestMap.get("dateCount").equals("")|| requestMap.get("CCId").equals("")){
                json.setErrorCode("1");
                json.setSuccess(false);
                json.setMsg("必填参数不能为空");
                return json;
            }*/
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = URLDecoder.decode(requestMap.get("startTime")==null?"":requestMap.get("startTime"), "UTF-8");
            String endTime = URLDecoder.decode(requestMap.get("endTime")==null?"":requestMap.get("endTime"), "UTF-8");
            String userId = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String address = URLDecoder.decode(requestMap.get("address")==null?"":requestMap.get("address"), "UTF-8");
            String dateCount = URLDecoder.decode(requestMap.get("dateCount")==null?"":requestMap.get("dateCount"), "UTF-8");
            String reason = URLDecoder.decode(requestMap.get("reason")==null?"":requestMap.get("reason"), "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(); //记录请假人的
            OaEvection oaEvection = new OaEvection();
            String type = "1";
            String alias = "1";
            List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
            if(approverId!=null && !approverId.equals("")) {
                if (approverId.contains(UserUtils.getUser().getId())){
                    json.setMsg("出差申请失败,审批人不能为本人");
                    json.setErrorCode("101");
                    json.setSuccess(false);
                    return json;
                }
                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(userId);

            oaEvection.setStartTime(startTime);
            oaEvection.setEndTime(endTime);
            oaEvection.setAddress(address);
            oaEvection.setDateCount(dateCount);
            oaEvection.setReason(reason);
            oaEvection.setCreateBy(user);
            oaEvection.setStatus("1");
            oaEvection.setUpdateBy(user);
            oaEvection.setDelFlag(delFlag);
            oaEvection.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            oaEvection.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            oaEvectionService.submit(oaEvection,variables,type);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(userId);
            approvalCopy.setType("evection");
            approvalCopy.setRemarks(reason);
            approvalCopy.setApprovalId(oaEvection.getId());
            approvalCopy.setApproverId(approverId);
            approvalCopy.setReadFlag("0");
            approvalCopyService.save(approvalCopy);

            //给抄送人、审批人发送通知
            if (approvalCopy != null && org.apache.commons.lang3.StringUtils.isNotBlank(approvalCopy.getId())) {
                String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
                String shenpiIds = alias;//给审批流程的第一个人发送通知
                oaEvectionService.sendNotify(chaosongIds, shenpiIds, approvalCopy.getApprovalId());
                UserUtils.pushIm(alias,"申请人:" + user.getName() + ",出差申请 待审批!");
                /*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(alias);
                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 = "待审批";
            String remarks =  "开始时间："+startTime+ "\n"
                    +"结束时间："+endTime+ "\n"
                    +"出差地点:"+address;
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", oaEvection.getId());
            extras.put("procDefKey", "evection");

            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(oaEvection.getId());
            pushinfo.setTitle(title);
            pushinfo.setStatus(status);
            pushinfo.setContent(content);
            pushinfo.setMobile("ios,android");
            pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            pushinfo.setAddcontent("evection");
            pushinfo.setPushUserId(alias);
            pushinfo.setParentType("singleApproval");
            pushinfoService.save(pushinfo);
            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("出差申请已经提交");
                json.put("id", oaEvection.getId());
            }else {
                json.setMsg("出差申请推送失败");
                json.setErrorCode(ErrorCode.code_2006);
                json.setSuccess(false);
            }
        } 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");
            OaEvection oaEvection =  oaEvectionService.getById(id);
            OSSClientUtil ossUtil =new OSSClientUtil();

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

                //取得上传文件
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    //String filePath= ossUtil.uploadFile2OSS(file, "evection");
                    OSSClientUtil ossClientUtil = new OSSClientUtil();
                    String filePath= oaEvectionService.uploadFile(ossClientUtil,file,oaEvection,"73");
                    filePaths = filePath;
                }
            }
            /*if(thisFiles==null || thisFiles.equals("")){
                if(filePaths.contains(",")){
                    oaEvection.setFiles(filePaths.substring(1, filePaths.length() - 1));
                }else {
                    oaEvection.setFiles(filePaths);
                }
            }else{
                filePaths = thisFiles+","+filePaths;
                oaEvection.setFiles(filePaths);
            }
            oaEvectionService.saveFile(oaEvection);*/
            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 = "getEvectionById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getEvectionById(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = oaEvectionService.getEvectionById(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;
    }
}