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

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.modules.act.service.ActTaskService;
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 com.jeeplus.modules.workgoout.entity.GoOut;
import com.jeeplus.modules.workgoout.service.GoOutService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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}/goout/goout")
@Controller
public class gooutMobileController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    protected GoOutService gooutService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动外出流程
     * @param
     */
    @Transactional
    @RequestMapping(value = "saveGoOut", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveGoOut(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);
            Map<String, Object> variables = Maps.newHashMap();
            GoOut goOut=new GoOut();
           /* Date startTime = sdf.parse(start);//格式化时间2017-07-22 13:15:16
            Date endTime = sdf.parse(end);//格式化时间*/
            //String remarks = requestMap.get("remarks"); // 新加字段 请假天数
            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");
            String userId = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String gooutDay = URLDecoder.decode(requestMap.get("gooutDay")==null?"":requestMap.get("gooutDay"), "UTF-8");
            String gooutTime = URLDecoder.decode(requestMap.get("gooutTime")==null?"":requestMap.get("gooutTime"), "UTF-8");
            String gooutReason = URLDecoder.decode(requestMap.get("gooutReason")==null?"":requestMap.get("gooutReason"), "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_1010);
                    ajaxJson.setSuccess(false);
                    return ajaxJson;
                }
                String[] approverIds = approverId.split(",");
                for (int i =0 ;i<approverIds.length;i++){
                    assigneeList.add(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);
            goOut.setGooutDay(gooutDay);
            goOut.setGooutTime(gooutTime);
            goOut.setGooutReason(gooutReason);
            //goOut.setRemarks(remarks);
            goOut.setUser(user);
            goOut.setStartTime(start);
            goOut.setEndTime(end);
            goOut.setCreateBy(user);
            goOut.setUpdateBy(user);
            goOut.setStatus("1");
            goOut.setDelFlag(delFlag);
            goOut.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            goOut.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            gooutService.save(goOut, variables,type);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(userId);
            approvalCopy.setType("goout");
            approvalCopy.setApprovalId(goOut.getId());
            approvalCopy.setRemarks(gooutReason);
            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;//给审批流程的第一个人发送通知
                gooutService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",外出申请: 待审批!";
                UserUtils.pushIm(alias,content);
            }

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的外出申请需要你审批";
            String status = "待审批";
            String remarks =  "开始时间："+start+ "\n"
                    +"结束时间："+end+ "\n"
                    +"外出天数："+gooutDay;
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", goOut.getId());
            extras.put("procDefKey", "goout");

            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(goOut.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setStatus(status);
            pushinfo.setPushUserId(alias);
            pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            pushinfo.setAddcontent("goout");
            pushinfo.setMobile("ios,android");
            pushinfo.setParentType("singleApproval");
            pushinfoService.save(pushinfo);
            if (b){
                ajaxJson.setSuccess(true);
                ajaxJson.setErrorCode(ErrorCode.code_1004);
                ajaxJson.setMsg("外出申请已经提交");
                ajaxJson.put("id", goOut.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("-1");
     map.put("body",list);
     json.setBody(map);
     } catch (Exception e) {
     logger.error("查看待审批列表失败：", e);
     json.setSuccess(false);
     json.setErrorCode("-1");
     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 {
            System.out.println("-----------开始------------------");
            String id = multiRequest.getParameter("id");
            GoOut goOut =  gooutService.getById(id);
            OSSClientUtil ossUtil =new OSSClientUtil();

            Iterator<String> fileNames = multiRequest.getFileNames();
            String thisFiles = goOut.getFiles();
            String filePaths= "";

            while(fileNames.hasNext()){

                //取得上传文件
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    //String filePath= ossUtil.uploadFile2OSS(file, "goout");
                    OSSClientUtil ossClientUtil = new OSSClientUtil();
                    String filePath= gooutService.uploadFile(ossClientUtil,file,goOut,"75");
                    filePaths = filePath;
                }
            }
           /* if(thisFiles==null || thisFiles.equals("")){
                if(filePaths.contains(",")){
                    goOut.setFiles(filePaths.substring(1, filePaths.length() - 1));
                }else {
                    goOut.setFiles(filePaths);
                }
            }else{
                filePaths = thisFiles+","+filePaths;
                goOut.setFiles(filePaths);
            }
            gooutService.saveFile(goOut);*/
            System.out.println("-----------结束------------------");
            j.put("filePath",filePaths);
            j.setSuccess(true);
            j.setErrorCode(ErrorCode.code_1004);
            j.setMsg("上传成功！");
        }catch (Exception e){
            j.put("filePath","");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
            j.setMsg("上传失败！");
        }finally {
            return j;
        }
    }

    /**
     * 获取详情
     * @param
     * @return
     */
    @RequestMapping(value = "getGoOutById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getGoOutById(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = gooutService.getGoOutById(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;
    }

}
