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

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.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
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.worksealform.entity.WorkSealForm;
import com.jeeplus.modules.worksealform.service.WorkSealFormService;
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}/useseal/useseal")
@Controller
public class UseSealMobileController extends BaseController {
    @Autowired
    private WorkSealFormService workSealFormService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动用印申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveUseSeal", method = RequestMethod.POST)
    public AjaxJson useSeal(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        AjaxJson json = 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();
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String agentId = URLDecoder.decode(requestMap.get("agentId")==null?"":requestMap.get("agentId"), "UTF-8");
            String sealType = URLDecoder.decode(requestMap.get("sealType")==null?"":requestMap.get("sealType"), "UTF-8");
            String userId = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String officeId = URLDecoder.decode(requestMap.get("officeId")==null?"":requestMap.get("officeId"), "UTF-8");
            String documentCount = URLDecoder.decode(requestMap.get("documentCount")==null?"":requestMap.get("documentCount"), "UTF-8");
            String documentName = URLDecoder.decode(requestMap.get("documentName")==null?"":requestMap.get("documentName"), "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 applicationDate = URLDecoder.decode(requestMap.get("applicationDate")==null?"":requestMap.get("applicationDate"), "UTF-8");
            String CCId = URLDecoder.decode(requestMap.get("CCId")==null?"":requestMap.get("CCId"), "UTF-8");
            String delFlag = "0"; //审核流程状态标记 0 待审核 1 审核完成
            User user = new User(); //记录
            WorkSealForm workSealForm = new WorkSealForm();
            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]);
                }
                type = approverIds.length+"";
                alias = approverIds[0];
            }
            variables.put("assigneeList", assigneeList);
            variables.put("count",assigneeList.size());
            User agent = new User();//经办人
            agent.setId(agentId);
            Office office = new Office();//用印部门
            office.setId(officeId);
            //approver.setId(approverId);
            User CC = new User();
            CC.setId(CCId);
            user.setId(userId);

            workSealForm.setUser(agent);
            //workSealForm.setUser(user);
            workSealForm.setApplicationDate(applicationDate);
            workSealForm.setDocumentCount(documentCount);
            workSealForm.setDocumentName(documentName);
            workSealForm.setSealType(sealType);
            workSealForm.setOffice(office);
            workSealForm.setCreateBy(user);
            workSealForm.setUpdateBy(user);
            workSealForm.setDelFlag(delFlag);
            workSealForm.setReason(reason);
            workSealForm.setStatus("1");
            workSealForm.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            workSealForm.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            workSealFormService.save(workSealForm,variables,type);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(userId);
            approvalCopy.setType("sealform");
            approvalCopy.setRemarks(reason);
            approvalCopy.setApprovalId(workSealForm.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;//给审批流程的第一个人发送通知
                workSealFormService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",用印申请: 待审批!";
                UserUtils.pushIm(alias,content);
            }

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的用印申请需要你审批";
            String status = "待审批";
            Office office1 = workSealForm.getOffice();
            String officeName = "";
            if (office1!=null){
                Office o = officeService.get(office1.getId());
                officeName = o.getName();
            }
            User agentUser = UserUtils.get(agentId);
            String agentName = "";
            if (agentUser!=null && agentUser.getName()!=null){
                agentName =agentUser.getName();
            }
            String remakers = "用印部门："+officeName+ "\n"
                    +"经办人："+agentName+ "\n"
                    +"日期："+workSealForm.getApplicationDate();
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", workSealForm.getId());
            extras.put("procDefKey", "sealform");

            boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
            Pushinfo pushinfo = new Pushinfo();
            pushinfo.setCurrentUser(UserUtils.getUser());
            pushinfo.setRemarks(remakers);
            pushinfo.setUserId(UserUtils.getUser().getId());
            pushinfo.setType("4001");
            pushinfo.setPushId(workSealForm.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setPushUserId(alias);
            pushinfo.setParentType("singleApproval");
            pushinfo.setStatus(status);
            pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            pushinfo.setAddcontent("sealform");
            pushinfo.setMobile("ios,android");
            pushinfoService.save(pushinfo);
            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("用印申请已经提交");
                json.put("id", workSealForm.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");
            WorkSealForm workSealForm =  workSealFormService.getById(id);
            OSSClientUtil ossUtil =new OSSClientUtil();

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

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