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

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.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 com.jeeplus.modules.workovertimeform.entity.WorkOvertimeForm;
import com.jeeplus.modules.workovertimeform.service.WorkOvertimeFormService;
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}/overtime/overtime")
@Controller
public class OverTimeMobileController extends BaseController {
    @Autowired
    private WorkOvertimeFormService workOvertimeFormService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动加班申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveOverTime", method = RequestMethod.POST)
    public AjaxJson overTime(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        AjaxJson json = new AjaxJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        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("longTime").equals("")
                    || requestMap.get("isHolidays").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 id = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String longTime = URLDecoder.decode(requestMap.get("longTime")==null?"":requestMap.get("longTime"), "UTF-8");
            String isHolidays = URLDecoder.decode(requestMap.get("isHolidays")==null?"":requestMap.get("isHolidays"), "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(); //记录请假人的
            WorkOvertimeForm workOvertimeForm = new WorkOvertimeForm();
            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(ErrorCode.code_1010);
                    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(id);
            workOvertimeForm.setUser(user);
            workOvertimeForm.setStartTime(startTime);
            workOvertimeForm.setEndTime(endTime);
            workOvertimeForm.setLongTime(longTime);
            workOvertimeForm.setIsHolidays(isHolidays);
            workOvertimeForm.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            workOvertimeForm.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            workOvertimeForm.setOffice(UserUtils.getSelectOffice());
            workOvertimeForm.setCreateBy(user);
            workOvertimeForm.setUpdateBy(user);
            workOvertimeForm.setDelFlag(delFlag);
            workOvertimeForm.setStatus("1");
            workOvertimeForm.setReason(reason);
            workOvertimeFormService.present(workOvertimeForm, variables,type);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(id);
            approvalCopy.setRemarks(reason);
            approvalCopy.setType("overtime");
            approvalCopy.setApproverId(approverId);
            approvalCopy.setApprovalId(workOvertimeForm.getId());
            approvalCopy.setReadFlag("0");
            approvalCopyService.save(approvalCopy);

            //给抄送人、审批人发送通知
            if(approvalCopy!=null && org.apache.commons.lang3.StringUtils.isNotBlank(approvalCopy.getId())){
                String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
                String shenpiIds = alias;//给审批流程的第一个人发送通知
                workOvertimeFormService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",加班申请: 待审批!";
                UserUtils.pushIm(alias,content);
            }

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的加班申请需要你审批";
            String status = "待审批";
            String remarks = "开始时间："+workOvertimeForm.getStartTime()+ "\n"
                    +"结束时间："+workOvertimeForm.getEndTime()+ "\n"
                    +"加班时长（小时）："+workOvertimeForm.getLongTime();
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", workOvertimeForm.getId());
            extras.put("procDefKey", "overtime");

            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(workOvertimeForm.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setStatus(status);
            pushinfo.setAddcontent("overtime");
            pushinfo.setMobile("ios,android");
            pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            pushinfo.setPushUserId(alias);
            pushinfo.setParentType("singleApproval");
            pushinfoService.save(pushinfo);
            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("加班申请已经提交");
                json.put("id", workOvertimeForm.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");
            WorkOvertimeForm workOvertimeForm =  workOvertimeFormService.getById(id);
            OSSClientUtil ossUtil =new OSSClientUtil();

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

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