<?php

namespace app\matchmaker\controller;

use app\common\Constant;
use app\matchmaker\model\MatchmakerModel;
use app\matchmaker\model\MatchmakerUserMatingModel;
use app\matchmaker\model\MatchmakerUserModel;
use cmf\controller\HomeBaseController;

class RegisterController extends HomeBaseController
{
    /**
     * 用户登记
     */
    public function infoAdd()
    {
        $id = $this->request->get('id', 0);
        if (empty($id)) {
            $this->error('参数错误');
        }
        $matchmaker = MatchmakerModel::get($id);
        if (empty($matchmaker)) {
            $this->error('红娘不存在');
        }
        $data = [
            'sex'       => Constant::SEX_MATCHMAKER,
            '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,
            'animal'    => Constant::ANIMAL,
        ];
        foreach ($data as &$v) {
            $v = json_encode($v);
            unset($v);
        }
        $data['id'] = $id;

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

    public function infoAddPost()
    {
        $value             = $this->request->post();
        $value['birthday'] = strtotime($value['birthday']);
        $check             = MatchmakerUserModel::get(['mobile' => $value['mobile']]);
        if (!empty($check)) {
            $this->error('您已填写过，请不要重复填写');
        }
        $user = MatchmakerUserModel::create($value);
        MatchmakerUserMatingModel::create(['user_id' => $user['id'], 'animal' => []]);
        $this->success('', '', ['id' => $user['id']]);
    }

    public function matingAdd()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $mating = MatchmakerUserMatingModel::get(['user_id' => $id]);
        if (empty($mating['animal'])) {
            $mating['animal'] = [];
        }
        $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::MATTING_SMOKING,
            'drink'      => Constant::MATTING_DRINK,
            'tinyint'    => Constant::COND_TINYINT,
            'animal'     => Constant::ANIMAL,
        ];
        foreach ($data as &$v) {
            $v = json_encode($v);
            unset($v);
        }

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

    public function matingAddPost()
    {
        $param = $this->request->post();
        if (empty($param['animal'])) {
            $param['animal'] = [];
        }
        MatchmakerUserMatingModel::update($param);
        $this->success('操作成功');
    }

    public function info()
    {
        return view();
    }

    /**
     * 图片上传
     */
    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('上传失败，请重新上传');
            }

            $avatar = cmf_get_user_avatar_url('image' . '/' . date('Ymd') . '/' . $file_name);

            $this->result([
                'avatar' => $avatar,
            ], 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;
        }
    }

}
