<?php

namespace app\api\controller\v1;

use app\api\ApiController;
use think\facade\Db;

// use app\api\validate\User as UserValidate;
// use think\exception\ValidateException;
use app\common\lib\Token;

class User extends ApiController
{
    public function getInfo()
    {
        try {
            $user = Db::name('user')
                ->field('user_id,avatar,line_id,line_name,line_picture,phone,real_name,email, code,parent_id')
                ->where('user_id', input('user_id'))
                // ->whereNotNull('delete_time')
                ->find();

            return $this->success($user);
        } catch (\Exception $e) {
            return $this->error('操作失敗');
        }
    }

    public function getUsers()
    {
        try {
            $users = Db::name('user')
                ->field('user_id,avatar,line_id,line_name,line_picture,phone,real_name,code')
                ->whereNotNull('delete_time')
                ->select();

            return $this->success($users);
        } catch (\Exception $e) {
            return $this->error('操作失敗');
        }
    }


    public function add()
    {

        $data = input();

        unset($data['version']);
        unset($data['action']);
        unset($data['controller']);


        $user_id = genUniqid($data['appid']);

        $data['user_id'] = $user_id;

        $avatar = isset($data['line_picture']) ? $this->saveLineImage($data['line_picture'], $data['user_id']) : '';

        if (!empty($avatar)) {
            $data['line_picture'] = getUrl() . '/storage/' . $data['user_id'] . '/' . $avatar;
        } else {
            $data['line_picture'] = '';
        }

        if (!isset($data['avatar'])) {
            $data['avatar'] = $data['line_picture'];
        } else {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . '/storage/' . $data['user_id'] . '/' . date('Ymd') . '/';
            if (!is_dir($file_path)) {
                mkdir($file_path, 0777, true);
            }
            $temp_file = str_replace(getUrl(), "", $data['avatar']);
            $avatar_file = $file_path . basename($temp_file);
            if (!rename($_SERVER['DOCUMENT_ROOT'] . $temp_file, $avatar_file)) {
                return $this->error('搬移檔案失敗');
            }
            $data['avatar'] = getUrl() . '/storage/' . $data['user_id'] . '/' . date('Ymd') . '/' . basename($temp_file);
        }

        $phone_exist = Db::name('user')
            ->where('phone', input('phone'))
            ->find();

        // 檢查會員電話是否存在
        if (!$phone_exist) {
            // 檢查推薦碼是否存在,存在的話取得推薦人的id
            if (input('refer_code')) {
                $refer_id = Db::name('user')
                    ->where('code', input('refer_code'))
                    ->value('user_id');

                if ($refer_id) {
                    $data['parent_id'] = $refer_id;
                }
            }
        }

        unset($data['appid']);
        unset($data['timestamp']);
        unset($data['sign']);
        unset($data['refer_code']);

        try {
            if ($phone_exist) {
                Db::name('user')
                    ->where('phone', input('phone'))
                    ->update($data);
            } else {
                $id = Db::name('user')
                    ->insertGetId($data);

                $refer_code = encodeRefer($id);

                Db::name('user')
                    ->where('id', $id)
                    ->update(['code' => $refer_code]);
            }



            //使用id取得user資料庫的資料
            $result = Db::name('user')
                ->where('phone', input('phone'))
                ->find();

            $payload = [
                'user_id' => $data['user_id'],
            ];

            $token = Token::genToken($payload);

            return $this->success(['uid' => $data['user_id'], 'info' => $result, 'token' => 'Bearer ' . $token]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function delete()
    {
        try {
            Db::name('user')
                ->where('user_id', input('user_id'))
                ->update([
                    'delete_time' => time()
                ]);
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->error('操作失敗');
        }
    }

    public function update()
    {
        $data = input('post.');

        unset($data['appid']);
        unset($data['timestamp']);
        unset($data['sign']);

        try {
            Db::name('user')
                ->where('user_id', $data['user_id'])
                ->update($data);

            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->error('操作失敗');
        }
    }

    private function saveLineImage($pictureUrl, $uid)
    {
        if ($pictureUrl) {
            $curl = curl_init($pictureUrl);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $imageData = curl_exec($curl);
            curl_close($curl);

            $filename = $uid . "_line.jpg";
            $filedir = $_SERVER['DOCUMENT_ROOT'] . '/storage/' . $uid;
            if (!file_exists($filedir)) {
                mkdir($filedir, 0777, true);
            }
            $fp = fopen($filedir . '/' . $filename, 'a');
            fwrite($fp, $imageData);
            fclose($fp);

            return $filename;
        } else {
            return false;
        }
    }
}
