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


import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
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.workpettycash.entity.WorkPettyCash;
import com.jeeplus.modules.workpettycash.service.WorkPettyCashService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 备用金申请Controller
 *
 * @author fgy
 * @version 2018-01-17
 */
@SuppressWarnings("all")
@RequestMapping(value = "${frontPath}/pettycash/pettyCash")
@Controller
public class PettyCashMobileController extends BaseController {

    @Autowired
    private WorkPettyCashService workPettyCashService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private PushinfoService pushinfoService;


    /**
     * 启动备用金申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "savePettyCash", method = RequestMethod.POST)
    public AjaxJson savePettyCash(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        AjaxJson json = new AjaxJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            HashMap<String, String> requestMap = findRequestMap(request);
            Map<String, Object> variables = Maps.newHashMap();
            String casherName = URLDecoder.decode(requestMap.get("casherName")==null?"":requestMap.get("casherName"), "UTF-8");
            String applicantName = URLDecoder.decode(requestMap.get("applicantName")==null?"":requestMap.get("applicantName"), "UTF-8");
            String applicantOfficeId = URLDecoder.decode(requestMap.get("applicantOfficeId")==null?"":requestMap.get("applicantOfficeId"), "UTF-8");
            String reason = URLDecoder.decode(requestMap.get("reason")==null?"":requestMap.get("reason"), "UTF-8");
            String amount = URLDecoder.decode(requestMap.get("amount")==null?"":requestMap.get("amount"), "UTF-8");
            String approverId = URLDecoder.decode(requestMap.get("approverId")==null?"":requestMap.get("approverId"), "UTF-8");
            String useDateStr = URLDecoder.decode(requestMap.get("useDateStr")==null?"":requestMap.get("useDateStr"), "UTF-8");
            String returnDateStr = URLDecoder.decode(requestMap.get("returnDateStr")==null?"":requestMap.get("returnDateStr"), "UTF-8");
            String remarks = URLDecoder.decode(requestMap.get("remarks")==null?"":requestMap.get("remarks"), "UTF-8");
            String CCId = URLDecoder.decode(requestMap.get("CCId")==null?"":requestMap.get("CCId"), "UTF-8");
            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());

            Office company = UserUtils.getSelectCompany();
            Office office = UserUtils.getSelectOffice();
            User user = UserUtils.getUser();

            Office applicantOffice = officeService.get(applicantOfficeId);

            WorkPettyCash workPettyCash = new WorkPettyCash();
            workPettyCash.setCompany(company);
            workPettyCash.setOffice(office);
            workPettyCash.setCreateBy(user);
            workPettyCash.setUpdateBy(user);
            workPettyCash.setDelFlag("0");
            workPettyCash.setStatus("1");
            workPettyCash.setDelFlag("0");
            workPettyCash.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            workPettyCash.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            workPettyCash.setReason(reason);
            workPettyCash.setAmount(amount);
            workPettyCash.setApplicantName(applicantName);
            workPettyCash.setApplicantOffice(applicantOffice);
            workPettyCash.setCasherName(casherName);
            workPettyCash.setCCid(CCId);
            workPettyCash.setRemarks(remarks);
            workPettyCash.setUseDateStr(useDateStr);
            workPettyCash.setUseDate(sdf.parse(useDateStr));
            workPettyCash.setReturnDateStr(returnDateStr);
            workPettyCash.setReturnDate(sdf.parse(returnDateStr));
            workPettyCashService.save(workPettyCash,variables,type);

            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(workPettyCash.getCCid());
            approvalCopy.setUserId(user.getId());
            approvalCopy.setType("pettyCash");
            approvalCopy.setRemarks(workPettyCash.getReason());
            approvalCopy.setApprovalId(workPettyCash.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;//给审批流程的第一个人发送通知
                workPettyCashService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",备用金申请: 待审批!";
                UserUtils.pushIm(alias,content);
            }

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的备用金申请需要你审批";
            String status = "待审批";
            String applicantOfficeName = applicantOffice.getName();

            String remakers = "备用金申请部门："+applicantOfficeName+ "\n"
                    +"申请人"+applicantName+"\n"
                    +"使用日期："+ useDateStr
                    +"归还日期："+ returnDateStr;
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", workPettyCash.getId());
            extras.put("procDefKey", "pettyCash");

            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(workPettyCash.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("pettyCash");
            pushinfo.setMobile("ios,android");
            pushinfoService.save(pushinfo);

            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("备用金申请已经提交");
                json.put("id", workPettyCash.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 = "getPettyCashById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getPettyCashById(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = workPettyCashService.getPettyCashById(id,type);
        if( map==null || map.size()==0){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("获取备用金申请详情失败");
            ajaxJson.setErrorCode(ErrorCode.code_2005);
            ajaxJson.put("data",map);
        }
        else{
            ajaxJson.put("data", map);
            ajaxJson.setMsg("获取备用申请金详情成功");
            ajaxJson.setErrorCode(ErrorCode.code_1004);
        }

        return ajaxJson;
    }
}
