<?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: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\love\controller;

use app\common\Constant;
use app\common\Fun;
use app\common\Wechat;
use app\love\model\ActiveModel;
use app\love\model\UserAuthModel;
use app\love\model\UserMatingModel;
use app\love\model\UserModel;
use cmf\controller\HomeBaseController;
use think\facade\Request;

class RegisterController extends HomeBaseController
{
    public function initialize()
    {
        parent::initialize();

        /*$user_id = cmf_get_current_user_id();
        if (!empty($user_id)) {
            $user = UserModel::get($user_id);
            if ($user['user_status'] > 0 && $user['is_complete'] == 1) {
                $this->redirect(url('/'));
            }
        }*/

        //分享页面
        $wx_api_sign = Wechat::instance()->getJsSign(Request::url(true));
        $this->assign('domain', $this->request->domain());
        $this->assign('wx_api_sign', json_encode($wx_api_sign));
    }

    /**
     * 禁用
     */
    public function ban()
    {
        return $this->fetch();
    }

    public function marry()
    {
        return $this->fetch();
    }

    public function audit()
    {
        return $this->fetch();
    }

    public function idcard()
    {
        $user = UserModel::get(cmf_get_current_user_id());
        if ($this->request->isPost()) {
            $idcard = $this->request->post('idcard');
            if (empty($idcard)) {
                $this->error('请输入身份证号');
            }

            $auth = UserAuthModel::where('idcard', $idcard)->find();
            if (empty($auth)) {
                $this->error('抱歉，您不在注册列表中，如需注册请联系妇联');
            }

            $user->realname     = $auth['name'];
            $user->idcard       = $auth['idcard'];
            $user->mobile       = $auth['mobile'];
            $user->company      = $auth['company'];
            $user->company      = $auth['company'];
            $user->marry        = $auth['marry'];
            $user->sex          = Fun::getSexByIdCard($auth['idcard']);
            $user->birthday     = strtotime(Fun::getBirthDayByIdCard($auth['idcard']));
            $user->check_status = 2;
            $user->create_time  = time();
            $user->save();

            $this->success('操作成功');
        } else {
            if (!empty($user['idcard'])) {
                $this->redirect(url('intro'));
            }
            return $this->fetch();
        }
    }

    /**
     * 活动说明
     */
    public function active()
    {
        $id                   = $this->request->param('id', 0);
        $active               = ActiveModel::get($id);
        $active['start_time'] = date('m-d', $active['start_time']);
        $active['end_time']   = date('m-d', $active['end_time']);
        $active['main_image'] = cmf_get_image_preview_url($active['main_image']);
        $this->assign('active', $active);

        return $this->fetch();
    }

    /**
     * 性别
     */
    public function sex()
    {
        $user = UserModel::get(cmf_get_current_user_id());
        if ($this->request->isPost()) {
            $value = $this->request->post('sex');
            if (empty($user['sex'])) {
                $user->sex = $value;
                $user->save();
            }
            $this->success('');
        } else {
            if (!empty($user['sex'])) {
                $this->redirect(url('intro'));
            }
            return $this->fetch();
        }
    }

    /**
     * 部门
     */
    public function department()
    {
        $user = UserModel::get(cmf_get_current_user_id());
        if ($this->request->isPost()) {
            $value = $this->request->post('department');
            if (empty($user['department'])) {
                $user->department = $value;
                $user->save();
            }
            $this->success('');
        } else {
            $this->assign('department', Constant::DEPARTMENT);
            return $this->fetch();
        }
    }

    /**
     * 头像
     */
    public function intro()
    {
        if ($this->request->isPost()) {
            $value           = $this->request->post();
            $value['avatar'] = $value['main_image_thumb'];
            UserModel::update($value, ['id' => cmf_get_current_user_id()], ['avatar', 'main_image', 'main_image_thumb', 'signature']);
            $this->success('');
        } else {
            $user = UserModel::get(cmf_get_current_user_id());
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    /**
     * 健康码
     */
    public function healthCode()
    {
        if ($this->request->isPost()) {
            $value = $this->request->post();
            UserModel::update($value, ['id' => cmf_get_current_user_id()], ['health_code']);
            $this->success('');
        } else {
            $user = UserModel::get(cmf_get_current_user_id());
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    /**
     * 个人资料
     */
    public function profile()
    {
        if ($this->request->isPost()) {
            $value                  = $this->request->post();
            $value['user_nickname'] = $value['realname'];
            $value['birthday']      = strtotime($value['birthday']);
            UserModel::update($value, ['id' => cmf_get_current_user_id()]);
            $this->success('');
        } else {
            $user             = UserModel::get(cmf_get_current_user_id());
            $user['birthday'] = date('Y-m-d', $user['birthday']);
            unset($user['user_pass']);
            $this->assign('user', json_encode($user));

            $data = [
                'marry'     => Constant::MARRY,
                'high'      => Constant::HIGH,
                'weight'    => Constant::WEIGHT,
                'education' => Constant::EDUCATION,
                'income'    => Constant::INCOME,
                'nation'    => Constant::NATION,
                'smoke'     => Constant::SMOKE,
                'drink'     => Constant::DRINK,
                'family'    => Constant::FAMILY,
                'tinyint'   => Constant::TINYINT,
            ];
            foreach ($data as &$v) {
                $v = json_encode($v);
                unset($v);
            }

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

    /**
     * 择偶要求
     */
    public function cond()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            UserMatingModel::update($param, ['user_id' => cmf_get_current_user_id()]);
            UserModel::update(['is_complete' => 1, 'id' => cmf_get_current_user_id()]);
            $user = UserModel::get(cmf_get_current_user_id());
            session('user', $user->toArray());
            $this->success('操作成功');
        } else {
            $mating = UserMatingModel::get(['user_id' => cmf_get_current_user_id()]);
            $this->assign('mating', $mating);

            $education   = Constant::EDUCATION;
            $education[] = '无要求';
            $data        = [
                'min_age'    => Constant::MIN_AGE,
                'max_age'    => Constant::MAX_AGE,
                'min_high'   => Constant::MIN_HIGH,
                'max_high'   => Constant::MAX_HIGH,
                'min_weight' => Constant::MIN_WEIGHT,
                'max_weight' => Constant::MAX_WEIGHT,
                'native'     => Constant::NATIVE,
                'education'  => $education,
                'income'     => Constant::COND_INCOME,
                'smoke'      => Constant::SMOKE,
                'drink'      => Constant::DRINK,
                'tinyint'    => Constant::COND_TINYINT,
            ];
            foreach ($data as &$v) {
                $v = json_encode($v);
                unset($v);
            }

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

//    public function t1()
//    {
//        $auth = UserAuthModel::all();
//        $num = 0;
//        foreach ($auth as $v) {
//            $birth = strtotime(Fun::getBirthDayByIdCard($v['idcard']));
//            $check = UserModel::where('mobile',$v['mobile'])->find();
//            if (!empty($check) && $check->birthday != $birth) {
//                $check->birthday = $birth;
//                $check->save();
//                $num++;
//            }
//        }
//
//        return $num;
//    }

    /**
     * 健康码上传
     */
    public function codeUpload()
    {
        $file = $this->request->post('file');
        $ext  = pathinfo($this->request->post('name'))['extension'];
        if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
            $this->error('文件后缀必须为jpg，jpeg，png');
        }

        if ($file) {
            //创建目录
            $upload_dir = WEB_ROOT . 'upload/health_code';
            if (!is_dir($upload_dir)) {
                @mkdir($upload_dir);
            }
            $upload_dir = $upload_dir . '/' . date('Ymd');
            if (!is_dir($upload_dir)) {
                @mkdir($upload_dir);
            }

            //保存文件
            $file_name = $this->_file_name($ext);
            $file_path = $upload_dir . '/' . $file_name;
            $is_upload = $this->_base64_image_content($file, $file_path);
            if (!$is_upload) {
                $this->error('上传失败，请重新上传');
            }
            $main_image = cmf_get_user_avatar_url('health_code' . '/' . date('Ymd') . '/' . $file_name);

            $this->result([
                'health_code' => cmf_get_user_avatar_url($main_image),
            ], 1);
        } else {
            $this->error('请上传文件');
        }
    }

    /**
     * 图片上传
     */
    public function imageUpload()
    {
        $file = $this->request->post('file');
        $ext  = pathinfo($this->request->post('name'))['extension'];
        if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
            $this->error('文件后缀必须为jpg，jpeg，png');
        }

        if ($file) {
            //创建目录
            $upload_dir = WEB_ROOT . 'upload/image';
            if (!is_dir($upload_dir)) {
                @mkdir($upload_dir);
            }
            $upload_dir = $upload_dir . '/' . date('Ymd');
            if (!is_dir($upload_dir)) {
                @mkdir($upload_dir);
            }

            //保存文件
            $file_name = $this->_file_name($ext);
            $file_path = $upload_dir . '/' . $file_name;
            $is_upload = $this->_base64_image_content($file, $file_path);
            if (!$is_upload) {
                $this->error('上传失败，请重新上传');
            }

            //缩略图
            $thumb_file = $this->_file_name($ext);
            $image      = \think\Image::open($file_path);
            $image->thumb(220, 270)->save($upload_dir . '/' . $thumb_file);

            $main_image       = cmf_get_user_avatar_url('image' . '/' . date('Ymd') . '/' . $file_name);
            $main_image_thumb = cmf_get_user_avatar_url('image' . '/' . date('Ymd') . '/' . $thumb_file);

            $this->result([
                'main_image'       => $main_image,
                'main_image_thumb' => $main_image_thumb,
            ], 1);
        } else {
            $this->error('请上传文件');
        }
    }

    private function _file_name($ext)
    {
        //生成随机文件名
        //定义一个包含大小写字母数字的字符串
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        //把字符串分割成数组
        $newchars = str_split($chars);
        //打乱数组
        shuffle($newchars);
        //从数组中随机取出15个字符
        $chars_key = array_rand($newchars, 15);
        //把取出的字符重新组成字符串
        $fnstr = '';
        for ($i = 0; $i < 15; $i++) {
            $fnstr .= $newchars[$chars_key[$i]];
        }
        //输出文件名并做MD5加密
        return md5($fnstr . microtime(true) * 1000) . '.' . $ext;
    }

    private function _base64_image_content($base64_image_content, $file_path)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            if (file_put_contents($file_path, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
