<?php

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

class Author extends CI_Controller {

    public $all_unread_sms;

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

    public function index($loadexcel = 'notexcel', $page = 1) {
        $this->load->library('accesscheck');
        $this->accesscheck->check_access();
        //获取任务状态
        $request_form = 'get';
        if ($loadexcel == 'loadexcel')
            $request_form = 'post';
        $t_status = $this->input->$request_form('taskstatus');
        if ($t_status == "-")
            $t_status = false;
        //根据任务状态加载视图模板
        switch (trim($t_status)) {
            case 'edit':
                $this->in_edit_tasks($loadexcel);
                break;
            case 'review':
                $this->in_review_tasks($loadexcel);
                break;
            case 'reviewed':
                $this->in_reviewed_tasks($loadexcel);
                break;
            case 'complete':
                $this->in_complete_tasks($loadexcel);
                break;
            case 'wait':
                $this->in_wait_tasks($loadexcel);
                break;
            default:
                //获取作者列表
                $data['author_list'] = $this->Infoauthors_model->active_list();
                $task_list = $this->_get_tasks_list(false, $loadexcel, $page, site_url("author/index/$loadexcel"));
                $data['task_list'] = $task_list['task_list'];
                //导出数据到excel表格
                if ($loadexcel == 'loadexcel') {
                    $this->load_to_excel($data['task_list']);
                    return;
                }
                $data['page'] = $task_list['page'];
                $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'all_tasks'), true);
                $this->load->view('bootstrap/header', $data);
                $this->load->view("bootstrap/author/index");
                $this->load->view('bootstrap/footer');
        }
    }

    //进行中任务列表
    public function in_edit_tasks($loadexcel = 'notexcel', $page = false) {
        $task_list = $this->_get_tasks_list('edit', $loadexcel, $page, site_url("author/in_edit_tasks/$loadexcel"));
        $data['task_list'] = $task_list['task_list'];
        //导出数据到excel表格
        if ($loadexcel == 'loadexcel') {
            $this->load_to_excel($data['task_list']);
            return;
        }
        $data['page'] = $task_list['page'];
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_edit'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/welcome');
        $this->load->view('bootstrap/footer');
    }

    //待审核任务列表
    public function in_review_tasks($loadexcel = 'notexcel', $page = false) {
        $task_list = $this->_get_tasks_list('review', $loadexcel, $page, site_url("author/index/$loadexcel"));
        $data['task_list'] = $task_list['task_list'];
        //导出数据到excel表格
        if ($loadexcel == 'loadexcel') {
            $this->load_to_excel($data['task_list']);
            return;
        }
        $data['page'] = $task_list['page'];
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_review'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/welcome');
        $this->load->view('bootstrap/footer');
    }

    //待结算任务列表
    public function in_reviewed_tasks($loadexcel = 'notexcel', $page = false) {
        //获取任务列表
        $task_list = $this->_get_tasks_list('reviewed', $loadexcel, $page, site_url("author/index/$loadexcel"));
        $data['task_list'] = $task_list['task_list'];
        //获取作者列表
        $data['author_list'] = $this->Infoauthors_model->active_list();
        foreach ($data['task_list'] as $task) {
            $task->last_version = $this->Infotaskarticles_model->version_last($task->t_id);
        }
        //导出数据到excel表格
        if ($loadexcel == 'loadexcel') {
            $this->load_to_excel($data['task_list']);
            return;
        }
        //获取最活跃作者
        $active_author = array();
        $data['isset_active_author'] = $this->Infotasks_model->is_active_author();
        if (!empty($data['task_list']) && $data['isset_active_author'] != 1) {
            $active_author = $this->Infotasks_model->get_author_count();
        }
        $data['page'] = $task_list['page'];
        $data['active_author'] = $active_author;
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_reviewed'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/task_list_reviewed');
        $this->load->view('bootstrap/footer');
    }

    //待审核投稿
    public function in_wait_tasks($loadexcel = 'notexcel', $page = false) {
        $admin_info = $this->session->userdata('session_admin');
        $task_list = $this->_get_tasks_list('wait', $loadexcel, $page, site_url("author/index/$loadexcel"));
        $data['task_list'] = $task_list['task_list'];
        //导出数据到excel表格
        if ($loadexcel == 'loadexcel') {
            $this->load_to_excel($data['task_list']);
            return;
        }
        $data['page'] = $task_list['page'];
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_wait'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/welcome');
        $this->load->view('bootstrap/footer');
    }

    //已完成任务列表
    public function in_complete_tasks($loadexcel = 'notexcel', $page = 1) {
        $data['author_list'] = $this->Infoauthors_model->active_list();
        $task_list = $this->_get_tasks_list('complete', $loadexcel, $page, site_url("author/in_complete_tasks/$loadexcel"));
        $data['task_list'] = $task_list['task_list'];
        foreach ($data['task_list'] as $t) {
            $t->last_version = $this->Infotaskarticles_model->version_last($t->t_id);
        }
        //导出数据到excel表格
        if ($loadexcel == 'loadexcel') {
            $this->load_to_excel($data['task_list']);
            return;
        }
        $data['page'] = $task_list['page'];
        $data['site_config'] = $this->config->item('site');
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_complete'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/task_list_complete');
        $this->load->view('bootstrap/footer');
    }

    //查询任务列表
    public function _get_tasks_list($t_status = false, $loadexcel = false, $page = false, $pageurl = false) {
        //异步获取任务列表时数据提交方式为get，导出数据时则为post
        $request_form = 'get';
        if ($loadexcel == 'loadexcel')
            $request_form = 'post';
        //任务过滤参数初始化
        $t_a_id = $t_td_type = $start_date = $tasktitle = false;
        $end_date = date('Y-m-d');
        if ($this->input->$request_form('author') && $this->input->$request_form('author') != 0)
            $t_a_id = $this->input->$request_form('author');
        if ($this->input->$request_form('tasktype') && $this->input->$request_form('tasktype') != '-')
            $t_td_type = $this->input->$request_form('tasktype');
        if ($this->input->$request_form('startdate') && $this->input->$request_form('startdate') != '')
            $start_date = $this->input->$request_form('startdate');
        if ($this->input->$request_form('enddate') && $this->input->$request_form('enddate') != '')
            $end_date = $this->input->$request_form('enddate');
        if ($this->input->$request_form('tasktitle') && $this->input->$request_form('tasktitle') != '')
            $tasktitle = $this->input->$request_form('tasktitle');
        $admin_info = $this->session->userdata('session_admin');
        //获取任务列表
        if ($loadexcel == 'loadexcel') {
            $task_list['task_list'] = $this->Infotasks_model->get_tasks_list($t_status, $admin_info['OPI_Code'], $t_a_id, $t_td_type, $start_date, $end_date, $tasktitle);
            return $task_list;
        }

        //分页
        $page_task = $this->Infotasks_model->get_tasks_list($t_status, $admin_info['OPI_Code'], $t_a_id, $t_td_type, $start_date, $end_date, $tasktitle, $page);
        $pages['total'] = count($page_task); //数据总条数
        $pages['pageSize'] = 50; //每页展示数量
        $pages['url'] = $pageurl; //页码链接
        $pages['current'] = $page; //当前页码
        $task_list['page'] = show_page($pages);

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

    public function create_task($is_id = false) {
        $data = array();
        if ($is_id) {
            $data['information'] = $this->Information_model->Detail($is_id);
            if ($data['information'] === false) {
                show_404();
                return false;
            }
        }
        $data['author_list'] = $this->Infoauthors_model->active_list();
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'create_task'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/task_create');
        $this->load->view('bootstrap/footer');
    }

    public function delete_task() {
        $admin_info = $this->session->userdata('session_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;
        }

        if ($task->t_ht_op_code != $admin_info['OPI_Code']) {
            $data[] = array('name' => 'no', 'value' => $this->lang->line('task_error_no_permissions'));
            echo json_encode($data);
            return false;
        }

        $this->Infotasks_model->delete($t_id);
        $data[] = array('name' => 'ok', 'value' => $this->lang->line('task_delete_ok'));
        $data[] = array('name' => 'ok_go', 'value' => site_url('author'));
        echo json_encode($data);
        return false;
    }

    public function review_task_submit() {
        $t_id = $this->input->post('t_id');
        $t_rating = $this->input->post('t_rating');
        $t_rating_total = $this->input->post('t_rating_total');

        $task = $this->Infotasks_model->detail($t_id);
        if (empty($task)) {
            $data[] = array('name' => 'no_modal', 'value' => $this->lang->line('task_error_notfound'));
            echo json_encode($data);
            return false;
        }
        $reviewed = $this->input->post('reviewed');
        if ($reviewed == 'reviewed') {
            $this->form_validation->set_rules('ta_count', 'lang:ta_count', 'required|numeric');
            $this->form_validation->set_rules('ta_charge', 'lang:ta_charge', 'required|numeric');
            //$this->form_validation->set_rules('review_m_content', 'lang:review_m_content', 'required');
        } else {
            //审核不通过
            $this->form_validation->set_rules('review_m_content', 'lang:review_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 {
            $flag = false;
            if ($this->input->post('ispublish') == 1) {
                $ispublished = $this->publish_task($task);
                $flag = $ispublished;
                //发布失败
                if (!$ispublished) {
                    $data[] = array('name' => 'no_modal', 'value' => $this->lang->line('publish_task_failed'));
                    echo json_encode($data);
                    return false;
                }
            }

            $this->Infotasks_model->reviwed($t_id, $reviewed, $t_rating, $t_rating_total);
            //保存审核字数和金额
            if ($reviewed == 'reviewed') {
                $this->Infotaskarticles_model->update_review($t_id, $this->input->post('ta_count'), $this->input->post('ta_charge'));
            }
            $msg = '';
            if ($flag != false)
                $msg = ' <a target="_blank" href="' . $flag . '"> 跳转到信息平台发布页</a>';
            $data[] = array('name' => 'ok_modal', 'value' => $this->lang->line('task_review_submit') . $msg);
            $data[] = array('name' => 'ok_go', 'value' => site_url('author/in_review_tasks'));
            echo json_encode($data);

            //发送邮件通知给作者
            $admin_info = $this->session->userdata('session_admin');
            $author = $this->Infoauthors_model->detail_by_id($task->t_a_id);
            //通过审核
            if ($reviewed == 'reviewed') {
                $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $author->a_name, $author->a_email, sprintf($this->lang->line('author_email_review_task_success_subject'), $task->t_title), $this->lang->line('author_email_review_task_success_body'));
            } else {
                $this->Infotasks_model->reviwed($t_id, 'unreviewed', $t_rating, $t_rating_total);
                $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $author->a_name, $author->a_email, sprintf($this->lang->line('author_email_review_task_failed_subject'), $task->t_title), $this->lang->line('author_email_review_task_failed_body'));
            }
        }
        $this->InfoSMS_model->add('task', $t_id, $task->t_a_id, $task->t_ht_op_code, $this->input->post('review_m_content'));
    }

    public function publish_task($task) {
        $this->load->model('Logs_model');
        $t_id = $this->input->post('t_id');
        $ic_is_id = $this->input->post('choose_ic_is_id');

        $task_last_version = $this->Infotaskarticles_model->version_last($task->t_id);
        if (empty($task_last_version->ta_ic_id)) {
            $selected_name = $this->input->post('choose_is_ic_name');
            $is_id = mb_substr($selected_name, strpos($selected_name, '{') + 1, -1);
            $information = $this->Information_model->Detail($is_id);
            if (empty($information)) {
                return false;
            }

            //添加到信息平台
            $this->InfoContents_model->Add($task_last_version->ta_title, $task_last_version->ta_title, '', $task_last_version->ta_title, $task_last_version->ta_content
                    , $task_last_version->ta_summary, $task_last_version->ta_seo_title, $task_last_version->ta_seo_description, $task_last_version->ta_seo_keywords
                    , 0, 0, '', $task_last_version->ta_photo, 0, 0, '', '', $information->ic_ht_area_id, $information->ic_ht_area_type, 0, '', $task->t_a_id);
            if ($this->InfoStructures_model->Add($information->is_id, $this->InfoContents_model->insert_id)) {
                $result = site_url('information/edit/' . $this->InfoStructures_model->insert_id);
            } else {
                $result = false;
            }
            //把任务和信息做关联
            $this->Infotaskarticles_model->link($task_last_version->ta_id, $this->InfoContents_model->insert_id);
        } else {
            //已经有信息关联，只需要更新对应的字段
            $information = $this->Information_model->detail_by_ic_id($task_last_version->ta_ic_id);
            if (!$information) {
                return false;
            }
            $this->InfoContents_model->Update($information->ic_id, $information->ic_url, $information->ic_url_title, $information->ic_type, $task_last_version->ta_title, $task_last_version->ta_content
                    , $task_last_version->ta_summary, $task_last_version->ta_seo_title, $task_last_version->ta_seo_description, $task_last_version->ta_seo_keywords
                    , $information->ic_show_bread_crumbs, $information->ic_status, $information->ic_template, $task_last_version->ta_photo, $information->ic_photo_width
                    , $information->ic_photo_height, $information->ic_recommend_tours, $information->ic_recommend_packages, $information->ic_ht_area_id
                    , $information->ic_ht_area_type, $information->ic_ht_product_id, $information->ic_ht_product_type, $information->ic_author);
            if ($ic_is_id) {
                $this->Logs_model->backup($ic_is_id, $task_last_version->ta_content);
            }
            $result = site_url('information/edit/' . $information->is_id);
        }
        return $result;
    }

    //发布信息
    public function publish_task_submit() {
        $this->load->model('Logs_model');
        $t_id = $this->input->post('t_id');
        $ic_is_id = $this->input->post('ic_is_id');
        $task = $this->Infotasks_model->detail($t_id);
        if ($task === false) {
            show_404();
            return false;
        }

        $action_result = true;

        $task_last_version = $this->Infotaskarticles_model->version_last($task->t_id);
        $information = false;
        if (!empty($task_last_version->ta_ic_id))
            $information = $this->Information_model->detail_by_ic_id($task_last_version->ta_ic_id);
        if (empty($task_last_version->ta_ic_id) or ! $information) {
            $selected_name = $this->input->post('selected_is_ic_name');
            $is_id = mb_substr($selected_name, strpos($selected_name, '{') + 1, -1);
            $information = $this->Information_model->Detail($is_id);
            if (empty($information)) {
                $action_result = false;
                $data[] = array('name' => 'no_modal', 'value' => $this->lang->line('structures_error_notfound'));
                echo json_encode($data);
                return false;
            }

            //添加到信息平台
            $this->InfoContents_model->Add($task_last_version->ta_title, $task_last_version->ta_title, '', $task_last_version->ta_title, $task_last_version->ta_content
                    , $task_last_version->ta_summary, $task_last_version->ta_seo_title, $task_last_version->ta_seo_description, $task_last_version->ta_seo_keywords
                    , 0, 0, '', $task_last_version->ta_photo, 0, 0, '', '', $information->ic_ht_area_id, $information->ic_ht_area_type, 0, '', $task->t_a_id);
            if ($this->InfoStructures_model->Add($information->is_id, $this->InfoContents_model->insert_id)) {
                $im_ic_id = $this->InfoContents_model->insert_id;
                $data[] = array('name' => 'ok_modal', 'value' => sprintf($this->lang->line('publish_task_success'), site_url('information/edit/' . $this->InfoStructures_model->insert_id)));
                //$this->Infotasks_model->reviwed($t_id,'published');//标识已经发布
            } else {
                $action_result = false;
                $data[] = array('name' => 'no_modal', 'value' => $this->lang->line('publish_task_failed'));
            }
            //把任务和信息做关联
            $this->Infotaskarticles_model->link($task_last_version->ta_id, $this->InfoContents_model->insert_id);
        } else {
            //已经有信息关联，只需要更新对应的字段
            $im_ic_id = $information->ic_id;
            $this->InfoContents_model->Update($information->ic_id, $information->ic_url, $information->ic_url_title, $information->ic_type, $task_last_version->ta_title, $task_last_version->ta_content
                    , $task_last_version->ta_summary, $task_last_version->ta_seo_title, $task_last_version->ta_seo_description, $task_last_version->ta_seo_keywords
                    , $information->ic_show_bread_crumbs, $information->ic_status, $information->ic_template, $task_last_version->ta_photo, $information->ic_photo_width
                    , $information->ic_photo_height, $information->ic_recommend_tours, $information->ic_recommend_packages, $information->ic_ht_area_id
                    , $information->ic_ht_area_type, $information->ic_ht_product_id, $information->ic_ht_product_type, $information->ic_author);
            $data[] = array('name' => 'ok_modal', 'value' => sprintf($this->lang->line('publish_task_success'), site_url('information/edit/' . $information->is_id)));
            if ($ic_is_id) {
                $this->Logs_model->backup($ic_is_id, $task_last_version->ta_content);
            }
            //$this->Infotasks_model->reviwed($t_id,'published');//标识已经发布
        }
        if ($action_result) {
            //若作者平台的作者推荐了相关推荐信息，则先删除旧的推荐信息再添加新的推荐信息
            $author_recommend_info = get_meta($t_id, 'meta_author_recommend_info');
            $author_related_info = get_meta($t_id, 'meta_author_related_info');
            if (!empty($author_recommend_info)) {
                delete_meta($im_ic_id, 'meta_recommend_info');
                add_meta($im_ic_id, 'meta_recommend_info', $author_recommend_info);
            }
            if (!empty($author_related_info)) {
                delete_meta($im_ic_id, 'meta_related_info');
                add_meta($im_ic_id, 'meta_related_info', $author_related_info);
            }
        }

        echo json_encode($data);
        return true;
    }

    //结算
    public function complete_task_submit() {
        $t_ids = $this->input->post('t_ids');
        if (empty($t_ids)) {
            $data[] = array('name' => 'no', 'value' => $this->lang->line('task_complete_notfound'));
            echo json_encode($data);
            return false;
        }
        foreach ($t_ids as $t_id) {
            $this->Infotasks_model->reviwed($t_id, 'complete');
        }
        //设置月度活跃作者
        if ($this->input->post('isset_active_author') == 0) {
            $this->Infotasks_model->set_active_author(
                    $this->input->post('active_t_id'), date('Y-m-d H:i:s'), $this->input->post('active_ta_id')
            );
        }
        $data[] = array('name' => 'ok', 'value' => $this->lang->line('task_complete_success'));
        $data[] = array('name' => 'ok_go', 'value' => site_url('author/in_reviewed_tasks'));
        echo json_encode($data);
        return true;
    }

    public function edit_task($t_id) {
        $data = array();
        $data['task'] = $this->Infotasks_model->detail($t_id);
        if ($data['task'] === false) {
            show_404();
            return false;
        }

        $task_detail = $this->Infotaskarticles_model->detail($data['task']->t_id);
        if ($task_detail) {
            $data['information'] = $this->Information_model->detail_by_ic_id($task_detail->ta_ic_id);
            //判断任务是否已上线
            $data['task_status'] = $this->Infotasks_model->is_in_used($task_detail->ta_id);
        }
        $data['task_detail_list'] = $this->Infotaskarticles_model->version_list($data['task']->t_id);
        $data['task_last_version'] = $this->Infotaskarticles_model->version_last($data['task']->t_id);

        $data['author_list'] = $this->Infoauthors_model->active_list();
        switch ($data['task']->t_status) {
            case 'review':
                $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_review') + $data, true);
                break;
            case 'reviewed':
                $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_reviewed') + $data, true);
                break;
            case 'published':
            case 'complete':
                $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_complete') + $data, true);
                break;
            case 'wait':
                $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_wait') + $data, true);
                break;
            default:
                $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'in_edit') + $data, true);
                break;
        }

        //获取根节点列表，用于跨类型迁移信息
        $root_type_list = $this->Information_model->root_type_list();
        $data['root_type_list'] = '"0"';
        foreach ($root_type_list as $item) {
            $data['root_type_list'].=',"' . str_replace('\'', '', $item->ic_url_title) . '-{' . $item->is_id . '}' . '"';
        }

        //获取短消息列表
        $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['OPI_Code']) {
                $this->InfoSMS_model->readed($sms->m_id);
            }
        }

        //获取该任务审核次数并计算奖励的百分比
        $review_count = $this->Infotaskarticles_model->get_review_count($t_id);
        switch ($review_count) {
            case 1:
                $data['discount'] = array('1.1', '110%');
                break;
            case 2:
                $data['discount'] = array('1.05', '105%');
                break;
            case 0:
            case 3:
                $data['discount'] = array('1', '100%');
                break;
            default:
                $data['discount'] = array('0.9', '90%');
        }

        $this->load->view('bootstrap/header', $data);
        if ($data['task']->t_status == 'wait') {
            $this->load->view('bootstrap/author/task_contribute');
        } else {
            $this->load->view('bootstrap/author/task_create');
        }
        $this->load->view('bootstrap/footer');
    }

    //修改任务详细信息
    public function save_task_datailinfo() {
        $result = $this->Infotaskarticles_model->update(
                $this->input->post('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 ($result) {
            $data[] = array('name' => 'ok', 'value' => 'success!');
        } else {
            $data[] = array('name' => 'no', 'value' => 'error!');
        }
        echo json_encode($data);
        return true;
    }

    //审核投稿申请
    public function change_wait_tast_status($t_status = 'edit') {
        $t_id = $this->input->post('t_id');
        $t_a_id = $this->input->post('t_a_id');
        $refuse_msg = $this->input->post('refuse_msg');

        $admin_info = $this->session->userdata('session_admin');
        $author = $this->Infoauthors_model->detail_by_id($t_a_id);
        if ($t_status == 'edit' && $this->Infotasks_model->reviwed($t_id, $t_status)) {
            if (!empty($author)) {
                $this->InfoSMS_model->add('task', $t_id, $t_a_id, $admin_info['OPI_Code'], 'Your proposal has been approved！');
                $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $author->a_name, $author->a_email, 'Your proposal has been approved.', 'Your proposal has been approved！Please log in at <a href="http://author.mycht.cn" target="_blank">http://author.mycht.cn</a>');
            }
            $data[] = array('name' => 'ok', 'value' => 'success');
        } elseif ($t_status == 'refuse' && $this->Infotasks_model->reviwed($t_id, $t_status)) {
            //如果指定用户则发送邮件通知
            if (!empty($author)) {
                $this->InfoSMS_model->add('task', $t_id, $t_a_id, $admin_info['OPI_Code'], $refuse_msg);
                $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $author->a_name, $author->a_email, 'Your proposal has been rejected.', 'Your proposal has been rejected: ' . $refuse_msg . ' Please log in at <a href="http://author.mycht.cn" target="_blank">http://author.mycht.cn</a>');
            }
            $data[] = array('name' => 'no', 'value' => 'success');
        }
        echo json_encode($data);
        return true;
    }

    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);
        } else {
            //任务ID，用来判断当前任务是新增还是更新
            $t_id = $this->input->post('t_id');
            if (!empty($t_id)) {
                //更新
                //$t_id 查找一次任务详细，用来判断当前用户是否有权限修改，暂时省略

                $this->Infotasks_model->update(
                        $t_id, $this->input->post('t_title'), $this->input->post('t_content'), $this->input->post('t_a_id'), $this->input->post('t_td_type'), $this->input->post('t_expires')
                );
                $data[] = array('name' => 'ok', 'value' => $this->lang->line('task_success_submit'));
                echo json_encode($data);
            } else {
                $admin_info = $this->session->userdata('session_admin');
                $this->Infotasks_model->add(
                        $this->input->post('t_title'), $this->input->post('t_content'), $this->input->post('t_a_id'), $admin_info['OPI_Code'], $this->input->post('t_td_type'), $this->input->post('t_expires'), $this->config->item('site_code')
                );
                //新建
                $is_id = $this->input->post('is_id');
                if (!empty($is_id)) {
                    $information = $this->Information_model->Detail($is_id);
                    if ($information === false) {
                        $data[] = array('name' => 'no', 'value' => $this->lang->line('structures_error_notfound'));
                        echo json_encode($data);
                        return false;
                    }

                    //添加推荐文章信息
                    $meta_recommend_info = get_meta($information->ic_id, 'meta_recommend_info');
                    $meta_related_info = get_meta($information->ic_id, 'meta_related_info');
                    if (!empty($meta_recommend_info)) {
                        add_meta($this->Infotasks_model->insert_id, 'meta_author_recommend_info', $meta_recommend_info);
                    }
                    if (!empty($meta_related_info)) {
                        add_meta($this->Infotasks_model->insert_id, 'meta_author_related_info', $meta_related_info);
                    }

                    if (empty($information->ic_summary))
                        $information->ic_summary = '';
                    $this->Infotaskarticles_model->add($this->Infotasks_model->insert_id, $information->ic_id, $information->ic_title
                            , $information->ic_content, $information->ic_summary, $information->ic_seo_title, $information->ic_seo_description
                            , $information->ic_seo_keywords, $information->ic_photo);
                } else {
                    $this->Infotaskarticles_model->add($this->Infotasks_model->insert_id, 0, '', '', '', '', '', '', '');
                }

                $add_articles_res = $this->Infotaskarticles_model->detail($this->Infotasks_model->insert_id);

                if (!$add_articles_res) {
                    $this->Infotasks_model->delete($this->Infotasks_model->insert_id);
                    $data[] = array('name' => 'no', 'value' => "创建任务失败" . $this->Infotaskarticles_model->insert_id);
                    echo json_encode($data);
                    return false;
                }
                //如果指定用户则发送邮件通知
                $t_a_id = $this->input->post('t_a_id');
                //所有作者
                $author_list = $this->Infoauthors_model->active_list();
                switch ($t_a_id) {
                    case 0://cht所有用户
                        foreach ($author_list as $a) {
                            if ($a->a_sitecode == 'cht' || empty($a->a_sitecode)) {
                                $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $a->a_name, $a->a_email, sprintf($this->lang->line('author_email_new_task_subject'), $this->input->post('t_title')), $this->lang->line('author_email_new_task_body2'));
                            }
                        }
                        break;
                    case -1://ah所有用户
                        foreach ($author_list as $a) {
                            if ($a->a_sitecode == 'ah') {
                                $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $a->a_name, $a->a_email, sprintf($this->lang->line('author_email_new_task_subject'), $this->input->post('t_title')), $this->lang->line('author_email_new_task_body2'));
                            }
                        }
                        break;
                    default://指定用户
                        $author = $this->Infoauthors_model->detail_by_id($t_a_id);
                        if (!empty($author)) {
                            $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $author->a_name, $author->a_email, sprintf($this->lang->line('author_email_new_task_subject'), $this->input->post('t_title')), $this->lang->line('author_email_new_task_body'));
                        }
                }

                $data[] = array('name' => 'ok', 'value' => $this->lang->line('task_success_submit'));
                $data[] = array('name' => 'ok_go', 'value' => site_url('author'));
                echo json_encode($data);
                return TRUE;
            }
        }
    }

    //作者列表
    public function author_list() {
        $data['author_list'] = $this->Infoauthors_model->active_list();
        $data['un_active_list'] = $this->Infoauthors_model->un_active_list();
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'author_list'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/author_list');
        $this->load->view('bootstrap/footer');
    }

    //作者列表
    public function unactive_author_list() {
        $data['author_list'] = $this->Infoauthors_model->un_active_list();
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'unactive_author_list'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/author_list');
        $this->load->view('bootstrap/footer');
    }

    //作者详细信息
    public function edit_author($a_id) {
        $data['author'] = $this->Infoauthors_model->detail_by_id($a_id);
        if (empty($data['author'])) {
            show_404();
        }
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'author_list'), true);
        $data['author_field'] = $this->load->view('bootstrap/author/author_field', $data, true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/author_edit');
        $this->load->view('bootstrap/footer');
    }

    //发送短消息给作者
    public function send_to_author() {
        $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_a_id, $task->t_ht_op_code, $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 = $this->Infoauthors_model->detail_by_id($task->t_a_id);
            if (!empty($author)) {
                $this->InfoSMS_model->send_mail($admin_info['OPI_Name'], $admin_info['OPI_Email'], $author->a_name, $author->a_email, sprintf($this->lang->line('author_email_message_subject'), $task->t_title), $this->lang->line('author_email_message_body'));
            }
            return true;
        }
    }

    public function edit_author_submit() {
        $a_id = $this->input->post('a_id');
        if (empty($a_id)) {
            show_404();
        }
        $this->Infoauthors_model->update_site($a_id, $this->input->post('a_sitecode'));
        $this->Infoauthors_model->reviwed($a_id, $this->input->post('a_active'));
        $admin_info = $this->session->userdata('session_admin');
        $this->InfoSMS_model->send_mail('gavin', 'gavin@chinahighlights.com', $this->input->post('edit_a_name'), $this->input->post('edit_a_email'), 'Sign Up For China Highlights Online Writers Platform', 'Welcom to China Highlights Online Writers Platform:<br><a href="http://author.mycht.cn">China Highlights Online Writers Platform</a>');
        $data[] = array('name' => 'ok', 'value' => $this->lang->line('author_review_submit'));
        echo json_encode($data);
    }

    //编辑作者资料
    public function profile_submit() {
        $a_id = $this->input->post('a_id');
        if (empty($a_id)) {
            show_404();
        }

        $this->form_validation->set_rules('a_email', 'lang:signup_a_email', 'required');
        $this->form_validation->set_rules('a_name', 'lang:signup_a_name', 'required');
        $this->form_validation->set_rules('a_bank', 'lang:a_bank', 'required');
        $this->form_validation->set_rules('a_bank_card', 'lang:a_bank_card', '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 {
            //头像处理
            $a_photo = $this->input->post('a_photo');
            if ($this->input->post('profile_url') != '') {
                $profile_file_path = getcwd() . '/author/document/profile_photo';
                $profile_url = $this->input->post('profile_url');
                $profile_array = explode('.', $profile_url);
                $profile_ext = 'jpg'; //end($profile_array);
                $new_profile = $profile_file_path . '/profile_' . $this->input->post('a_email') . '.' . $profile_ext;
                if (file_exists($new_profile))
                    unlink($new_profile);
                rename($profile_file_path . '/' . $profile_url, $new_profile);
                rename($profile_file_path . '/' . str_replace('_thumb', '', $profile_url), $profile_file_path . '/profile_' . $this->input->post('a_email') . '_org.' . $profile_ext);
                $a_photo = 'profile_' . $this->input->post('a_email') . '.' . $profile_ext;
            }

            //处理上传的身份证复印件
            if ($this->input->post('ID_file_name') != '') {
                $ID_file_path = getcwd() . '/author/document/ID_CARD';
                $a_id_file = $this->input->post('ID_file_name');
                $file_array = explode('.', $a_id_file);
                $ext = 'jpg'; //end($file_array);
                $new_file = $ID_file_path . '/id_card_' . $this->input->post('a_email') . '.' . $ext;
                if (file_exists($new_file))
                    unlink($new_file);
                rename($ID_file_path . '/' . $a_id_file, $new_file);
            }

            $a_name = trim($this->input->post('a_name'));
            $a_name_cn = trim($this->input->post('a_name_cn'));
            $this->Infoauthors_model->update($a_id, $this->input->post('a_email'), $a_name, $a_name_cn, $a_photo, $this->input->post('a_mobile_phone'), $this->input->post('a_phone'), $this->input->post('a_id_card'), $this->input->post('a_gender'), $this->input->post('a_address'), $this->input->post('a_school'), $this->input->post('a_bank'), $this->input->post('a_bank_card'), $this->input->post('a_resume'));

            $this->Infoauthors_model->set_title($a_id, $this->input->post('a_title'));

            $data[] = array('name' => 'ok', 'value' => $this->lang->line('setting_profile_success'));
            echo json_encode($data);
            return TRUE;
        }
    }

    //上传头像、身份证复印件等
    public function upload_ID_file($profile = false) {
        $save_path = 'ID_CARD';
        $jsfunction = 'get_id_card_file';
        $upload_id = 'ID_file';
        if ($profile) {
            $save_path = 'profile_photo';
            $jsfunction = 'get_photo_url';
            $upload_id = 'Profile_file';
        }
        $path = APPPATH;
        $config['upload_path'] = getcwd() . '/author/document/' . $save_path;
        $config['allowed_types'] = 'gif|jpg|png';
        $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'];
            if ($profile) {
                $baseurl_array = explode('application', dirname(__FILE__));
                $baseurls = $baseurl_array[0];
                $config['image_library'] = 'gd2';
                $config['source_image'] = $baseurls . 'author/document/profile_photo/' . $file_name;
                $config['create_thumb'] = TRUE;
                $config['maintain_ratio'] = false;
                $config['width'] = 175;
                $config['height'] = 175;
                $this->load->library('image_lib', $config);
                $this->image_lib->resize();
                $profile_array = explode('.', $file_name);
                $file_name = $profile_array[0] . '_thumb.' . $profile_array[1];
            }
            echo "<script>parent.$jsfunction('$file_name');</script>";
        }
    }

    //修改职称
    public function submit_author_title() {
        $a_id = $this->input->post('a_id');
        if (empty($a_id)) {
            show_404();
        }
        $this->Infoauthors_model->set_title($a_id, $this->input->post('a_title'));
        $data[] = array('name' => 'ok', 'value' => $this->lang->line('author_title_submit'));
        echo json_encode($data);
    }

    //公告管理
    public function announce_list() {
        $data['announce_list'] = $this->Infotaskarticles_model->get_announce('', 'announce');
        $data['notice_list'] = $this->Infotaskarticles_model->get_announce();
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'announce_list'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/announce_list');
        $this->load->view('bootstrap/footer');
    }

    //公告详情
    public function announce_detail($announce_id, $type = 'notice') {
        $announce = $this->Infotaskarticles_model->get_announce($announce_id, $type);
        $data['announce_detail'] = $announce[0];
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'announce_list'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/announce_list');
        $this->load->view('bootstrap/footer');
    }

    //编辑公告
    public function announce_edit($announce_id = "", $type = 'notice') {
        if ($announce_id != "") {
            $announce = $this->Infotaskarticles_model->get_announce($announce_id, $type);
            $data['announce'] = $announce[0];
        }
        $data['nav_view'] = $this->load->view('bootstrap/author/nav', array('nav_active' => 'announce_edit'), true);
        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/author/announce_edit');
        $this->load->view('bootstrap/footer');
    }

    //公告更新
    public function add_announce() {
        $title = $this->input->post('title');
        $announce = $this->input->post('announce');
        $announce_id = $this->input->post('announce_id');
        $announce_type = $this->input->post('announce_type');
        $result = false;
        if (!empty($announce_id)) {
            $result = $this->Infotaskarticles_model->update($this->input->post('announce_id'), $title, $announce, '', $announce_type, '', '', '');
        } else {
            $result = $this->Infotaskarticles_model->add(0, 0, $title, $announce, '', $announce_type, '', '', '', 'announce');
        }
        if ($result) {
            $datas[] = array('name' => 'ok', 'value' => 'success!');
            echo json_encode($datas);
        } else {
            $datas[] = array('name' => 'no', 'value' => 'error!');
            echo json_encode($datas);
        }
        return true;
    }

    //删除公告
    public function announce_delete($announce_id) {
        if ($this->Infotaskarticles_model->delete_announce($announce_id)) {
            $datas[] = array('name' => 'ok', 'value' => 'success!');
        } else {
            $datas[] = array('name' => 'no', 'value' => 'error!');
        }
        echo json_encode($datas);
    }

    //优秀文章评优处理
    public function set_task_charge() {
        $ta_isbest = NULL;
        if ($this->input->post('ta_isbest') == 1) {
            $ta_isbest = date('Y-m-d H:i:s');
        }
        $result = $this->Infotaskarticles_model->update_review($this->input->post('t_id'), $this->input->post('ta_count'), $this->input->post('ta_charge'), $ta_isbest);
        if ($result) {
            $datas = array('name' => 'ok', 'value' => 'success!');
        } else {
            $datas = array('name' => 'no', 'value' => 'error!');
        }
        echo json_encode($datas);
    }

    //标识所有收录信息为已读
    public function set_msg_to_read() {
        $msg_ids = array();
        $ic_id_str = $this->input->post('msg_ids');
        $msg_ids = explode(',', $ic_id_str);
        foreach ($msg_ids as $key => $v) {
            $this->InfoSMS_model->readed_for_info($v);
        }
        echo 1;
    }

    //下载数据列表
    public function load_to_excel($task_list) {
        $sum_count = $sum_charge = 0;
        $exceldata = array();
        $exceldata[0] = array('任务号', '任务名称', '类型', '作者', '编辑', '发布时间', '完成时间', '字数', '金额');
        foreach ($task_list as $key => $task) {
            if (isset($task->last_version->ta_count)) {
                $sum_count+=$task->last_version->ta_count;
            } else {
                $task->last_version->ta_count = '-';
            }
            if (isset($task->last_version->ta_charge)) {
                $sum_charge+=$task->last_version->ta_charge;
            } else {
                $task->last_version->ta_charge = '-';
            }
            if (!isset($task->last_version->ta_datetime)) {
                $task->last_version->ta_datetime = $task->t_expires;
                $exceldata[0][6] = '截止时间';
            }
            $k = $key + 1;
            $exceldata["$k"][] = $task->t_id; //任务号
            $exceldata["$k"][] = $task->t_title; //任务名称
            $exceldata["$k"][] = $task->t_td_type; //任务类型
            $exceldata["$k"][] = get_author_name($task->t_a_id); //作者
            $exceldata["$k"][] = get_author_name($task->t_ht_op_code); //编辑
            $exceldata["$k"][] = date('m/d/Y', strtotime($task->t_datetime)); //任务发布时间
            $exceldata["$k"][] = date('m/d/Y', strtotime($task->last_version->ta_datetime)); //完成时间或者截止时间
            $exceldata["$k"][] = $task->last_version->ta_count; //完成的字数
            $exceldata["$k"][] = $task->last_version->ta_charge; //金额
        }
        $exceldata[] = array('', '', '', '', '', '', '总计', $sum_count, $sum_charge);
        $this->_excel($exceldata);
    }

    //导出数据到excel
    //$output要填充到excel的数据,必须是一个二维数组
    public function _excel($output = array()) {
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Disposition:attachment;filename=" . time() . ".csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $excel_str = "";
        foreach ($output as $item) {
            foreach ($item as $v) {
                $v = str_replace(',', ' ', $v);
                $excel_str.=$v . ","; //设置某一单元格的值
            }
            $excel_str.="\n"; //添加行结束符
        }
        $filetype = $this->input->post('filetype');
        if ($filetype == 2)
            $excel_str = iconv('UTF-8', 'GB2312', $excel_str); //excel简体中文版使用gb2312编码
        echo "$excel_str";
    }

    //返回指定页面路径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 "请选择正确的日期";
            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('bootstrap/author/analytics', $data);
    }

}
