<?php

/**
 *    会议相关
 *    请求地址如：http://oa.test/api.php?m=openmeet&a=test&openkey=fee5efd3a93ca5c6a85b679cde60faa2
 */
class openmeetClassAction extends openapiAction
{

    public function testAction() {
        $str = $this->postdata;
        return json_encode($str);
    }

    // 获取会议信息
    public function getMeetInfoAction() {
        $rawArr = $this->getpostarr();

        if (!isset($rawArr['device_id'])) {
            $this->showreturn([], "参数错误", 201);
        }

        $rawData = m('meeting_room')->getone(" mac = '{$rawArr['device_id']}'");

        if (!isset($rawData['room_name'])) {
            $this->showreturn([], "未找到会议室", 202);
        }

        $sqlStr = /** @lang text */
            "SELECT 1 as type, id, title, start_time, end_time, null as compere, meet_state, is_hand
               FROM `[Q]meeting` 
              where start_time REGEXP '".date("Y-m-d")."'
                and end_time > now()
                and status = 1
                and meeting_room = '".$rawData['room_name']."'
             union all
             SELECT 2 as type, id, title, start_time, end_time, compere, meet_state, is_hand 
               FROM `[Q]meeting_key` 
              where start_time REGEXP '".date("Y-m-d")."' 
                and end_time > now()
                and meeting_room = '".$rawData['room_name']."'";

        $meetData = $this->db->getall($sqlStr);

        if (count($meetData) == 0) {
            $this->showreturn(
                [
                    "meeting_list"=>[],
                    "basic_information"=>[
                        "meeting_room_name" => $rawData['room_name'],
                        "meeting_name" => '空闲中',
                        "meeting_time" => null,
                        "meeting_moderator" => null,
                    ],
                    "meetingTopic"=>[],
                    "participants"=>[]
                ],
                "暂无会议",
                203);
        }

        $data = [];

        for ($i = 0; $i < count($meetData); $i++) {
            $meeting = $meetData[$i];
            $data['meeting_list'][$i] = [
                "meeting_name"=>str_replace("\n", "",$meeting['title']),
                "meeting_time"=>date("H:i", strtotime($meeting['start_time'])).' ~ '.date("H:i", strtotime($meeting['end_time'])),
                "meeting_moderator"=>$meeting['compere'],
                "meeting_state"=>$meeting['meet_state'] == 1 ? 1 : 0,
            ];

            // 时间到了自动结束一下
            if (strtotime($meeting['end_time']) < strtotime(date("Y-m-d H:i:s"))) {
                if ($meeting['type'] == 1) {
                    m("meeting")->update(["meet_state"=>2], "id=".$meeting['id']);
                } else {
                    m("meeting_key")->update(["meet_state"=>2], "id=".$meeting['id']);
                }
            } else if (strtotime($meeting['start_time']) > strtotime(date("Y-m-d H:i:s"))) {
                if ($meeting['type'] == 1) {
                    m("meeting")->update(["meet_state"=>0], "id=".$meeting['id']);
                } else {
                    m("meeting_key")->update(["meet_state"=>0], "id=".$meeting['id']);
                }
            } else if (strtotime($meeting['start_time']) < strtotime(date("Y-m-d H:i:s")) && $meeting['is_hand'] != 2) {
                if ($meeting['type'] == 1) {
                    m("meeting")->update(["meet_state"=>1], "id=".$meeting['id']);
                } else {
                    m("meeting_key")->update(["meet_state"=>1], "id=".$meeting['id']);
                }
            }
        }

        $nowMeetingSql = /** @lang text */
            "select * from (
            SELECT 1 as type, id, title, start_time, end_time, null as compere, meet_state, meeting_room, attendees
               FROM `[Q]meeting` 
              where status = 1 
                and start_time < now() 
                and end_time > now() 
                and meeting_room = '".$rawData['room_name']."'
             union all
             SELECT 2 as type, id, title, start_time, end_time, compere, meet_state, meeting_room, null as attendees
               FROM `[Q]meeting_key` 
              where start_time < now() and end_time > now() and meeting_room = '".$rawData['room_name']."'
              ) as t order by start_time";
        $nowMeetingData = $this->db->getall($nowMeetingSql);


        if (count($nowMeetingData) > 0 && $nowMeetingData[0]['meet_state'] != 2) {
            $nowMeet = $nowMeetingData[0];

            $data['basic_information'] = [
                "meeting_room_name" => $nowMeet['meeting_room'],
                "meeting_name" => str_replace("\n", "",$nowMeet['title']),
                "meeting_time" => date("H:i", strtotime($nowMeet['start_time'])).' ~ '.date("H:i", strtotime($nowMeet['end_time'])),
                "meeting_moderator" => $nowMeet['compere'],
            ];
            $data['meetingTopic'] = [];
            $data['participants'] = [];

            // 党委会议（需要加入议题）
            if ($nowMeet['type'] == 2) {

                $topics = $this->db->getall("select `id`, `topic_title`, `topic_attendee`, `topic_state`, `topic_info` from `[Q]meeting_topics` where mid = {$nowMeet['id']} order by sort");

                $meetingTopic = array_fill(0, count($topics) - 1, null);
                // 会议议题处理

                for ($i = 0,$j = 0; $i < count($topics); $i++) {
                    $info = $topics[$i];
                    // 用于排序（已结束放最后）
                    if ($info['topic_state'] == 3) {
                        $index = count($topics) - 1 - $j++;
                    } else {
                        $index = $i-$j;
                    }

                    $meetingTopic[$index]['state'] = $info['topic_state'];
                    $meetingTopic[$index]['tip'] = m("meeting")->ytarra[$info['topic_state']];
                    $meetingTopic[$index]['text'] = $info['topic_title'];
                    $meetingTopic[$index]['personnel_list'] = str_replace("\n", "<br />", $info['topic_info']);

                    if ($info['topic_state'] == 2) {
                        // 当前议题 + 参会人员
                        $data['participants'][] = [
                            "topics" => $info['topic_title'],
                            "personnel_list" => str_replace("\n", "<br />", $info['topic_info']),
                        ];
                        // 下一议题 + 参会人员
                        if (isset($topics[$i + 1])) {
                            $data['participants'][] = [
                                "topics" => $topics[$i + 1]['topic_title'],
                                "personnel_list" => str_replace("\n", "<br />", $topics[$i + 1]['topic_info']),
                            ];
                        }
                    }
                }
                $data['meetingTopic'] = $meetingTopic;

            } else {
                // 普通会议，议题为空
                $data['meetingTopic'] = [];
                // 基础会议人员信息
                $data['participants'] = [
                    [
                        "topics"=>$nowMeet['title'],
                        "personnel_list"=>str_replace("\n", "<br />", $nowMeet['attendees']),
                    ]
                ];
            }
        } else {
            $data['basic_information'] = [
                "meeting_room_name" => $rawData['room_name'],
                "meeting_name" => '空闲中',
                "meeting_time" => null,
                "meeting_moderator" => null,
            ];
            $data['meetingTopic'] = [];
            $data['participants'] = [];
        }
        $this->showreturn($data, "请求成功");
    }

    // 手机端 - 会议室列表
    public function mMeetRoomListAction() {

        $rawArr = $this->getpostarr();
        if (isset($rawArr['date'])) {
            $dataDate = substr($rawArr['date'], 0, 10);
        } else {
            $dataDate = date("Y-m-d");
        }

        $dataArr = m("meeting_room")->getall('1=1');
        $list = [];

        for ($i = 0; $i < count($dataArr); $i++) {
            $data = $dataArr[$i];

            $sqlStr = /** @lang text */
                "SELECT count(1) con FROM (
                    SELECT 1 FROM `[Q]meeting`
                     WHERE `status` = 1
                       and `start_time` < now()
                       and `meet_state` != 2
                       and `room_id` = '".$data['id']."'
                    UNION ALL
                    SELECT 1 FROM `[Q]meeting_key`
                     WHERE `start_time` < now()
                       and `meet_state` != 2
                       and `room_id` = '".$data['id']."'
                ) t";
            $meetingHave = $this->db->getall($sqlStr);

            $sqlStr = /** @lang text */
                "SELECT count(1) con FROM (
                    SELECT 1 FROM `[Q]meeting`
                     WHERE `status` = 1
                       AND `meet_state` != 2
                       AND `start_time` REGEXP '".$dataDate."'
                       AND `room_id` = '".$data['id']."'
                    UNION ALL
                    SELECT 1 FROM `[Q]meeting_key`
                     WHERE `start_time` REGEXP '".$dataDate."'
                       AND `meet_state` != 2
                       AND `room_id` = '".$data['id']."'
                ) t";
            $meetCon = $this->db->getall($sqlStr);

            $list[$i] = [
                'meeting_room_id' => $data['id'],
                'meeting_room_name' => $data['room_name'],
                'meeting_room_state' => $meetingHave[0]['con'] ?? 0 > 0 ? 1 : 0,
                'meeting_room_state_text' => $meetingHave[0]['con']  ?? 0 > 0 ? "会议中" : "空闲中",
                'meeting_today_num' => $meetCon[0]['con'] ?? 0
            ];
        }

        $this->showreturn($list,'success');
    }

    // 手机端 - 会议列表
    public function mMeetListAction() {
        $rawArr = $this->getpostarr();

        if (!isset($rawArr['room_id'])) {
            return returnerror('参数缺失');
        }
        $roomId = $rawArr['room_id'];

        $roomInfo = m('meeting_room')->getone("id={$roomId}");
        if (empty($roomInfo)) {
            return returnerror('会议室不存在！');
        }

        if (isset($rawArr['date'])) {
            $dataDate = substr($rawArr['date'], 0, 10);
        } else {
            $dataDate = date("Y-m-d");
        }


        $sqlStr = /** @lang text */
            "SELECT 1 as type, id, title, start_time, end_time, null compere, '办公会议' as meeting_type 
               FROM `[Q]meeting`
              WHERE `status` = 1
                and `start_time` regexp '".$dataDate."'
                and `meet_state` != 2
                and `room_id` = '".$roomId."'
             UNION ALL
             SELECT 2 as type, id, title, start_time, end_time, compere, '党委会议' as meeting_type 
               FROM `[Q]meeting_key`
              WHERE `start_time` regexp '".$dataDate."'
                and `meet_state` != 2
                and `room_id` = '".$roomId."'
            ";
        $meetingArr = $this->db->getall($sqlStr);

        if (!empty($meetingArr)) {

            for ($i = 0; $i < count($meetingArr); $i++) {
                $meet = $meetingArr[$i];
                $meet_time = date("H:i", strtotime($meet['start_time'])).' ~ '.date("H:i", strtotime($meet['end_time']));
                $state_code =  m("meeting")->meetingState($meet['start_time'], $meet['end_time'], 1);
                $state_text =  m("meeting")->meetingState($meet['start_time'], $meet['end_time'], 2);
                $list["meeting_list"][$i] = [
                    "meeting_id" => $meet['id'],
                    "meeting_name" => str_replace("\n", "",$meet['title']),
                    "meeting_time" => $meet_time,
                    "meeting_moderator" => $meet['compere'],
                    "meeting_state" => $state_code,
                    "meeting_state_text" => $state_text,
                    "meeting_type" => $meet['meeting_type'],
                    "meeting_type_id" => $meet['type'],
                ];

                // 会议中
                if ($state_code == 1) {
                    $meeting = [
                        "meeting_room_name" => $roomInfo['room_name'],
                        "meeting_name" => m("meeting")->meetingState($meet['start_time'], $meet['end_time'], 2),
                        "meeting_time" => $meet_time,
                        "meeting_moderator" => null,
                    ];
                }
            }

            if (empty($meeting)) {
                $list['basic_information'] = [
                    "meeting_room_name" => $roomInfo['room_name'],
                    "meeting_name" => '空闲中',
                    "meeting_time" => null,
                    "meeting_moderator" => null,
                ];
            } else {
                $list['basic_information'] = $meeting;
            }


        } else {
            $list['basic_information'] = [
                "meeting_room_name" => $roomInfo['room_name'],
                "meeting_name" => '空闲中',
                "meeting_time" => null,
                "meeting_moderator" => null,
            ];
            $list['meeting list'] = [];
        }


        $this->showreturn($list,'success');

    }

    // 手机端 - 会议详情
    public function mMeetDetailAction() {
        $rawArr = $this->getpostarr();

        if (!isset($rawArr['meet_id']) && !isset($rawArr['meet_type'])) {
            return returnerror('参数缺失');
        }
        $meetId = $rawArr['meet_id'];
        $meetType = $rawArr['meet_type'];
        // 普通会议
        if ($meetType == 1) {
            $meetInfo = $this->db->getone("[Q]meeting", "`id` = '".$meetId."'");
            if (!empty($meetInfo)) {
                $info['basic_information'] = [
                    "meeting_name"=>str_replace("\n", "",$meetInfo['title']),
                    "meeting_time"=>$meetInfo['start_time'],
                    "meeting_moderator"=>null,
                    "meeting_state"=>$meetInfo['meet_state'],
                    "meeting_state_text"=>m('meeting')->hyarra[$meetInfo['meet_state']],
                    "meeting_type"=>"办公会议",
                    "meeting_attendees"=>[
                        [
                            "label"=>"参会部门及人员",
                            "text"=>$meetInfo['attendees']
                        ],
                        [
                            "label"=>"备注",
                            "remark"=>$meetInfo['remark']
                        ]
                    ]
                ];
                $info['meetingTopic'] = [];
                $this->showreturn($info, 'success');
            }
        } else {
            // 党委会议
            $meetInfo = $this->db->getone("[Q]meeting_key", "`id` = '".$meetId."'");
            if (!empty($meetInfo)) {
                $info['basic_information'] = [
                    "meeting_name"=>str_replace("\n", "",$meetInfo['title']),
                    "meeting_time"=>$meetInfo['start_time'],
                    "meeting_moderator"=>$meetInfo['compere'],
                    "meeting_state"=>$meetInfo['meet_state'],
                    "meeting_state_text"=>m('meeting')->hyarra[$meetInfo['meet_state']],
                    "meeting_type"=>"党委会议",
                    "meeting_attendees"=>[
                        [
                            "label"=>"出席",
                            "text"=>str_replace("\n", " ", $meetInfo['attendees']),
                        ],
                        [
                            "label"=>"列席",
                            "text"=>str_replace("\n", " ", $meetInfo['attends']),
                        ]
                    ]
                ];

                // 会议议题
                $topics = m("meeting_topics")->getall("`mid` = '".$meetId."'", "*", "sort");

                $meetingTopic = array_fill(0, count($topics), null);
                // 会议议题处理
                for ($i = 0,$j = 0; $i < count($topics); $i++) {
                    $topiic = $topics[$i];
                    // 用于排序（已结束放最后）
                    if ($topiic['topic_state'] == 3) {
                        $index = count($topics) - 1 - $j++;
                    } else {
                        $index = $i-$j;
                    }

                    $meetingTopic[$index]['state'] = $topiic['topic_state'];
                    $meetingTopic[$index]['tip'] = m("meeting")->ytarra[$topiic['topic_state']];
                    $meetingTopic[$index]['text'] = $topiic['topic_title'];
                    $meetingTopic[$index]['personnel_list'] = str_replace("\n", "<br />", $topiic['topic_info']);

                }
                $info['meetingTopic'] = $meetingTopic;

                $this->showreturn($info, 'success');
            }
        }
        return returnerror('未找到会议');
    }




    protected function getWeek($date=null) {
        if (!isset($date)) {
            $date = date("Y-m-d H:i:s");
        }
        // 将日期转换为时间戳
        $timestamp = strtotime($date);

        // 格式化输出星期几（返回值为英文）
        $weekday_en = date('l', $timestamp);

        // 如果需要显示中文星期几，则需要进行相关处理
        switch ($weekday_en) {
            case 'Monday':
                $weekday_cn = "星期一";
                break;
            case 'Tuesday':
                $weekday_cn = "星期二";
                break;
            case 'Wednesday':
                $weekday_cn = "星期三";
                break;
            case 'Thursday':
                $weekday_cn = "星期四";
                break;
            case 'Friday':
                $weekday_cn = "星期五";
                break;
            case 'Saturday':
                $weekday_cn = "星期六";
                break;
            default:
                $weekday_cn = "星期天";
        }
        return $weekday_cn;
    }

}