package com.cftech.workshop.workshop.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.*;
import com.cftech.mp.wechat.web.MobileImageTextController;
import com.cftech.sys.model.User;
import com.cftech.sys.service.UserService;
import com.cftech.workshop.agenda.model.Agenda;
import com.cftech.workshop.agenda.service.AgendaService;
import com.cftech.workshop.meeting.model.Meeting;
import com.cftech.workshop.meeting.service.MeetingService;
import com.cftech.workshop.workshop.model.Workshop;
import com.cftech.workshop.workshop.model.WorkshopDto;
import com.cftech.workshop.workshop.service.WorkshopService;
import com.ctc.wstx.util.DataUtil;
import com.google.gson.Gson;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.mp.api.core.req.model.message.IndustryTemplateMessageSend;
import org.mp.api.core.req.model.message.TemplateData;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by byj on 2018/7/10.
 */

@RestController
@RequestMapping("/mobile/auth/workshop")
public class MobileWorkshopController {

    private static final Logger logger = LoggerFactory.getLogger(MobileImageTextController.class);

    @Autowired
    private WorkshopService workshopService;

    @Autowired
    private MeetingService meetingService;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private UserService userService;


    /**
     *输入邀请码
     * @param invitcode 邀请码
     * @return
     */
    @RequestMapping(value = "/regis",method = {RequestMethod.GET,RequestMethod.POST},produces={"application/json;charset=UTF-8"})
    public JSONObject regis(String invitcode){
        JSONObject jsonObject = new JSONObject();
        Conds conds = new Conds();
        conds.equal("invitcode",invitcode);
        Sort sort = new Sort("create_time", OrderType.DESC);
        List<Workshop> list = workshopService.fetchSearchByPage(conds,sort,0,0);
        if(list != null){
            for(Workshop w:list){
                jsonObject.put("organization",w.getOrganization()); //预导入公司
                jsonObject.put("gender",w.getGender()); //预导入性别
            }
        }else{
            logger.info("无效邀请码");
        }
        return  jsonObject;
    }


    /**
     * 会议简介
     * @param meetingId 研讨会ID
     * @return
     */
    @RequestMapping(value = "/getworkshopdetails",method = {RequestMethod.GET,RequestMethod.POST},produces={"application/json;charset=UTF-8"})
    public JSONObject getworkshopdetails(Long meetingId){
        JSONObject jsonObject = new JSONObject();
        try {
            if(StringUtils.isNoneBlank(String.valueOf(meetingId))){
                Meeting meeting = meetingService.fetchById(meetingId);
                if(meeting!=null){
                    meeting.setContentBriefInfo(ESAPI.encoder().decodeForHTML(meeting.getContentBriefInfo()));
                    meeting.setContentBriefEnInfo(ESAPI.encoder().decodeForHTML(meeting.getContentBriefEnInfo()));
                    jsonObject.put("errorNo",0);
                    jsonObject.put("data",meeting);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("erroeNo",1);
        }
        return jsonObject;
    }

    /**
     * 参加研讨会
     * @param member_uid
     * @param ivitecode 邀请码
     * @return
     */
    @RequestMapping(value = "/isjoinmeeting",method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    public JSONObject joinmeeting(String member_uid,String ivitecode,Long accountsId,String meetingId){
        JSONObject jsonObject = new JSONObject();

        try {
            if(StringUtils.isNoneBlank(member_uid)&&StringUtils.isNoneBlank(ivitecode)&&StringUtils.isNoneBlank(meetingId)){
                Conds conds = new Conds();
                conds.equal("m.member_uid",member_uid);
                conds.equal("w.del_flag",0);
                conds.equal("w.wsid",meetingId);
                conds.equal("w.status",1);
                Sort sort = new Sort("w.create_time",OrderType.ASC);
                List<WorkshopDto> list = workshopService.searchmembershop(conds,sort,0,0);
                if(list!=null && list.size()>0){
                    jsonObject.put("errorNo",2);
                    return jsonObject;
                }
                List<WorkshopDto> lists = workshopService.joinmeeting(member_uid,ivitecode);
                //绑定粉丝发送的模板消息
                String templateId = SystemConfig.p.getProperty("JOINTEMPLATEID");
                String token = mpTokenUtil.getToken(accountsId);
                String open_id = null;
                String name = null;
                String first = null;
                String remark = "感谢您报名参加此次会议，点击详情了解更多会议信息";
                String meetingtitle = null;
                String meetingdate = null;
                String meetingaddress = null;
                Conds condsmeet = new Conds();
                condsmeet.equal("id",meetingId);
                condsmeet.equal("del_flag",0);
                Meeting meeting = meetingService.fetchSearchByConds(condsmeet);
                if(meeting!= null){
                    meetingtitle = meeting.getTitle();
                    //日期加一
                    Calendar calendar   =   new   GregorianCalendar();
                    calendar.setTime(meeting.getStartTime());
                    calendar.add(calendar.DATE,1);
                    String start = DateUtils.formatDate(calendar.getTime());
                    String end = DateUtils.formatDate(meeting.getEndTime());
                    meetingdate = start.substring(0,4)+"年"+start.substring(5,7)+"月"+start.substring(8,10)+"日"+"-"+end.substring(5,7)+"月"+end.substring(8,10)+"日";
                    //DateFormatUtils.getDateFormat(enddate);
                    meetingaddress = meeting.getAddress();
                }
                String [] keywords = {meetingtitle,String.valueOf(meetingdate),meetingaddress};
                if(lists!=null&&lists.size()>0){
                    for(WorkshopDto workshopDto : lists){
                        open_id = workshopDto.getOpen_id();
                        name = workshopDto.getMsurname()+workshopDto.getMname();
                        first = "尊敬的"+name+"，您已报名成功！";
                    }
                }
                String yuming = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
                String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");
                String url = yuming +"/static/mp/schaeffler/overview.html?appid="+appid+"&id="+meetingId;
                sendMessage(templateId,token,open_id,first,remark,keywords,url);

                //推送给管理员发送的模板消息
                String openid = null;
                Meeting meeting1 = meetingService.fetchById(meetingId);
                if(meeting1!=null){
                    Conds conds1 = new Conds();
                    conds1.equal("delflag",0);
                    conds1.equal("id",meeting1.getCreateBy());
                    User user = userService.fetchSearchByConds(conds1);
                    if(user!=null){
                        openid = user.getEmpid();
                    }
                }
                      if(StringUtils.isNoneBlank(openid)){
                          String templateId1 = SystemConfig.p.getProperty("UPDATEDETAILS");
                          String token1 = mpTokenUtil.getToken(accountsId);
                          String first1 = null;
                          String remark1 = "请及时登录后台查看。";
                          String name1 = null;
                          String title = "已报名";
                          Conds conds1 = new Conds();
                          conds1.equal("member_uid",member_uid);
                          conds1.equal("del_flag",0);
                          conds1.equal("wsid",meetingId);
                          Workshop workshop1 = workshopService.fetchSearchByConds(conds1);
                          if(workshop1!=null){
                              first1 = "尊敬的管理员，序号"+workshop1.getSort()+"的客户已报名参加。";
                          }
                          Conds conds2 = new Conds();
                          conds2.equal("m.member_uid",member_uid);
                          conds2.equal("w.del_flag",0);
                          conds2.equal("w.wsid",meetingId);
                          Sort sort1 = new Sort("w.create_time",OrderType.ASC);
                          List<WorkshopDto> list1 = workshopService.searchmembershop(conds2,sort1,0,0);
                          if(list1!=null&&list1.size()>0){
                              for(WorkshopDto workshopDto1 : list1){
                                  name1 = workshopDto1.getMsurname()+workshopDto1.getMname();
                              }
                          }
                          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                          String str = sdf.format(new Date());
                          String[] keywords1 = {name1,title,str.substring(0,4)+"年"+str.substring(5,7)+"月"+str.substring(8,10)+"日"+str.substring(11,13)+"时"+str.substring(14,16)+"分"};
                          sendMessage(templateId1,token1,openid,first1,remark1,keywords1,null);
                      }
                jsonObject.put("errorNo",0);
            }else{
                jsonObject.put("errorNo",2);
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("errorNo",1);
        }
        return jsonObject;
    }

    /**
     * 不参加研讨会
     * @param meetingId  研讨会ID
     * @param member_uid
     * @return
     */
    @RequestMapping(value = "/nojoinmeeting",method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    public JSONObject nojoinmeeting(Long meetingId,String member_uid,String invitedcode,Long accountsId){
        JSONObject jsonObject = new JSONObject();
        try {
            if(StringUtils.isNoneBlank(invitedcode)&&StringUtils.isNoneBlank(member_uid)&&StringUtils.isNoneBlank(String.valueOf(meetingId))){
                Conds conds= new Conds();
                conds.equal("w.del_flag",0);
                conds.equal("w.wsid",meetingId);
                conds.equal("w.invitcode",invitedcode);
                Sort sort = new Sort("w.create_time",OrderType.ASC);
                List<WorkshopDto> list = workshopService.searchmembershop(conds,sort,0,0);
                if(list.size()>0){
                    for (WorkshopDto workshopDto : list){
                        Workshop workshop = new Workshop();
                        workshop.setId(workshopDto.getId());
                        workshop.setMember_uid(member_uid);
                        workshop.setStatus("-1");
                        boolean flag = workshopService.update(workshop);
                        if(flag){  //拒绝成功
                            String openid = null;
                            Meeting meeting = meetingService.fetchById(meetingId);
                            if(meeting!=null){
                                User user = userService.fetchById(meeting.getCreateBy());
                                if(user!=null){
                                    openid = user.getEmpid();
                                }
                            }
                                    String templateId = SystemConfig.p.getProperty("UPDATEDETAILS");
                                    String token = mpTokenUtil.getToken(accountsId);
                                    String first = null;
                                    String remark = "请及时登录后台查看。";
                                    String name = null;
                                    String title = "已拒绝";
                                    Conds conds1 = new Conds();
                                    conds1.equal("member_uid",member_uid);
                                    conds1.equal("del_flag",0);
                                    conds1.equal("wsid",meetingId);
                                    Workshop workshop1 = workshopService.fetchSearchByConds(conds1);
                                    if(workshop1!=null){
                                        first = "尊敬的管理员，序号"+workshop1.getSort()+"的客户已拒绝参加。";
                                    }
                                    Conds conds2 = new Conds();
                                    conds2.equal("m.member_uid",member_uid);
                                    conds2.equal("w.del_flag",0);
                                    conds2.equal("w.wsid",meetingId);
                                    Sort sort1 = new Sort("w.create_time",OrderType.ASC);
                                    List<WorkshopDto> list1 = workshopService.searchmembershop(conds2,sort1,0,0);
                                    if(list1!=null&&list1.size()>0){
                                        for(WorkshopDto workshopDto1 : list1){
                                            name = workshopDto1.getMsurname()+workshopDto1.getMname();
                                        }
                                    }
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String str = sdf.format(new Date());
                                    String[] keywords = {name,title,str.substring(0,4)+"年"+str.substring(5,7)+"月"+str.substring(8,10)+"日"+str.substring(11,13)+"时"+str.substring(14,16)+"分"};
                                    sendMessage(templateId,token,openid,first,remark,keywords,null);
                                }
                            }

                            jsonObject.put("errorNo",0);


                }
            }else{
                jsonObject.put("errorNo",2);
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("errorNo",1);
        }
        return jsonObject;
    }

    private void sendMessage(String templateId,String token,String openId,String first,String remark,String []keywords,String url){
        IndustryTemplateMessageSend mc = new IndustryTemplateMessageSend();
        mc.setTemplate_id(templateId);
        mc.setTouser(openId);
        mc.setAccess_token(token);
        mc.setUrl(url);
        StringBuffer json = new StringBuffer();
        Gson gson = new Gson();
        String objJson = gson.toJson(mc);
        json.append(objJson);
        json.setLength(json.length()-1);
        json.append(",");
        json.append("\"data\":{");
        TemplateData template = new TemplateData();
        template.setValue(first);
        //template.setColor("#ffAADD");
        objJson = gson.toJson(template);
        json.append(" \"first\":");
        json.append(objJson);
        json.append(",");
        if(keywords!=null && keywords.length>0){
            for(int i=0;i<keywords.length;i++){
                template.setValue(keywords[i]);
                objJson = gson.toJson(template);
                json.append(" \"keyword"+(i+1)+"\":");
                json.append(objJson);
                json.append(",");
            }
        }
        template.setValue(remark);
        objJson = gson.toJson(template);
        json.append(" \"remark\":");
        json.append(objJson);
        json.append("}}");
        JwTemplateMessageAPI.sendTemplateMsgJson(json.toString(),token);
    }

    /**
     * 是否报名
     * @param member_uid 会员UID
     * @return
     */
    @RequestMapping(value = "/isregis",method = {RequestMethod.GET,RequestMethod.POST},produces={"application/json;charset=UTF-8"})
    public JSONObject isregis(String member_uid,String meetingId){
        JSONObject jsonObject = new JSONObject();
        try {
            if(StringUtils.isNoneBlank(member_uid)){
                Conds conds = new Conds();
                conds.equal("m.member_uid",member_uid);
                conds.equal("w.wsid",meetingId);
                conds.equal("w.del_flag",0);
                Sort sort = new Sort("w.create_time",OrderType.DESC);
                List<WorkshopDto> list = workshopService.searchmembershop(conds,sort,0,0);
                if(list!=null && list.size()>0){
                    for(WorkshopDto workshopDto : list){
                        if(workshopDto.getStatus().equals("1")|| workshopDto.getStatus().equals("2")){
                            jsonObject.put("errorNo",3); //已报名
                            return jsonObject;
                        }else{
                            jsonObject.put("errorNo",4);  //未报名
                        }
                    }
                }else{
                    jsonObject.put("errorNo",4);  //未报名
                }
            }else{
                jsonObject.put("errorNo",2);
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("errorNo",1);
        }
        return jsonObject;
    }

    /**
     * 姓名头像
     * @param member_uid
     * @return
     */
    @RequestMapping(value = "/getpeopledetails",method = {RequestMethod.GET,RequestMethod.POST},produces={"application/json;charset=UTF-8"})
    public JSONObject getpeopledetails(String member_uid,Long meetingId){
       JSONObject jsonObject = new JSONObject();
        try {
            if(StringUtils.isNoneBlank(member_uid)){
                Conds conds = new Conds();
                conds.equal("m.member_uid",member_uid);
                conds.equal("w.del_flag",0);
                conds.equal("wsid",meetingId);
                Sort sort = new Sort("w.create_time",OrderType.DESC);
                List<WorkshopDto> list = workshopService.searchmembershop(conds,sort,0,0);
                if(list != null &&list.size()>0){
                    for(WorkshopDto workshopDto : list){
                        jsonObject.put("errorNo",0);
                        jsonObject.put("suname",workshopDto.getMsurname());
                        jsonObject.put("name",workshopDto.getMname());
                        jsonObject.put("name_en",workshopDto.getName_en());
                        jsonObject.put("imgurl",workshopDto.getImageurl());
                    }
                }
            }else{
                jsonObject.put("errorNo",2);
            }
            if(meetingId!=null){
                Map<String,Object> params =new HashMap<String,Object>();
                params.put("id",meetingId);
                Map<String,Object> object = meetingService.fetchMeetingMobileMenu(params);
                jsonObject.put("menu",object);
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("errorNo",1);
        }
        return  jsonObject;
    }



}
