package com.cftech.workshop.signin.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.sys.security.UserUtils;
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.StringUtil;
import com.google.gson.Gson;
import com.qcloud.cos.transfer.TransferManager;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 java.util.Date;
import java.util.List;

/**
 * Created by lisw on 2018/7/26.
 */
@Controller
@RequestMapping(value = "/a/signin")
public class SignInController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SignInController.class);

    public static final String MEETINGSIGN_VIEW = "qy:meetingsignin:view";
    public static final String MEETINGSIGN_EDIT = "qy:meetingsignin:edit";

    private static final  String domain = SystemConfig.p.getProperty("QY_DOMAIN");

    private static final  String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");

    @Autowired
    private WorkshopService workshopService;

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private MeetingService meetingService;



    @RequiresPermissions(value = MEETINGSIGN_VIEW)
    @RequestMapping(value = "signin",method = RequestMethod.GET)
    public String form(){
        return "/signin/signinlist";
    }

    @RequestMapping(value = "signList",method = RequestMethod.GET)
    @RequiresPermissions(value = MEETINGSIGN_VIEW)
    @ResponseBody
    public JSONObject form(String code,int iDisplayStart, int iDisplayLength,String name,String surname,String sort){
        JSONObject rtnJson = new JSONObject();
        try{
            Conds conds  = new Conds();
            if(StringUtils.isNotBlank(name)){
                conds.like("s.mname",name);
            }
            if(StringUtils.isNoneBlank(surname)){
                conds.like("s.msurname",surname);
            }
            if(StringUtils.isNoneBlank(sort)){
                conds.equal("s.sort",sort);
            }
            conds.equal("s.invitcode",code);
            conds.equal("s.status","1");
            conds.equal("s.del_flag",0);
            List<WorkshopDto> workshopList =  workshopService.delworkshop(conds,null,iDisplayStart,iDisplayLength);
            if(workshopList.size()>0&&workshopList!=null){
                for(WorkshopDto workshopDto :workshopList){
                    if(workshopDto.getMsurname()==null){
                        workshopDto.setMsurname("");
                    }
                    if(workshopDto.getMname()==null){
                        workshopDto.setMname("");
                    }
                    if(workshopDto.getName_en()==null){
                        workshopDto.setName_en("");
                    }
                    if(workshopDto.getOrganization()==null){
                        workshopDto.setOrganization("");
                    }
                    if(workshopDto.getOrganization_en()==null){
                        workshopDto.setOrganization_en("");
                    }
                    if(workshopDto.getTable_number()==null){
                        workshopDto.setTable_number("");
                    }
                    if(workshopDto.getFactory_number()==null){
                        workshopDto.setFactory_number("");
                    }
                    if(workshopDto.getDrive_number()==null){
                        workshopDto.setDrive_number("");
                    }
                }
            }
            Integer counts = workshopService.delnum(conds);
            rtnJson.put("iTotalRecords", counts);
            rtnJson.put("iTotalDisplayRecords", counts);
            rtnJson.put("aaData", workshopList);
        }catch (Exception e){
            rtnJson.put("errorNo","1");
            LOGGER.error("查询签到列表失败",e);
        }
        return rtnJson;
    }

    @RequestMapping(value = "sign",method = RequestMethod.GET)
    @RequiresPermissions(value = MEETINGSIGN_VIEW)
    @ResponseBody
    public JSONObject formPost(String code, HttpServletRequest request){
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo","0");
        try{
            Conds conds  = new Conds();
            conds.equal("w.invitcode",code);
            List<WorkshopDto> workshops =  workshopService.searchmembershop(conds,null,0,0);
            if(workshops!=null && workshops.size()>0){
                WorkshopDto workshop = workshops.get(0);
                if(!workshop.getStatus().equals("1")){
                    return rtnJson;
                }
                Workshop works = new Workshop();
                works.setId(workshop.getId());
                works.setStatus("2");
                works.setNumber("【打印签到】,管理员ID["+UserUtils.getUser().getId()+"],签到人员ID["+workshop.getId()+"],邀请码["+code+"]，时间["+ DateFormatUtils.getDateTimeFormat(new Date()) +"]");
                workshopService.update(works);
                LOGGER.info("【打印签到】,管理员ID["+UserUtils.getUser().getId()+"],签到人员ID["+workshop.getId()+"],邀请码["+code+"]");
                if(StringUtils.isNotBlank(workshop.getOpen_id())){
                    String templateId = SystemConfig.p.getProperty("SIGNTEMPLATE");
                    String desc = "";
//                    if(StringUtils.isNotBlank(workshop.getTable_number())){
//                        desc=",您的晚宴桌号是"+workshop.getTable_number();
//                    }
                    String first = "尊敬的"+workshop.getMsurname()+workshop.getMname()+",您好!您已签到成功"+desc+"。";

                    Meeting meeting = meetingService.fetchById(workshop.getWsid());
                    String remarks = "欢迎您参加"+meeting.getTitle()+"。点击了解更多会议信息↓";
                    //String remarks = "欢迎您参加"+meeting.getTitle()+"。点击查看晚宴桌位分布图↓";
                    /**
                     * 签到地点，要求苏州太湖万豪酒店，活动地址配置太长，故用空格做区分
                     */
                    String signAddress = meeting.getAddress();
                    if(StringUtils.isNotBlank(signAddress) && signAddress.indexOf(" ")>=1){
                        signAddress = signAddress.split(" ")[0];
                    }
                    String [] keywords = {signAddress,DateUtils.formatDate(new Date(),"yyyy-MM-dd")};
                    String url = domain+"/schaeffler/static/mp/schaeffler/overview.html?appid="+appid+"&id="+meeting.getId();
                    sendMessage(templateId,tokenUtil.getToken(UserUtils.getmpaccounts(request)),workshop.getOpen_id(),first,remarks,keywords,url);
                }
            }
        }catch (Exception e){
            rtnJson.put("errorNo","1");
            LOGGER.error("查询签到列表失败",e);
        }
        return rtnJson;
    }

    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);
    }

    //心跳检查
    @RequestMapping(value = "heartBeat",method = RequestMethod.GET)
    @RequiresPermissions(value = MEETINGSIGN_VIEW)
    @ResponseBody
    public JSONObject heartBeat(){
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("aaData", "1");
        return rtnJson;
    }

}
