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

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.buydetails.entity.BuyDetails;
import com.jeeplus.modules.oabuy.entity.OaBuy;
import com.jeeplus.modules.oabuy.service.OaBuyService;
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.entity.Workattachment;
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.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
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}/oabuy/oabuy")
@Controller
public class OaBController extends BaseController {
    @Autowired
    private OaBuyService oaBuyService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private WorkClientAttachmentDao workClientAttachmentService;
    @Autowired
    private WorkattachmentService workattachmentService;

    @Autowired
    private ApprovalCopyService approvalCopyService;

    @Autowired
    private PushinfoService pushinfoService;

    /**
     * 启动采购申请
     *
     * @param request
     * @param response
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveOaBuy", method = RequestMethod.POST)
    public AjaxJson oaBuy(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        AjaxJson json = new AjaxJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Map<String, Object> variables = Maps.newHashMap();
            HashMap<String, String> requestMap = findRequestMap(request);

            String applyContent = URLDecoder.decode(requestMap.get("applyContent")==null?"":requestMap.get("applyContent"), "UTF-8");
            String buySort = URLDecoder.decode(requestMap.get("buySort")==null?"":requestMap.get("buySort"), "UTF-8");
            String id = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String totalPrice = URLDecoder.decode(requestMap.get("totalPrice")==null?"":requestMap.get("totalPrice"), "UTF-8");
            String deliverDate = URLDecoder.decode(requestMap.get("deliverDate")==null?"":requestMap.get("deliverDate"), "UTF-8");
            String payStyle = URLDecoder.decode(requestMap.get("payStyle")==null?"":requestMap.get("payStyle"), "UTF-8");
            String CCId = URLDecoder.decode(requestMap.get("CCId")==null?"":requestMap.get("CCId"), "UTF-8");
            String approverId = URLDecoder.decode(requestMap.get("approverId")==null?"":requestMap.get("approverId"), "UTF-8");
            String buyDetailsList = URLDecoder.decode(requestMap.get("buyDetailsList")==null?"":requestMap.get("buyDetailsList"), "UTF-8");
            String remark = URLDecoder.decode(requestMap.get("remarks")==null?"":requestMap.get("remarks"), "UTF-8");
            String delFlag="0"; //审核流程状态标记 0 待审核 1 审核完成
            User user = new User(); //记录请假人的
            OaBuy oaBuy = new OaBuy();
            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);
            oaBuy.setUser(user);
            oaBuy.setApplyContent(applyContent);
            oaBuy.setBuySort(buySort);
            if(StringUtils.isNotBlank(deliverDate)){
                oaBuy.setDeliverDate(sdf.parse(deliverDate));
            }
            List<BuyDetails> buyDetailsList2 = new ArrayList<BuyDetails>();
            if(StringUtils.isNotBlank(buyDetailsList)){
                List<BuyDetails> detailsList = JsonUtil.json_to_list(buyDetailsList, BuyDetails.class);
                if(detailsList!=null && detailsList.size()>0){
                    for (int i = 0; i < detailsList.size(); i++) {
                        BuyDetails buyDetails = detailsList.get(i);
                        buyDetails.setId("");
                        buyDetailsList2.add(buyDetails);
                    }
                }

            }
            oaBuy.setBuyDetailsList(buyDetailsList2);
            oaBuy.setTotalPrice(totalPrice);
            oaBuy.setPayStyle(payStyle);
            oaBuy.setRemarks(remark);
            oaBuy.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
            oaBuy.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
            oaBuy.setCreateBy(user);
            oaBuy.setUpdateBy(user);
            oaBuy.setDelFlag(delFlag);
            oaBuy.setStatus("1");
            oaBuyService.save(oaBuy, variables);
            ApprovalCopy approvalCopy = new ApprovalCopy();
            approvalCopy.setCCId(CCId==null?"":CCId);
            approvalCopy.setUserId(user.getId());
            approvalCopy.setType("oaBuy");
            approvalCopy.setApprovalId(oaBuy.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;//给审批流程的第一个人发送通知
                oaBuyService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
                String content = "审批信息 申请人:" + user.getName() + ",采购申请 待审批!";
                UserUtils.pushIm(alias,content);
            }

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

            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(oaBuy.getId());
            pushinfo.setTitle(title);
            pushinfo.setContent(content);
            pushinfo.setStatus(status);
            pushinfo.setAddcontent("oaBuy");
            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", oaBuy.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");
            OaBuy oaBuy =  oaBuyService.getById(id);
            OSSClientUtil ossUtil =new OSSClientUtil();

            Iterator<String> fileNames = multiRequest.getFileNames();
            System.out.println("-----------开始------------------");
           /* 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 = ossUtil.uploadFile2OSS(file, "oaBuy");
                    WorkClientAttachment workattachment = new WorkClientAttachment();
                    workattachment.setUrl(url);
                    workattachment.setType(fileType);
                    workattachment.setAttachmentName(fileName);
                    workattachment.setAttachmentUser(UserUtils.getUser().getId());
                    workattachment.setAttachmentId(oaBuy.getId());
                    workattachment.setAttachmentFlag("69");
                    workClientAttachmentService.insert(workattachment);
                }
            }
            List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(id, "69");
            String filePath = ",";
            if(attachmentList!=null && attachmentList.size()>0){
                for (int i = 0; i < attachmentList.size(); i++) {
                    if(StringUtils.isNotBlank(attachmentList.get(i).getUrl())){
                        filePath += attachmentList.get(i).getUrl();
                    }
                }
            }
            if(filePath.length()>2){
                filePath = filePath.substring(1);
            }*/
            String thisFiles = oaBuy.getFiles();
            String filePaths= "";
            while(fileNames.hasNext()){

                //取得上传文件
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    //String filePath= ossUtil.uploadFile2OSS(file, "oaBuy");
                    OSSClientUtil ossClientUtil = new OSSClientUtil();
                    String filePath= oaBuyService.uploadFile(ossClientUtil,file,oaBuy,"69");
                    filePaths = filePath;
                }
            }
            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 = "getOaBuyById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getOaBuyById(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        Map map = oaBuyService.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;
    }
}