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


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.workpayment.entity.WorkPayment;
import com.jeeplus.modules.workpayment.service.WorkPaymentService;
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-18
 */
@SuppressWarnings("all")
@RequestMapping(value = "${frontPath}/payment/Payment")
@Controller
public class PaymentMobileController extends BaseController {
    @Autowired
    private WorkPaymentService workPaymentService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private ApprovalCopyService approvalCopyService;
    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动付款申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "savePayment", method = RequestMethod.POST)
    public AjaxJson savePayment(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 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 payDateStr = URLDecoder.decode(requestMap.get("payDateStr")==null?"":requestMap.get("payDateStr"), "UTF-8");
            String payType = URLDecoder.decode(requestMap.get("payType")==null?"":requestMap.get("payType"), "UTF-8");
            String payObject = URLDecoder.decode(requestMap.get("payObject")==null?"":requestMap.get("payObject"), "UTF-8");
            String payBank = URLDecoder.decode(requestMap.get("payBank")==null?"":requestMap.get("payBank"), "UTF-8");
            String payBankAccount = URLDecoder.decode(requestMap.get("payBankAccount")==null?"":requestMap.get("payBankAccount"), "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();//

            WorkPayment workPayment = new WorkPayment();
            workPayment.setUser(user);
            workPayment.setCompany(company);
            workPayment.setOffice(office);
            workPayment.setCreateBy(user);
            workPayment.setUpdateBy(user);
            workPayment.setDelFlag("0");
            workPayment.setStatus("1");
            workPayment.setDelFlag("0");
            workPayment.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            workPayment.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            workPayment.setReason(reason);
            workPayment.setAmount(amount);
            workPayment.setCCid(CCId);
            workPayment.setRemarks(remarks);
            workPayment.setPayDate(sdf.parse(payDateStr));
            workPayment.setPayType(payType);
            workPayment.setPayObject(payObject);
            workPayment.setPayBank(payBank);
            workPayment.setPayBankAccount(payBankAccount);
            workPaymentService.save(workPayment,variables,type);

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

            String title="审批";
            String content =  UserUtils.getUser().getName()+"的付款申请需要你审批";
            String status = "待审批";
            Office office1 = workPayment.getOffice();
            String officeName = "";
            if (office1!=null){
                Office o = officeService.get(office1.getId());
                officeName = o.getName();
            }

            String remakers = "付款申请部门："+office.getName()+ "\n"
//                    +"申请人："+user.getName()+"\n"
                    +"付款事由："+workPayment.getReason()+"\n"
                    +"付款金额："+workPayment.getAmount()+"\n";
            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", workPayment.getId());
            extras.put("procDefKey", "payment");

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

            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("付款申请已经提交");
                json.put("id", workPayment.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 = "getPaymentById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getPaymentById(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = workPaymentService.getPaymentById(id,type);
        if( map==null){
            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;
    }
}
