<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------

namespace app\love\controller;

use app\admin\model\UserModel;
use app\common\Excel;
use app\common\Fun;
use app\love\model\ActiveApplyModel;
use app\love\model\ActiveModel;
use app\love\model\QuestionModel;
use app\love\model\UserOutlookModel;
use cmf\controller\AdminBaseController;

class AdminActiveController extends AdminBaseController
{
    /**
     * 列表
     */
    public function index()
    {
        $list = ActiveModel::paginate(10);
        foreach ($list as $v) {
            $v['url'] = urlencode(url('love/Scene/wechat', ['active_id' => $v['id']], true, true));
        }

        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        // 渲染模板输出
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 添加提交
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $post = $data['post'];

            if (empty($post['start_time'])) {
                $this->error('请选择开始时间');
            }

            if (empty($post['end_time'])) {
                $this->error('请选择结束时间');
            }

            $post['create_time'] = $post['update_time'] = time();
            $post['start_time']  = strtotime($post['start_time']);
            $post['end_time']    = strtotime($post['end_time']);
            ActiveModel::create($post);

            $this->success('添加成功!', url('index'));
        }

    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id   = $this->request->param('id', 0, 'intval');
        $post = ActiveModel::get($id);

        $this->assign('post', $post);
        return $this->fetch();
    }

    /**
     * 编辑提交
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data = $this->request->param();
            $post = $data['post'];

            if (empty($post['start_time'])) {
                $this->error('请选择开始时间');
            }

            if (empty($post['end_time'])) {
                $this->error('请选择结束时间');
            }

            $post['create_time'] = $post['update_time'] = time();
            $post['start_time']  = strtotime($post['start_time']);
            $post['end_time']    = strtotime($post['end_time']);
            ActiveModel::update($post, ['id' => $post['id']]);

            $this->success('编辑成功!', url('index'));
        }
    }

    /**
     * 审核列表
     */
    public function applyList()
    {
        $param = $this->request->param();
        $this->assign('id', $param['id']);
        $this->assign('check_status', $param['check_status'] ?? 0);
        $this->assign('sex', $param['sex'] ?? 0);

        $where = [
            ['active_id', '=', $param['id']],
        ];
        if (!empty($param['check_status'])) {
            $where[] = ['cmf_active_apply.check_status', '=', $param['check_status']];
        }
        $sexWhere = [];
        if (!empty($param['sex'])) {
            $sexWhere = ['sex' => $param['sex']];
        }
        $total = ActiveApplyModel::hasWhere('user', $sexWhere)->where($where)->count();
        $this->assign('total', $total);

        $list = ActiveApplyModel::hasWhere('user', $sexWhere)->with('user')->where($where)->order('check_status asc')->paginate(10, false, [
            'query' => $param,//不丢失已存在的url参数
        ]);
        foreach ($list as $v) {
            $v['age'] = Fun::getAgeByBirth($v['user']['birthday']);
        }

        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * 审核
     */
    public function checkPost()
    {
        $data = $this->request->post();
        ActiveApplyModel::update($data, ['id' => $data['id']]);

        $this->success('操作成功');
    }

    /**
     * 报名列表导出
     */
    public function applyExport()
    {
        $param = $this->request->param();

        $where = [
            ['active_id', '=', $param['id']],
        ];
        if (!empty($param['check_status'])) {
            $where[] = ['cmf_active_apply.check_status', '=', $param['check_status']];
        }
        $sexWhere = [];
        if (!empty($param['sex'])) {
            $sexWhere = ['sex' => $param['sex']];
        }

        $list = ActiveApplyModel::hasWhere('user', $sexWhere)->with('user')->where($where)->order('check_status asc')->select();
        $data = [];
        foreach ($list as $v) {
            $data[] = [
                'name'         => $v['user']['realname'],
                'sex'          => $v['user']['sex_text'],
                'age'          => Fun::getAgeByBirth($v['user']['birthday']),
                'mobile'       => $v['user']['mobile'],
                'company'      => $v['user']['company'],
                'native'       => $v['user']['native'],
                'marry'        => $v['user']['marry'],
                'check_status' => $v['status_text'],
            ];
        }

        if (empty($data)) {
            return '暂无数据';
        }

        $excel = new Excel();
        $title = [
            ['name', '姓名'],
            ['sex', '性别'],
            ['age', '年龄'],
            ['mobile', '电话'],
            ['company', '单位'],
            ['native', '籍贯'],
            ['marry', '婚姻状况'],
            ['check_status', '审核状态'],
        ];
        $excel->export('报名列表', $title, $data, ['mobile']);
    }

    public function exportoutlook()
    {
        $id       = $this->request->param('id');
        $outlook  = UserOutlookModel::all();
        $question = QuestionModel::all();
        $user_ids = $outlook->column('user_id');
        $user     = UserModel::where('id', 'in', $user_ids)->column('user_nickname,sex', 'id');
        $active   = ActiveApplyModel::where('active_id', $id)->column('user_no', 'user_id');

        if ($outlook->isEmpty()) {
            return '暂时无人填写三观';
        }

        //分出男女
        $outlook_man   = [];
        $outlook_woman = [];
        foreach ($outlook as $v) {
            if (empty($user[$v['user_id']])) {
                continue;
            }
            $v['user_nickname'] = $user[$v['user_id']]['user_nickname'];
            $v['sex']           = $user[$v['user_id']]['sex'];
            if ($v['sex'] == 1) {
                $outlook_man[] = $v;
            } else {
                $outlook_woman[] = $v;
            }
        }

        if (empty($outlook_man)) {
            return '暂无男生填写三观';
        }

        if (empty($outlook_woman)) {
            return '暂无女生填写三观';
        }

        $data    = [];
        $options = [1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D'];
        foreach ($outlook_man as $man) {
            foreach ($outlook_woman as $woman) {
                $item                   = [];
                $item['man_nickname']   = $man['user_nickname'];
                $item['man_no']         = isset($active[$man['user_id']]) ? $active[$man['user_id']] : '未报名';
                $item['woman_nickname'] = $woman['user_nickname'];
                $item['woman_no']       = isset($active[$woman['user_id']]) ? $active[$woman['user_id']] : '未报名';
                $item['match_num'] = $this->_matchOption($man, $woman);
                $item['match']     = $item['match_num'] . '0%';
                $item['title1']    = "男：" . $options[$man['question1']] . "，女：" . $options[$woman['question1']] . "。";
                $item['title2']    = "男：" . $options[$man['question2']] . "，女：" . $options[$woman['question2']] . "。";
                $item['title3']    = "男：" . $options[$man['question3']] . "，女：" . $options[$woman['question3']] . "。";
                $item['title4']    = "男：" . $options[$man['question4']] . "，女：" . $options[$woman['question4']] . "。";
                $item['title5']    = "男：" . $options[$man['question5']] . "，女：" . $options[$woman['question5']] . "。";
                $item['title6']    = "男：" . $options[$man['question6']] . "，女：" . $options[$woman['question6']] . "。";
                $item['title7']    = "男：" . $options[$man['question7']] . "，女：" . $options[$woman['question7']] . "。";
                $item['title8']    = "男：" . $options[$man['question8']] . "，女：" . $options[$woman['question8']] . "。";
                $item['title9']    = "男：" . $options[$man['question9']] . "，女：" . $options[$woman['question9']] . "。";
                $item['title10']   = "男：" . $options[$man['question10']] . "，女：" . $options[$woman['question10']] . "。";
                $data[]            = $item;
            }
        }
        usort($data, function ($a, $b) {
            return $b['match_num'] - $a['match_num']; // 倒序排列
        });

        //抬头
        $title1  = "题目：{$question[0]['title']}。选项：A.{$question[0]['option1']}。B.{$question[0]['option2']}。C.{$question[0]['option3']}。D.{$question[0]['option4']}。";
        $title2  = "题目：{$question[1]['title']}。选项：A.{$question[1]['option1']}。B.{$question[1]['option2']}。C.{$question[1]['option3']}。D.{$question[1]['option4']}。";
        $title3  = "题目：{$question[2]['title']}。选项：A.{$question[2]['option1']}。B.{$question[2]['option2']}。C.{$question[2]['option3']}。D.{$question[2]['option4']}。";
        $title4  = "题目：{$question[3]['title']}。选项：A.{$question[3]['option1']}。B.{$question[3]['option2']}。C.{$question[3]['option3']}。D.{$question[3]['option4']}。";
        $title5  = "题目：{$question[4]['title']}。选项：A.{$question[4]['option1']}。B.{$question[4]['option2']}。C.{$question[4]['option3']}。D.{$question[4]['option4']}。";
        $title6  = "题目：{$question[5]['title']}。选项：A.{$question[5]['option1']}。B.{$question[5]['option2']}。C.{$question[5]['option3']}。D.{$question[5]['option4']}。";
        $title7  = "题目：{$question[6]['title']}。选项：A.{$question[6]['option1']}。B.{$question[6]['option2']}。C.{$question[6]['option3']}。D.{$question[6]['option4']}。";
        $title8  = "题目：{$question[7]['title']}。选项：A.{$question[7]['option1']}。B.{$question[7]['option2']}。C.{$question[7]['option3']}。D.{$question[7]['option4']}。";
        $title9  = "题目：{$question[8]['title']}。选项：A.{$question[8]['option1']}。B.{$question[8]['option2']}。C.{$question[8]['option3']}。D.{$question[8]['option4']}。";
        $title10 = "题目：{$question[9]['title']}。选项：A.{$question[9]['option1']}。B.{$question[9]['option2']}。C.{$question[9]['option3']}。D.{$question[9]['option4']}。";

        $title = [
            ['man_nickname', '男生'],
            ['man_no', '男生编号'],
            ['woman_nickname', '女生编号'],
            ['woman_no', '女生编号'],
            ['match', '匹配度'],
            ['title1', $title1],
            ['title2', $title2],
            ['title3', $title3],
            ['title4', $title4],
            ['title5', $title5],
            ['title6', $title6],
            ['title7', $title7],
            ['title8', $title8],
            ['title9', $title9],
            ['title10', $title10],
        ];


        $excel = new Excel();
        $excel->export('三观匹配度', $title, $data);
    }

    public function exportOutlookCount()
    {
        $outlook  = UserOutlookModel::all();
        $user_ids = $outlook->column('user_id');
        $userById = UserModel::where('id','in',$user_ids)->column('sex','id');

        $data = [];
        $title = [];
        for ($i = 1; $i <= 10; $i++) {
            $title[] = ["man{$i}","男问题{$i}"];
            $title[] = ["woman{$i}","女问题{$i}"];
            $data["man{$i}"] = [1=>0,2=>0,3=>0,4=>0];
            $data["woman{$i}"] = [1=>0,2=>0,3=>0,4=>0];
        }

        foreach ($outlook as $v) {
            if (!empty($userById[$v['user_id']])) {
                $sex = $userById[$v['user_id']] == 1 ? 'man' : 'woman';
                for ($i = 1; $i <= 10; $i++) {
                    $data[$sex.$i][$v['question'.$i]]++;
                }
            }
        }
        $res = [];
        foreach ($data as $k => $v) {
            $res[$k] = "A:{$v[1]}，B:{$v[2]}，C:{$v[3]}，D:{$v[4]}";
        }
        
        $excel = new Excel();
        $excel->export('选项统计', $title, [$res]);
    }

    private function _matchOption($man, $woman)
    {
        $match_num = 0;
        for ($i = 1; $i <= 10; $i++) {
            if ($man['question' . $i] == $woman['question' . $i]) {
                $match_num++;
            }
        }
        return $match_num;
    }
}
