<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public $all_unread_sms;

    function __construct() {
        parent::__construct();
        $this->permission->is_admin();
        //$this->output->enable_profiler(TRUE);
        $this->load->model('Infotasks_model');
        $this->load->model('Infotaskarticles_model');
        $this->load->model('InfoSMS_model');
        $this->load->model('Operator_model');
        $this->load->model('Infoauthors_model');
    }

    //所有任务
    public function index($page = 1) {
        $data = array();
        $data = $this->_get_home_base_data();
        //已完成任务使用另一模板
        if ($this->input->get('taskstatus') == 'complete') {
            $this->in_complete_tasks();
            return;
        }
        $task_list = $this->_get_task_list(false, $page, site_url("welcome/index"));
        $data['task_list'] = $task_list['task_list'];
        $data['page'] = $task_list['page'];
        $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_all') + $data, true);
        $this->load->view('header', array('navbar_active' => 'mytask') + $data);
        $this->load->view('tasklist');
        $this->load->view('footer');
    }

    //正在编辑的任务
    public function in_edit_tasks($page = 1) {
        $data = array();
        $data = $this->_get_home_base_data();
        $task_list = $this->_get_task_list('edit', $page, site_url("welcome/in_edit_tasks"));
        $data['task_list_in_edit'] = $task_list['task_list'];
        $data['page'] = $task_list['page'];
        $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_edit') + $data, true);
        $this->load->view('header', array('navbar_active' => 'mytask') + $data);
        $this->load->view('welcome');
        $this->load->view('footer');
    }

    //已经完成的任务
    public function in_complete_tasks($page = 1) {
        $data = array();
        $data = $this->_get_home_base_data();
        $task_list = $this->_get_task_list('complete', $page, site_url("welcome/in_complete_tasks"));
        $data['task_list'] = $task_list['task_list'];
        $data['page'] = $task_list['page'];

        foreach ($data['task_list'] as $task) {
            $task->last_version = $this->Infotaskarticles_model->version_last($task->t_id);
        }
        $data['site_config'] = $this->config->item('site');
        $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_complete') + $data, true);
        $this->load->view('header', array('navbar_active' => 'mytask') + $data);
        $this->load->view('in_complete');
        $this->load->view('footer');
    }

    //未通过审核的投稿申请
    public function in_refuse_tasks($page = 1) {
        $data = array();
        $data = $this->_get_home_base_data();
        $task_list = $this->_get_task_list('refuse', $page, site_url("welcome/in_refuse_tasks"));
        $data['task_list'] = $task_list['task_list'];
        $data['page'] = $task_list['page'];

        $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_refuse') + $data, true);
        $this->load->view('header', array('navbar_active' => 'mytask') + $data);
        $this->load->view('in_refuse');
        $this->load->view('footer');
    }

    //根据任务状态获取任务列表
    public function task_lists($t_status = false, $page = 1) {
        $data = array();
        $data = $this->_get_home_base_data();
        $admin_info = $this->session->userdata('session_admin');
        $task_list = $this->_get_task_list($t_status, $page, site_url("welcome/task_lists/$t_status"));
        $data['task_list'] = $task_list['task_list'];
        $data['page'] = $task_list['page'];
        $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_' . $t_status) + $data, true);
        $this->load->view('header', array('navbar_active' => 'mytask') + $data);
        $this->load->view('in_refuse');
        $this->load->view('footer');
    }

    //获取任务列表
    function _get_task_list($t_status = false, $page = false, $pageurl = false) {
        $t_td_type = $start_date = $tasktitle = false;
        $end_date = date('Y-m-d');
        if ($this->input->get('tasktype') && $this->input->get('tasktype') != '-')
            $t_td_type = $this->input->get('tasktype');
        if ($this->input->get('startdate') && $this->input->get('startdate') != '')
            $start_date = $this->input->get('startdate');
        if ($this->input->get('enddate') && $this->input->get('enddate') != '')
            $end_date = $this->input->get('enddate');
        if ($this->input->get('tasktitle') && $this->input->get('tasktitle') != '')
            $tasktitle = $this->input->get('tasktitle');
        if (!$t_status && $this->input->get('taskstatus') && $this->input->get('taskstatus') != '-')
            $t_status = $this->input->get('taskstatus');
        $admin_info = $this->session->userdata('session_admin');

        //分页
        $page_task = $this->Infotasks_model->get_tasks_list($t_status, $admin_info->a_id, $t_td_type, $start_date, $end_date, $tasktitle, $page);
        $pages['total'] = count($page_task);
        $pages['pageSize'] = 20;
        $pages['url'] = $pageurl;
        $pages['current'] = $page;
        $task_list['page'] = show_page($pages);

        //获取任务列表
        $task_id_str = 0;
        $page_task = array_slice($page_task, $pages['pageSize'] * ($page - 1), $pages['pageSize']);
        foreach ($page_task as $v) {
            $task_id_str.=',' . $v->t_id;
        }
        $task_list['task_list'] = $this->Infotasks_model->get_list_by_taskids($task_id_str);

        return $task_list;
    }

    public function _get_home_base_data() {
        $user_data = $this->session->userdata('session_admin');
        $data['author_rank_list'] = $this->Infotasks_model->get_author_rank_list();
        $data['article_rank_list'] = $this->Infotasks_model->get_article_rank_list();
        //最新公告
        $announce = $this->Infotaskarticles_model->get_announce('', 'announce');
        $data['announce'] = array();
        if (!empty($announce))
            $data['announce'] = $announce;
        $data['notice_list'] = $this->Infotaskarticles_model->get_announce();
        $data['avatar'] = get_author_photo();
        $data['rank_view'] = $this->load->view('rank', $data, true);
        //获取作者网前url名字组成部分
        $data['suer_weburl'] = get_user_web_url();
        return $data;
    }

    public function view($t_id) {
        $data = array();
        $data['task'] = $this->Infotasks_model->detail($t_id);
        $admin_info = $this->session->userdata('session_admin');
        if (empty($data['task'])) {
            show_404();
            return false;
        }
        $data['task_detail'] = $this->Infotaskarticles_model->detail($data['task']->t_id);
        $data['task_last_version'] = $this->Infotaskarticles_model->version_last($data['task']->t_id);
        if (!empty($data['task_detail'])) {
            $data['information'] = $this->Infotaskarticles_model->get_information($data['task_detail']->ta_ic_id);
            if (isset($data['information']->ic_sitecode)) {
                $sitedata = $this->config->item('site');
                $data['sitedata'] = $sitedata[$data['information']->ic_sitecode];
            }
            //判断任务是否已上线
            $data['task_status'] = $this->Infotasks_model->is_in_used($data['task_detail']->ta_id);
        }

        if ($data['task']->t_a_id != $admin_info->a_id and $data['task_detail']->ta_isbest == NULL) {
            show_404();
            return false;
        }

        switch ($data['task']->t_status) {
            case 'published':
            case 'complete':
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_complete') + $data, true);
                break;
            case 'review':
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_review') + $data, true);
                break;
            case 'reviewed':
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_reviewed') + $data, true);
                break;
            case 'unreviewed':
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_unreviewed') + $data, true);
                break;
            case 'refuse':
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_refuse') + $data, true);
                break;
            case 'wait':
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_refuse') + $data, true);
                break;
            default:
                $data['nav_view'] = $this->load->view('nav', array('nav_active' => 'in_edit') + $data, true);
                break;
        }

        //获取短消息列表
        $data['sms_list'] = $this->InfoSMS_model->get_task_sms($data['task']->t_id);
        $admin_info = $this->session->userdata('session_admin');
        foreach ($data['sms_list'] as $sms) {
            if ($sms->m_receiver == $admin_info->a_id) {
                $this->InfoSMS_model->readed($sms->m_id);
            }
        }
        $data['admin_info_user'] = $admin_info->a_id;
        $this->load->view('header', array('navbar_active' => 'mytask') + $data);
        if ($data['task']->t_status == 'refuse') {
            $this->load->view('edit_refuse_task'); //未通过审核的投稿
        } else {
            $this->load->view('task_detail');
        }
        $this->load->view('footer');
    }

    public function edit_submit($task_submit = false) {
        $t_id = $this->input->post('t_id');
        $task = $this->Infotasks_model->detail($t_id);
        $admin_info = $this->session->userdata('session_admin');
        if ($admin_info->a_id != $task->t_a_id) {
            $data[] = array('name' => 'no', 'value' => 'error:it\'s not your task!');
            echo json_encode($data);
            return false;
        }

        $task_used = $this->Infotaskarticles_model->detail($t_id);
        /* if(empty($task_used))
          {
          $data[] = array('name' => 'no', 'value' => $this->lang->line('task_error_notfound'));
          echo json_encode($data);
          return false;
          } */

        $task_original = $this->Infotaskarticles_model->detail_original($t_id);
        if (empty($task_original)) {
            if (!empty($task_used)) {
                //把原始任务状态改为original，防止原始任务信息被删除
                $this->Infotaskarticles_model->set_original($task_used->ta_id);
            }
            //新建一个任务，状态改为used
            $this->Infotaskarticles_model->add($t_id, $this->input->post('ta_ic_id'), $this->input->post('ta_title')
                    , $this->input->post('ta_content'), $this->input->post('ta_summary'), $this->input->post('ta_seo_title')
                    , $this->input->post('ta_seo_description'), $this->input->post('ta_seo_keywords')
                    , $this->input->post('ta_photo'));
            if (!$task_submit) {
                $data[] = array('name' => 'ok', 'value' => $this->lang->line('script_success_save'));
                echo json_encode($data);
            }
            return true;
        } else {
            if (empty($task_used)) {
                $data[] = array('name' => 'no', 'value' => $this->lang->line('task_error_notfound'));
                echo json_encode($data);
                return false;
            }
            $this->Infotaskarticles_model->update($task_used->ta_id, $this->input->post('ta_title'), $this->input->post('ta_content')
                    , $this->input->post('ta_summary'), $this->input->post('ta_seo_title')
                    , $this->input->post('ta_seo_description'), $this->input->post('ta_seo_keywords')
                    , $this->input->post('ta_photo'));
            if (!$task_submit) {
                $data[] = array('name' => 'ok', 'value' => $this->lang->line('script_success_save'));
                echo json_encode($data);
            }
            return true;
        }
    }

    public function review_submit() {
        if ($this->edit_submit(true)) {
            $this->Infotaskarticles_model->add($this->input->post('t_id'), $this->input->post('ta_ic_id'), $this->input->post('ta_title')
                    , $this->input->post('ta_content'), $this->input->post('ta_summary'), $this->input->post('ta_seo_title')
                    , $this->input->post('ta_seo_description'), $this->input->post('ta_seo_keywords')
                    , $this->input->post('ta_photo'), 'version');
            $this->Infotasks_model->reviwed($this->input->post('t_id'), 'review');
            //发送消息
            $this->InfoSMS_model->add('task', $this->input->post('t_id'), $this->input->post('ht_user'), $this->input->post('t_a_id'), 'Task submitted; please check!');
            $data[] = array('name' => 'ok', 'value' => $this->lang->line('task_success_submit'));
            echo json_encode($data);
            return true;
        }
    }

    //发送短消息给管理员
    public function send_to_admin() {
        $t_id = $this->input->post('t_id');
        $task = $this->Infotasks_model->detail($t_id);
        if (empty($task)) {
            $data[] = array('name' => 'no', 'value' => $this->lang->line('task_error_notfound'));
            echo json_encode($data);
            return false;
        }
        $this->form_validation->set_rules('m_content', 'lang:task_m_content', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data = array();
            foreach ($this->form_validation->_error_array as $key => $value) {
                $data[] = array('name' => $key, 'value' => $value);
            }
            echo json_encode($data);
            return false;
        } else {
            $this->InfoSMS_model->add('task', $task->t_id, $task->t_ht_op_code, $task->t_a_id, $this->input->post('m_content'));
            $data[] = array('name' => 'ok', 'value' => $this->lang->line('send_sms_success'));
            echo json_encode($data);

            //发送邮件通知
            $admin_info = $this->session->userdata('session_admin');
            $author_admin = $this->Operator_model->get_user($task->t_ht_op_code);
            $this->InfoSMS_model->send_mail($admin_info->a_name, $admin_info->a_email, 'gavin', 'gavin@chinahighlights.com', sprintf($this->lang->line('author_email_message_subject'), $task->t_title), $this->lang->line('author_email_message_body'));
            return true;
        }
    }

    public function create_task() {
        $data = array();
        $data = $this->_get_home_base_data();
        $data['nav_view'] = $this->load->view('nav_hall', array('nav_active' => 'create_task') + $data, true);
        $this->load->view('header', array('navbar_active' => 'create_task') + $data);
        $this->load->view('create_task');
        $this->load->view('footer');
    }

    public function create_task_submit() {
        $this->form_validation->set_rules('t_title', 'lang:t_title', 'required');
        $this->form_validation->set_rules('t_content', 'lang:t_content', 'required');
        $this->form_validation->set_rules('t_expires', 'lang:t_expires', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data = array();
            foreach ($this->form_validation->_error_array as $key => $value) {
                $data[] = array('name' => $key, 'value' => $value);
            }
            echo json_encode($data);
            return false;
        } else {
            //TODO:暂时把稿件全部发给RURU(zzy)，今后会读取各站点的管理员名单
            $admin_info = $this->session->userdata('session_admin');
            $this->Infotasks_model->add(
                    $this->input->post('t_title'), $this->input->post('t_content'), $admin_info->a_id, 'Gavin', 'contribute', $this->input->post('t_expires'), 'wait', $this->config->item('site_code'), $this->input->post('t_attach')
            );
            $this->Infotaskarticles_model->add($this->Infotasks_model->insert_id, 0, '', '', '', '', '', '', '');
            $this->InfoSMS_model->add('task', $this->Infotasks_model->insert_id, 'Gavin', $admin_info->a_id, 'I have submitted a proposal; please check!');

            $data[] = array('name' => 'ok', 'value' => $this->lang->line('task_create_success'));
            $data[] = array('name' => 'ok_go', 'value' => site_url('welcome'));
            echo json_encode($data);

            return true;
        }
    }

    public function upload_task_attach() {
        $save_path = 'task_attach';
        $jsfunction = 'upload_task_attach';
        $upload_id = 'task_attach';

        $config['upload_path'] = APPPATH . 'document/' . $save_path;
        $config['allowed_types'] = 'gif|jpg|png|rar|zip|docx|doc|xls|xlsx|ppt';
        $config['encrypt_name'] = true;

        $this->load->library('upload', $config);
        if (!$this->upload->do_upload($upload_id)) {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);
        } else {
            $data = array('upload_data' => $this->upload->data());
            $file_name = $data['upload_data']['file_name'];
            echo "<script>parent.$jsfunction('$file_name');</script>";
        }
    }

    //修改后重新提交投稿申请
    public function update_task() {
        $this->form_validation->set_rules('t_title', 'lang:t_title', 'required');
        $this->form_validation->set_rules('t_content', 'lang:t_content', 'required');
        $this->form_validation->set_rules('t_expires', 'lang:t_expires', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data = array();
            foreach ($this->form_validation->_error_array as $key => $value) {
                $data[] = array('name' => $key, 'value' => $value);
            }
            echo json_encode($data);
            return false;
        } else {
            //更新任务状态
            $result = $this->Infotasks_model->update(
                    $this->input->post('t_id'), $this->input->post('t_title'), $this->input->post('t_content'), $this->input->post('t_a_id'), 'contribute', $this->input->post('t_expires'), 'wait', $this->input->post('t_attach')
            );
            if ($result) {
                $this->InfoSMS_model->add('task', $this->input->post('t_id'), 'Gavin', $this->input->post('t_a_id'), 'I have submitted a proposal; please check!');
                $data[] = array('name' => 'ok', 'value' => 'success');
            } else {
                $data[] = array('name' => 'no', 'value' => 'error');
            }
            echo json_encode($data);
        }
        return true;
    }

    //删除任务
    public function delete_task($t_id) {
        $this->Infotasks_model->delete($t_id);
        if ($this->Infotasks_model->delete($t_id)) {
            redirect(site_url('welcome/in_refuse_tasks'));
        } else {
            header('Location: ' . $_SERVER['HTTP_REFERER']);
        }
        return true;
    }

    //返回指定页面路径pagepath在指定时间内的成效信息
    public function get_analytics_by_date($loadtotal = 0) {
        $data = array();
        //获取请求的日期范围以及请求的页面路径
        $startdate = $this->input->post('startdate');
        $enddate = $this->input->post('enddate');
        $pagepath = $this->input->post('pagepath');
        $sitecode = $this->input->post('sitecode');
        if (empty($pagepath)) {
            echo '';
            return false;
        }
        //如果开始时间为空则把开始时间设为往前七天
        if ($startdate == '') {
            $startdate = time() - 7 * 24 * 60 * 60;
        } else {
            $startdate = strtotime($startdate);
        }
        //如果结束时间为空，则把结束时间设为当天
        if ($enddate == '') {
            $enddate = time();
        } else {
            $enddate = strtotime($enddate);
        }
        if ($startdate > $enddate) {
            echo "please check your date";
            die();
        }
        //查取google分析数据
        $data['analytics_list'] = $this->Infotaskarticles_model->get_analytics_list($pagepath, $sitecode, 50, $startdate, $enddate);
        $total_visit['pv'] = $total_visit['uv'] = $total_visit['agv_time'] = $total_visit['entrances'] = 0;
        $analytics_count = 0;
        //访问量汇总
        foreach ($data['analytics_list'] as $v) {
            $total_visit['pv']+=$v->kwa_pageviews;
            $total_visit['uv']+=$v->kwa_uniquepageviews;
            $total_visit['agv_time']+=$v->kwa_avgtimeonpage;
            $total_visit['entrances']+=$v->kwa_entrances;
            $analytics_count++;
        }
        $analytics_count == 0 ? $analytics_count = 1 : null;
        $total_visit['agv_time'] = ceil($total_visit['agv_time'] / $analytics_count);
        $data['total_visit'] = $total_visit;
        //如果loadtotal==1,则只返回google分析的汇总数据;如果loadtotal==0，则返回明细数据表
        $data['loadtotal'] = $loadtotal;

        $this->load->view('analytics', $data);
    }

    public function set_readed($m_id) {
        $this->InfoSMS_model->readed($m_id);
        echo 'ok';
    }

    public function search_by_icid() {
        $ic_id_list = $this->input->post('ic_id_list');
        $ic_id_list = rtrim(trim($ic_id_list), ',') . ',';
        $this->load->model('InfoContents_model');
        $data['search_list'] = $this->InfoContents_model->get_ic_contents_by_list($ic_id_list);
        $data['search_type'] = 'recommended';
        $this->load->view('recommendlist', $data);
    }

    public function search() {
        $this->load->model('Information_model');
        $data['keywords'] = $this->input->post('keywords');
        $search_url = str_replace($this->config->item('site_url'), "", $data['keywords']);
        $data['search_list'] = $this->Information_model->search_url($search_url);
        if (count($data['search_list']) === 0) {
            $data['search_list'] = $this->Information_model->search($data['keywords']);
        }
        $data['ic_id_list'] = $this->input->post('ic_id_list') == '' ? '0' : $this->input->post('ic_id_list');
        $this->load->view('recommendlist', $data);
        return TRUE;
    }

    //保存自定义配置
    function save_meta() {
        $this->load->model('InfoMetas_model');
        $im_ic_id = $this->input->post('im_ic_id');
        $im_key = $this->input->post('im_key');
        $im_value = $this->input->post('im_value');
        if ($im_ic_id && $im_key && $im_value !== false) {
            $meta = $this->InfoMetas_model->get($im_ic_id, $im_key);
            if ($meta === false) {
                $this->InfoMetas_model->add($im_ic_id, $im_key, $im_value);
            } else {
                $this->InfoMetas_model->update($im_ic_id, $im_key, $im_value);
            }
            $data[] = array('name' => 'ok', 'value' => 'success');
        } else {
            $data[] = array('name' => 'no', 'value' => 'error');
        }
        echo json_encode($data);
        return true;
    }

    //保存自定义配置
    function delete_meta() {
        $this->load->model('InfoMetas_model');
        $im_ic_id = $this->input->post('im_ic_id');
        $im_key = $this->input->post('im_key');
        if ($im_ic_id && $im_key) {
            $this->InfoMetas_model->delete($im_ic_id, $im_key);
            $data[] = array('name' => 'ok', 'value' => 'success');
        } else {
            $data[] = array('name' => 'no', 'value' => 'error');
        }
        echo json_encode($data);
        return true;
    }

}
