package com.cftech.workshop.demand.web;

import com.alibaba.fastjson.JSONArray;
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.DateUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.sys.model.User;
import com.cftech.sys.service.UserService;
import com.cftech.workshop.demand.service.DemandService;
import com.cftech.workshop.detail_log.model.Detail_log;
import com.cftech.workshop.detail_log.service.Detail_logService;
import com.cftech.workshop.details.model.Details;
import com.cftech.workshop.details.service.DetailsService;
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 lombok.Data;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Ago on 2018/7/18.
 */
@RestController
@RequestMapping(value = "/mobile/auth/demand")
public class MobileDemandController {

    @Autowired
    private DemandService demandService;

    @Autowired
    private DetailsService detailsService;

    @Autowired
    private MeetingService meetingService;

    @Autowired
    private WorkshopService workshopService;

    @Autowired
    private Detail_logService detail_logService;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private  UserService userService;

    /**
     * 我的行程
     * @param meetingId 研讨会ID
     * @param member_uid 会员名称
     * @return
     */
    @RequestMapping(value = "/getdemand", method = {RequestMethod.GET,RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getdemand(Long meetingId , String member_uid){
        JSONObject jsonObject = new JSONObject();
      try {
          if(StringUtils.isNoneBlank(String.valueOf(meetingId))&&StringUtils.isNoneBlank(member_uid)){
              jsonObject.put("errorNo",0);
            Conds conds = new Conds();
              conds.equal("meeting_id",meetingId);
              conds.equal("memberUid",member_uid);
              conds.equal("del_flag",0);
              Sort sort = new Sort("create_time", OrderType.DESC);
              List<Details> list = detailsService.fetchSearchByPage(conds,sort,0,0);
              if(list.size()>0){
                  for(Details details : list){
                      jsonObject.put("detailsinfo", HtmlUtils.htmlUnescape(details.getDetailsinfo())); //会员自己填的行程信息
                  }
              }
              Meeting meeting = meetingService.fetchById(meetingId);
              if(meeting!=null){
                  jsonObject.put("service",HtmlUtils.htmlUnescape(meeting.getService())); //后台配置的需求服务
                  SimpleDateFormat sj = new SimpleDateFormat("yyyy-MM-dd");
                  Calendar calendar = Calendar.getInstance();
                  calendar.setTime(meeting.getEndTime());
                  calendar.add(Calendar.DATE, 1);
                  //System.out.println("明天：" +      sj.format(calendar.getTime()));
                  Calendar calendar1 = Calendar.getInstance();
                  calendar1.setTime(meeting.getStartTime());
                  calendar1.add(Calendar.DATE, -1);
                  jsonObject.put("startTime",sj.format(calendar1.getTime()));
                  jsonObject.put("endTime",sj.format(calendar.getTime()));
              }
              Conds conds1 = new Conds();
              conds1.equal("m.member_uid",member_uid);
              conds1.equal("w.wsid",meetingId);
              conds1.equal("w.del_flag",0);
              Sort sort1 = new Sort("create_time",OrderType.DESC);
              List<WorkshopDto> list1 = workshopService.searchmembershop(conds1,sort1,0,0);
              JSONArray jsonArray = new JSONArray();
              JSONObject jsonObject1 = new JSONObject();
              if(list1!=null&&list1.size()>0){
                WorkshopDto workshopDto = list1.get(0);
                      jsonObject1.put("surname",workshopDto.getMsurname());
                      jsonObject1.put("first_name",workshopDto.getMname());
                      jsonObject1.put("conpany",workshopDto.getMorganization());
                      jsonArray.add(jsonObject1);

                  jsonObject.put("data",jsonArray);
              }

          }else{
              jsonObject.put("errorNo",2);  //参数错误
          }
      }catch (Exception e){
          e.printStackTrace();
          jsonObject.put("errorNo",1);
      }
        return jsonObject;
    }

    /**
     * 是否可以更改行程
     * @param meetingId 研讨会ID
     * @return
     */
    @RequestMapping(value = "/getmeetingclosetime", method = {RequestMethod.GET,RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getmeetingclosetime(Long meetingId){
        JSONObject jsonObject = new JSONObject();
        try {
            if(StringUtils.isNoneBlank(String.valueOf(meetingId))){
                Meeting meeting = meetingService.fetchById(meetingId);
                if(meeting!=null){
                    Date closetime = meeting.getClosing_date();
                    Date date = new Date();
                    if(closetime.getTime()-date.getTime()>0){
                        jsonObject.put("errorNo",0); //修改成功
                    }else{
                        jsonObject.put("errorNo",2); //需叫前台手动修改
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("errorNo",1);
        }
        return jsonObject;
    }

    /**
     * 更改我的行程
     * @param meetingId
     * @param detailsinfo
     * @return
     */
    @RequestMapping(value = "/updatedetailsinfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject updatedetailsinfo(Long meetingId,String detailsinfo,String member_uid,Long accountsId){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("errorNo",0);
            if(StringUtils.isNoneBlank(String.valueOf(meetingId))&&StringUtils.isNoneBlank(detailsinfo)&&StringUtils.isNoneBlank(member_uid)){
                Conds conds = new Conds();
                conds.equal("meeting_id",meetingId);
                conds.equal("memberUid",member_uid);
                conds.equal("del_flag",0);
                Details details = detailsService.fetchSearchByConds(conds);
                if(details!=null){
                        details.setDetailsinfo(detailsinfo);
                        detailsService.update(details);
                        Detail_log detail_log = new Detail_log();
                    detail_log.setMeetingId(details.getMeeting_id());
                    detail_log.setDetaillog(details.getDetailsinfo());
                    detail_log.setTime(details.getUpdateTime());
                    detail_log.setIsadmin(String.valueOf(0));
                    detail_log.setMemberUid(details.getMemberUid());
                    detail_logService.save(detail_log);
                    //模板推送
                    String openid = null;
                    Meeting meeting = meetingService.fetchById(meetingId);
                    if(meeting!=null){
                        User user = userService.fetchById(meeting.getCreateBy());
                        if(user!=null){
                            openid = user.getEmpid();
                        }
                    }
                    if(openid!=null){  //如果管理员绑定了粉丝
                        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 workshop = workshopService.fetchSearchByConds(conds1);
                        if(workshop!=null){
                            first = "尊敬的管理员，序号"+workshop.getSort()+"的客户更新了行程信息。";
                        }
                        Conds conds2 = new Conds();
                        conds2.equal("m.member_uid",member_uid);
                        conds2.equal("w.del_flag",0);
                        conds2.equal("w.wsid",meetingId);
                        Sort sort = new Sort("w.create_time",OrderType.ASC);
                        List<WorkshopDto> list = workshopService.searchmembershop(conds2,sort,0,0);
                        if(list!=null&&list.size()>0){
                            for(WorkshopDto workshopDto : list){
                                name = workshopDto.getMsurname()+workshopDto.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);
                    }


                }else{
                    details  = new Details();
                    details.setAccountsId(accountsId);
                    details.setDelFlag(false);
                    details.setDetailsinfo(detailsinfo);
                    details.setMeeting_id(meetingId);
                    details.setMemberUid(member_uid);
                    detailsService.save(details);
                    Detail_log detail_log = new Detail_log();
                    detail_log.setMeetingId(details.getMeeting_id());
                    detail_log.setDetaillog(details.getDetailsinfo());
                    detail_log.setTime(details.getUpdateTime());
                    detail_log.setIsadmin(String.valueOf(0));
                    detail_log.setMemberUid(details.getMemberUid());
                    detail_logService.save(detail_log);
                }
            }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);
    }
}
