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


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.utils.JsonUtil;
import com.jeeplus.common.utils.StringUtils;
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.entity.Workattachment;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
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.workreimbur.dao.WorkReimburDao;
import com.jeeplus.modules.workreimbur.entity.WorkReimbur;
import com.jeeplus.modules.workreimbur.entity.WorkReimburDetails;
import com.jeeplus.modules.workreimbur.service.WorkReimburService;
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 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;

/**
 * oa报销申请Controller
 *
 * @author fgy
 * @version 2018-01-20
 */
@SuppressWarnings("all")
@RequestMapping(value = "${frontPath}/workreimbur/WorkReimbur")
@Controller
public class WorkReimburMobileController extends BaseController {
    @Autowired
    private WorkReimburService workReimburService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private ApprovalCopyService approvalCopyService;
    @Autowired
    private PushinfoService pushinfoService;
    @Autowired
    private WorkReimburDao workReimburDao;
    @Autowired
    private WorkattachmentService workattachmentService;

    /**
     * 启动报销申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveReimbur", 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 approverId = URLDecoder.decode(requestMap.get("approverId")==null?"":requestMap.get("approverId"), "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 detailsListJson = URLDecoder.decode(requestMap.get("detailsListJson")==null?"":requestMap.get("detailsListJson"), "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();//

            WorkReimbur workReimbur = new WorkReimbur();
            workReimbur.setCompany(company);
            workReimbur.setOffice(office);
            workReimbur.setCreateBy(user);
            workReimbur.setUpdateBy(user);
            workReimbur.setDelFlag("0");
            workReimbur.setStatus("1");
            workReimbur.setDelFlag("0");
            workReimbur.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            workReimbur.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            workReimbur.setCCid(CCId);
            workReimbur.setRemarks(remarks);
            workReimburService.save(workReimbur,variables,type);

            List<WorkReimburDetails> detailsList = JsonUtil.json_to_list(detailsListJson, WorkReimburDetails.class);
            if(detailsList!=null && detailsList.size()>0){
                for (int i = 0; i < detailsList.size(); i++) {
                    WorkReimburDetails reimburDetails = detailsList.get(i);
                    String UUid = UUID.randomUUID().toString().replaceAll("-","");
                    reimburDetails.setId(UUid);
                    reimburDetails.setWorkReimburId(workReimbur.getId());
                    workReimburDao.insertReimburDetail(reimburDetails);
                }
            }

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

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

            Map extras = new HashMap();
            extras.put("type", "4001");
            extras.put("id", workReimbur.getId());
            extras.put("procDefKey", "reimbur");

            boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
            Pushinfo pushinfo = new Pushinfo();
            pushinfo.setCurrentUser(UserUtils.getUser());
            pushinfo.setRemarks("oa报销申请");
            pushinfo.setUserId(UserUtils.getUser().getId());
            pushinfo.setType("4001");
            pushinfo.setPushId(workReimbur.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("reimbur");
            pushinfo.setMobile("ios,android");
            pushinfoService.save(pushinfo);

            if (b){
                json.setSuccess(true);
                json.setErrorCode(ErrorCode.code_1004);
                json.setMsg("报销申请已经提交");
                json.put("id", workReimbur.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 = "getReimburById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getReimburById(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = workReimburService.getReimburById(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;
    }
//    /**
//     * 保存报销明细 (该接口暂时不用)
//     * @param
//     * @return
//     */
//    @Transactional
//    @RequestMapping(value = "saveWorkReimburDetails", method=RequestMethod.POST)
//    @ResponseBody
//    public AjaxJson saveWorkReimburDetails(HttpServletRequest request) {
//        AjaxJson ajaxJson = new AjaxJson();
//        try {
//            HashMap<String, String> requestMap = findRequestMap(request);
//            Map<String, Object> variables = Maps.newHashMap();
//            String reimburAmount = URLDecoder.decode(requestMap.get("reimburAmount")==null?"":requestMap.get("reimburAmount"), "UTF-8");
//            String reimburCategory = URLDecoder.decode(requestMap.get("reimburCategory")==null?"":requestMap.get("reimburCategory"), "UTF-8");
//            String reimburDetail = URLDecoder.decode(requestMap.get("reimburDetail")==null?"":requestMap.get("reimburDetail"), "UTF-8");
//            String workReimburId = URLDecoder.decode(requestMap.get("workReimburId")==null?"":requestMap.get("workReimburId"), "UTF-8");
//
//            WorkReimburDetails reimburDetails = new WorkReimburDetails();
//            String UUid = UUID.randomUUID().toString().replaceAll("-","");
//            reimburDetails.setId(UUid);
//            reimburDetails.setReimburAmount(reimburAmount);
//            reimburDetails.setReimburCategory(reimburCategory);
//            reimburDetails.setReimburDetail(reimburDetail);
//            reimburDetails.setWorkReimburId(workReimburId);
//            workReimburDao.insertReimburDetail(reimburDetails);
//
//            ajaxJson.put("reimburDetails",reimburDetails);
//            ajaxJson.setSuccess(true);
//            ajaxJson.setErrorCode(ErrorCode.code_1004);
//            ajaxJson.setMsg("报销明细保存成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
//        return ajaxJson;
//    }
    /**
     * 保存图片
     * @param
     * @return
     */
    @Transactional
    @RequestMapping(value = "saveFile", method=RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveFile(MultipartHttpServletRequest multiRequest) {
        AjaxJson j=new AjaxJson();
        try {
            String id = multiRequest.getParameter("id");
            WorkReimbur workReimbur =  workReimburDao.get(id);
            OSSClientUtil ossClientUtil =new OSSClientUtil();
            Iterator<String> fileNames = multiRequest.getFileNames();
            while(fileNames.hasNext()){
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if(file != null && !file.isEmpty() &&file.getSize()>0){
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    String url = ossClientUtil.uploadFile2OSS(file,"workReimbur");
                    Workattachment workattachment = new Workattachment();
                    workattachment.setUrl(url);
                    workattachment.setType(fileType);
                    workattachment.setAttachmentName(fileName);
                    workattachment.setAttachmentUser(UserUtils.getUser().getId());
                    workattachment.setAttachmentId(workReimbur.getId());
                    workattachment.setCompanyId(UserUtils.getSelectCompany().getId());
                    workattachment.setAttachmentFlag("70");
                    workattachmentService.save(workattachment);
                }
            }
            List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(id, "70");
            String files = "";
            if(attachmentList!=null && attachmentList.size()>0){
                for (int i = 0; i < attachmentList.size(); i++) {
                    if(StringUtils.isNotBlank(attachmentList.get(i).getUrl())){
                        files += "," + attachmentList.get(i).getUrl();
                    }
                }
            }
            if(files.startsWith(",")&&files.length()>2){
                files = files.substring(1);
            }
            //j.put("attachmentList",attachmentList);
            j.put("files",files);
            j.setSuccess(true);
            j.setErrorCode(ErrorCode.code_1004);
            j.setMsg("上传成功！");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("上传失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }finally {
            return j;
        }
    }

}
