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

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.oaperformance.entity.OaPerformance;
import com.jeeplus.modules.oaperformance.service.OaPerformanceService;
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}/oaperformance/oaperformance")
@Controller
public class OaPController extends BaseController {
    @Autowired
    private WorkOvertimeFormService workOvertimeFormService;
    @Autowired
    private OaPerformanceService oaPerformanceService;
    @Autowired
    private UserDao userDao;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动绩效自评
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveOaPerformance", method = RequestMethod.POST)
    public AjaxJson oaPerformance(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);

            String lastWork = URLDecoder.decode(requestMap.get("lastWork")==null?"":requestMap.get("lastWork"), "UTF-8");
            String finishWork = URLDecoder.decode(requestMap.get("finishWork")==null?"":requestMap.get("finishWork"), "UTF-8");
            String finishRate = URLDecoder.decode(requestMap.get("finishRate")==null?"":requestMap.get("finishRate"), "UTF-8");
            String lastPerformance = URLDecoder.decode(requestMap.get("lastPerformance")==null?"":requestMap.get("lastPerformance"), "UTF-8");
            String nowWork = URLDecoder.decode(requestMap.get("nowWork")==null?"":requestMap.get("nowWork"), "UTF-8");
            String nowPlan = URLDecoder.decode(requestMap.get("nowPlan")==null?"":requestMap.get("nowPlan"), "UTF-8");
            String id = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "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(); //记录申请人的
            OaPerformance oaPerformance = new OaPerformance();
            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);
            oaPerformance.setLastWork(lastWork);
            oaPerformance.setFinishWork(finishWork);
            oaPerformance.setFinishRate(finishRate);
            oaPerformance.setLastPerformance(lastPerformance);
            oaPerformance.setNowWork(nowWork);
            oaPerformance.setNowPlan(nowPlan);
            oaPerformance.setUser(user);
            oaPerformance.setCreateBy(user);
            oaPerformance.setUpdateBy(user);
            oaPerformance.setStatus("1");
            oaPerformance.setDelFlag("0");
            oaPerformance.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
            oaPerformance.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            oaPerformanceService.save(oaPerformance, variables);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(user.getId());
            approvalCopy.setType("oaPerformance");
            approvalCopy.setApprovalId(oaPerformance.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;//给审批流程的第一个人发送通知
                oaPerformanceService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",绩效自评申请: 待审批!";
                UserUtils.pushIm(alias,content);
            }

            //推送
            String title = "审批";
            String content = UserUtils.getUser().getName() + "的绩效自评申请需要你审批";
            String status = "待审批";
            String remarks = "绩效自评申请内容类型：" + oaPerformance.getLastPerformance();
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", oaPerformance.getId());
            extras.put("procDefKey", "oaPerformance");

            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(oaPerformance.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setStatus(status);
            pushinfo.setAddcontent("oaPerformance");
            pushinfo.setPushUserId(alias);
            pushinfo.setParentType("singleApproval");
            pushinfo.setMobile("ios,android");
            pushinfo.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
            pushinfoService.save(pushinfo);
            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("绩效自评申请已经提交");
                json.put("id", oaPerformance.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;
    }

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