package com.persagy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.persagy.domain.ReservationCustom;
import com.persagy.domain.ReservationVo;
import com.persagy.domain.Room;
import com.persagy.service.ReservationService;
import com.persagy.service.RoomService;
import com.persagy.service.UserService;
import com.persagy.util.PinyinUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.netty.util.internal.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Admiral on 2018/1/20.
 */
@Controller
@ResponseBody
@RequestMapping("/ordinary")
public class OrdinaryController {

    @Resource(name = "roomServiceImpl")
    private RoomService roomService;
    @Resource(name = "userServiceImpl")
    private UserService userService;
    @Resource(name = "reservationServiceImpl")
    private ReservationService reservationService;
    //获取CorpAccessToken URL
    private String corpAccessTokenURL = "https://open.fxiaoke.com/cgi/corpAccessToken/get/V2";
    //部门列表
    private String departmentURL = "https://open.fxiaoke.com/cgi/department/list";
    //部门下人员列表
    private String userURL = "https://open.fxiaoke.com/cgi/user/list";
    //消息
    private String messageURL = "https://open.fxiaoke.com/cgi/message/send";
    private String corpAccessToken = null;
    private String corpId = null;

    /**
     * 获取会议室列表
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/roomList", method=RequestMethod.POST)
    @ResponseBody
    public List<Room> roomList() throws Exception {
        List<Room> list = roomService.findByPaging(1);
        return list;
    }

    /**
     * 根据会议室名称模糊搜索会议室
     * @param roomName
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryRoomByName", method = {RequestMethod.POST,RequestMethod.GET})
    private List<Room> queryRoomByName(@RequestBody String roomName) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(roomName);
        String name = jsonObject.getString("roomName");
        List<Room> list = roomService.findByName(name);
        return list;
    }

    /**
     * 根据会议室id查询会议室详情
     * @param roomID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryRoomById", method = {RequestMethod.POST,RequestMethod.GET})
    private Room queryRoomById(@RequestBody String roomID) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(roomID);
        Integer id = jsonObject.getInteger("roomID");
        String date = jsonObject.getString("date");
        Room room = roomService.findById(id);
        return room;
    }

    /**
     * 查询所有的会议室预约记录
     * @return
     * @throws Exception
     */
    @RequestMapping("/showRecord")
    public List<ReservationVo> findAllReservation() throws Exception {
        List<ReservationVo> list = null;
        list = reservationService.findAllByPaging(1);
        return list;
    }

    /**
     * 根据会议室id查询会议室记录
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/showRecordByRoomId")
    public List<ReservationVo> findAllReservationByRoomId(@RequestBody String id) throws Exception {

        JSONObject jsonObject = JSONObject.parseObject(id);
        Integer roomId = jsonObject.getInteger("id");
        String date = jsonObject.getString("date");
        List<ReservationVo> list2 = new ArrayList<>();
        List<ReservationVo> list = null;
        list = reservationService.findByRoomId(roomId);
        if(!StringUtils.isEmpty(date)){
            for (int i = 0; i < list.size(); i++) {
                ReservationVo vo = list.get(i);
                if(date.equals(vo.getDate())){
                    list2.add(vo);
                }
            }
        }else {
            return list;
        }
        return list2;
    }

    //搜索借用人

    /**
     * 搜索我组织的会议
     * @param userName
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryByUser",method = RequestMethod.POST)
    private List<ReservationVo> queryUser(@RequestBody String userName) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(userName);
        String name = jsonObject.getString("userName");
        List<ReservationVo> list = reservationService.queryByUser(name);
        return list;
    }

    //预约会议室页面跳转
    @RequestMapping(value = "/reserveRoom", method = RequestMethod.GET)
    public String reserveRoomUI(Model model) throws Exception {
        //从数据库查询出所有会议室信息回显到页面
        List<Room> list = roomService.nameList();
        model.addAttribute("nameList", list);

        return "/ordinary/reserveRoom";
    }

    /**
     * 预约会议室功能实现
     * @param reservation
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reserveRoom", method = RequestMethod.POST)
    public String reserveRoom(@RequestBody String reservation) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(reservation);
        String roomName = jsonObject.getString("roomName");
        int roomId = jsonObject.getIntValue("roomId");
        int alarmminute = jsonObject.getIntValue("alarmminute");
        String userName = jsonObject.getString("userName");
        String department = jsonObject.getString("department");
        String theme = jsonObject.getString("theme");
        JSONArray enterUsers = jsonObject.getJSONArray("enterUsers");

        JSONArray dateArray = jsonObject.getJSONArray("dateArray");
        String date = "";
        String beginTime = "";
        String endTime = "";
        for (int i = 0; i <dateArray.size() ; i++) {
            JSONObject json = dateArray.getJSONObject(i);
            date = json.getString("date");
            beginTime = json.getString("beginTime");
            endTime = json.getString("endTime");
//            String a = date+""+
            ReservationCustom reservationCustom = new ReservationCustom();
            reservationCustom.setDate(date);
            reservationCustom.setBeginTime(beginTime);
            reservationCustom.setEndTime(endTime);
            reservationCustom.setUser(userName);
            reservationCustom.setRoomId(roomId);
            reservationCustom.setMark("待审核");
            reservationCustom.setName(roomName);
            if(enterUsers != null){
                reservationCustom.setEnterUsers(enterUsers.toString());
            }
            reservationCustom.setTheme(theme);
            reservationCustom.setDepartment(department);
            reservationCustom.setAlarmminute(alarmminute);
            reservationService.addReservation(reservationCustom);
        }
        //发送消息
        //0. 获取所有人员
        JSONObject result = new JSONObject();
        JSONArray users = new JSONArray();
        users.add(userService.findUserById(userName).getFsuid());
        if(enterUsers !=null){
            for (int i = 0; i < enterUsers.size(); i++) {
                JSONObject object = enterUsers.getJSONObject(i);
                String uid = object.getString("id");
                users.add(uid);
            }
        }
        result.put("users",users);
        JSONObject result2 = new JSONObject();
        JSONObject message = new JSONObject();
        JSONObject head = new JSONObject();
        JSONObject head2 = new JSONObject();
        head2.put("title","详情");
        head2.put("url","http://www.fxiaoke.com");
        head.put("title","会议参加提醒");
        JSONObject first = new JSONObject();
        first.put("content","欢迎参加“"+userName+"”组织的【"+theme+"】会议，" +
                "会议将于"+date+" "+beginTime+"-"+endTime+"召开，请届时参见");
        message.put("head",head);
        message.put("first",first);
        message.put("link",head2);
        result.put("text",message);
        sendMessage(result.toString());

        return "success";
    }

    //取消预约申请页面跳转
    @RequestMapping(value = "/cancelApplication",method = RequestMethod.GET)
    public String cancelApplicationUI(String user,Model model) throws Exception{
        List<ReservationCustom> list=reservationService.findByUser(user);
        model.addAttribute("reserveList",list);

        return "/ordinary/cancelApplication";
    }

    /**
     * 根据预约id查看详情
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findByReservationId", method = RequestMethod.POST)
    public ReservationVo findByReservationId(@RequestBody String id) throws Exception{
        JSONObject jsonObject = JSONObject.parseObject(id);
        Integer cancelID = jsonObject.getInteger("id");
        ReservationVo reservationVo =reservationService.findByReservationId(cancelID);
        return reservationVo;
    }
    //取消预约申请业务实现
    @RequestMapping(value = "/cancelApply", method = RequestMethod.POST)
    public ReservationVo cancelApplication(@RequestBody String id) throws Exception{
        JSONObject jsonObject = JSONObject.parseObject(id);
        Integer cancelID = jsonObject.getInteger("id");
        reservationService.cancelApplication(cancelID);

        ReservationVo reservationVo =reservationService.findByReservationId(cancelID);
        String user = reservationVo.getUser();
        String theme =reservationVo.getTheme();

        String StringEnterUsers = reservationVo.getEnterUsers();
        JSONArray enterUsers = JSONArray.parseArray(StringEnterUsers);

        //发送消息
        //0. 获取所有人员
        JSONObject result = new JSONObject();
        JSONArray users = new JSONArray();
        users.add(userService.findUserById(user).getFsuid());
        if(enterUsers !=null){
            for (int i = 0; i < enterUsers.size(); i++) {
                JSONObject object = enterUsers.getJSONObject(i);
                String uid = object.getString("id");
                users.add(uid);
            }
        }
        result.put("users",users);
        JSONObject result2 = new JSONObject();
        JSONObject message = new JSONObject();
        JSONObject head = new JSONObject();
        JSONObject head2 = new JSONObject();
        head2.put("title","详情");
        head2.put("url","http://www.fxiaoke.com");
        head.put("title","会议取消提醒");
        JSONObject first = new JSONObject();
        first.put("content","您好，“"+user+"”组织的【"+theme+"】会议，" +
                "会议原定于"+reservationVo.getDate()+" "+reservationVo.getBeginTime()+"-"+reservationVo.getEndTime()+"召开，已经取消，请悉知。");
        message.put("head",head);
        message.put("first",first);
        message.put("link",head2);
        result.put("text",message);
        sendMessage(result.toString());

        return reservationVo;
    }
    //获取数字签名
    public void getSignature() throws Exception{
        //appId
        String appId = "FSAID_131860e";
        //appSecret
        String appSecret = "e1c53d3c6dff4e96b9ec155a031889af";
        //永久授权码
        String permanentCode = "B83ED308137C9653E543303740DB2533";
        JSONObject corpAccessTokenObj = getCorpAccessToken(appId,appSecret,permanentCode);
        corpAccessToken = corpAccessTokenObj.getString("corpAccessToken");
        corpId = corpAccessTokenObj.getString("corpId");

    }

    /**
     *  获取所有部门
     */
    @RequestMapping(value="/departmentList", method=RequestMethod.POST)
    @ResponseBody
    public String departmentList() throws Exception {
        getSignature();
        Map<String,Object> obj = new HashMap<String, Object>();
        obj.put("corpAccessToken",corpAccessToken);
        obj.put("corpId",corpId);
        String result = httpPostRequest(departmentURL, obj);
        return result;
    }

    /**
     * 获取部门下所有人员
     */
    @RequestMapping(value="/usertList", method=RequestMethod.POST)
    @ResponseBody
    public String usertList(@RequestBody String jsonStr) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String departmentId = jsonObject.getString("departmentId");
        Map<String,Object> obj = new HashMap<String, Object>();
        obj.put("corpAccessToken",corpAccessToken);
        obj.put("corpId",corpId);
        obj.put("departmentId",Integer.valueOf(departmentId));
        String result = httpPostRequest(userURL, obj);
        return result;
    }



    private JSONObject getCorpAccessToken(String appId, String appSecret, String permanentCode) throws Exception{
        Map<String,Object> obj = new HashMap<String, Object>();
        obj.put("appId",appId);
        obj.put("appSecret",appSecret);
        obj.put("permanentCode",permanentCode);
        String result = httpPostRequest(corpAccessTokenURL, obj);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    /**
     * 执行http请求
     * @param httpClient
     * @param httpRequest
     * @return
     */
    private String executeHttpRequest(CloseableHttpClient httpClient, HttpUriRequest httpRequest){
        CloseableHttpResponse response = null;
        String respContent = null;
        try {
            response = httpClient.execute(httpRequest);
            respContent = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
            if(response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
        }
        return respContent;
    }

    public String httpPostRequest(String url, Map<String, Object> params) throws Exception {
        String respContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        // 设置请求的的参数
        JSONObject jsonParam = new JSONObject();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            jsonParam.put(key, params.get(key));
        }
        httpPost.setEntity(new StringEntity(jsonParam.toString(), "utf-8"));
        // 执行请求
        respContent = executeHttpRequest(httpclient, httpPost);
        return respContent;
    }
    /**
     * 所有人员
     */
    @RequestMapping(value="/usertListFirst", method=RequestMethod.POST)
    @ResponseBody
    public String usertList() throws Exception {
        Map<String,Object> obj = new HashMap<String, Object>();
        obj.put("corpAccessToken",corpAccessToken);
        obj.put("corpId",corpId);
        String result = httpPostRequest(departmentURL, obj);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray departments = jsonObject.getJSONArray("departments");
        JSONArray jsonArray = new JSONArray();
        Integer departmentId = 0;
        for (int i = 0; i < departments.size(); i++) {
            JSONObject department = (JSONObject)departments.get(i);
            Boolean isStop = department.getBoolean("isStop");
            if(isStop){
               continue;
            }
            departmentId = department.getInteger("id");
            //获取人员
            Map<String,Object> personobj = new HashMap<String, Object>();
            personobj.put("corpAccessToken",corpAccessToken);
            personobj.put("corpId",corpId);
            personobj.put("departmentId",departmentId);
            String resultStr = httpPostRequest(userURL, personobj);
            jsonObject = JSONObject.parseObject(resultStr);
            JSONArray userList = jsonObject.getJSONArray("userList");
            for (int j = 0; j < userList.size(); j++) {
                JSONObject jsonObject1 = new JSONObject();
                JSONObject user = (JSONObject)userList.get(j);
                Boolean stop = user.getBoolean("isStop");
                if(stop){
                    continue;
                }
                String name = user.getString("name");
                String openUserId = user.getString("openUserId");
                String first = name;
                jsonObject1.put("name",name);
                jsonObject1.put("openUserId",openUserId);
//                System.out.println(PinyinUtils.getPinYinHeadChar(name));
                jsonObject1.put("first", PinyinUtils.getPinYinHeadChar(name));
                jsonArray.add(jsonObject1);
            }
        }
        return jsonArray.toJSONString();
    }
    /**
     * 发送消息
     */
    @RequestMapping(value="/sendMessage", method=RequestMethod.POST)
    @ResponseBody
    public String sendMessage(@RequestBody String jsonStr) throws Exception {
        getSignature();
        Map<String,Object> obj = new HashMap<String, Object>();
        obj.put("corpAccessToken",corpAccessToken);
        obj.put("corpId",corpId);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //消息内容
        JSONObject text = jsonObject.getJSONObject("text");
        //发送人
        JSONArray users = jsonObject.getJSONArray("users");

        obj.put("toUser",users);
        obj.put("msgType","composite");
        obj.put("composite",text);

        String result = httpPostRequest(messageURL, obj);
        return result;
    }
}
