<?php

namespace app\api\controller\manage;

use app\api\middleware\Auth;
use app\api\service\UtilService;
use app\api\validate\StudentValidate;
use app\BaseController;
use app\model\Student as StudentModel;
use app\Request;
use think\facade\Db;
use app\model\project\User;
use app\event\PhpOffice;
use OSS\OssClient;

class Student extends BaseController
{

    protected $middleware = [
        Auth::class,
    ];


    //添加学生
    public function createStudent(Request $request)
    {
        $vo = (new StudentValidate())->goCheck(['realname', 'sex', 'age', 'idcard', 'mobile', 'xq', 'nj', 'bj', 'xh']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        Db::startTrans();
        try {
            $user_id = $this->createuser($parm);
            $parm['birthday'] = strtotime($parm['birthday']);
            $parm['school_user_id'] = $request->userId;
            $parm['user_id'] = $user_id;
            $result = StudentModel::create($parm);
            Db::commit();
            return $this->returnMsg('操作成功', 1, $result);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnMsg($e->getMessage());
        }
    }

    //创建用户
    public function createuser($parm)
    {
        $userinfo = User::where('mobile', $parm['mobile'])->where('is_del', 0)->field('id')->find();
        if ($userinfo) {
            //学生已注册进行绑定
            $user_id = $userinfo->id;
            $userinfo->school_user_id = \request()->userId;
            $userinfo->save();
        } else {
            //学生未注册添加一条用户记录
            $salt = random(4);
            $password = md5(substr($parm['mobile'], 5, 6) . $salt);
            $datauser = [
                'realname' => $parm['realname'],
                'username' => $parm['realname'],
                'mobile' => $parm['mobile'],
                'sex' => $parm['sex'],
                'reg_time' => time(),
                'password' => $password,
                'salt' => $salt,
                'school_user_id' => \request()->userId,
            ];
            $userinfo = User::create($datauser);
            $user_id = $userinfo->id;
        }

        return $user_id;
    }

    //编辑学生
    public function updateStudent(Request $request)
    {

        $vo = (new StudentValidate())->goCheck(['student_id', 'realname', 'sex', 'age', 'birthday', 'idcard', 'xq', 'nj', 'bj', 'xh']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        $updatedata = $parm;
        unset($updatedata['student_id']);
        if (isset($updatedata['mobile'])) unset($updatedata['mobile']);
        $result = StudentModel::update($updatedata, ['id' => $parm['student_id']]);
        return $this->returnMsg('操作成功', 1, $result);
    }

    //学生列表
    public function studentList(Request $request)
    {

        $parm = $request->param();
        $where = ['school_user_id' => $request->userId];
        $map = [];
        if (isset($parm['searchrealname']) && $parm['searchrealname']) {
            $map[] = ['realname|mobile', 'like', '%' . $parm['searchrealname'] . '%'];
        }
        $page = $request->param('page', 1);
        $pageSize = $request->param('pageSize', 10);
        $list = StudentModel::where($where)->where($map)
            ->order('createtime desc')
            ->append(['sex_text', 'birthday_text'])
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize
            ]);
        return $this->returnMsg('success', 1, $list);
    }

    //学生详情
    public function studentDetail(Request $request)
    {

        $vo = (new StudentValidate())->goCheck(['student_id']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        $info = StudentModel::with(['userprofile'])->find($parm['student_id'])->append(['sex_text', 'birthday_text']);
        return $this->returnMsg('success', 1, $info);
    }

    //删除学生
    public function StudentDelete(Request $request)
    {
        $vo = (new StudentValidate())->goCheck(['student_id']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        $student_id = is_array($parm['student_id']) ? $parm['student_id'] : explode(',', $parm['student_id']);
        $result = StudentModel::destroy($student_id);
        return $this->returnMsg('success', 1, $result);
    }

    //导入学生
    public function StudentExcel11(Request $request)
    {
        set_time_limit(0); // 无时间限制
        ini_set('memory_limit', '512M');
        $vo = (new StudentValidate())->goCheck(['file_id']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        $checkfiled = ['realname', 'sex', 'age', 'idcard', 'mobile', 'xq', 'nj', 'bj', 'xh'];
        try {
            $fileinfo = get_upload_file($parm['file_id'], 'info');
            $filePath = $fileinfo['fileurl'];
            $filepath = '.' . strstr($filePath, '/static/');
            if (!file_exists($filepath)) {
                throw new \Exception("文件不存在: " . $filePath);
            }
            $list = PhpOffice::importexcel($filepath);
            if (empty($list)) {
                throw new \Exception("文件数据空 ");
            }
            $datalin = [];
            foreach ($list[0] as $k => $item) {
                $thisitem = trim($item);
                $datalin = StudentModel::excelfiled($thisitem, $k, $datalin);

            }
            unset($list[0]);
            $createdata = [];
            $sv = new StudentValidate();
            foreach ($list as $vo) {

                $savedata = array();
                foreach ($datalin as $ks => $linval) {
                    if ($ks == 'birthday') {
                        $savedata[$ks] = strtotime(trim($vo[$linval]));
                    } else {
                        $savedata[$ks] = trim($vo[$linval]);
                    }
                }
                //验证数据
                $vo = $sv->goCheck($checkfiled, $savedata);
                if ($vo !== true) {
                    throw new \Exception($sv->getError());
                }
                $user_id = $this->createuser($savedata);
                $savedata['school_user_id'] = $request->userId;
                $savedata['user_id'] = $user_id;
                $createdata[] = $savedata;
            }
            StudentModel::saveAll($createdata);
            return $this->returnMsg('导入成功', 1);
        } catch (\Exception $e) {

            return $this->returnMsg($e->getMessage());
        }

    }

    //导入学生
    public function StudentExcel(Request $request)
    {

        set_time_limit(0); // 无时间限制
        ini_set('memory_limit', '512M');
        $vo = (new StudentValidate())->goCheck(['file_id']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();

        $checkfiled = ['realname', 'sex', 'age', 'idcard', 'mobile', 'xq', 'nj', 'bj', 'xh'];
        try {
            $fileinfo = get_upload_file($parm['file_id'], 'info');
            $filepath = $fileinfo['fileurl'];

            if ($fileinfo['storage'] == 'aliyun') {
                $filepath = PhpOffice::ossdowntem($filepath);
            } else {
                $filepath = '.' . strstr($filepath, '/static/');
                if (!file_exists($filepath)) {
                    throw new \Exception("文件不存在: " . $filepath);
                }
            }

            $school_user_id = \request()->userId;
            PhpOffice::chunkedImportXlsx($filepath, function ($list, $startRow, $endRow) use ($checkfiled, $school_user_id) {
//                echo "处理行 {$startRow} 到 {$endRow}" . PHP_EOL;

                $datalin = [];
                foreach ($list[0] as $k => $item) {
                    $thisitem = trim($item);
                    $datalin = StudentModel::excelfiled($thisitem, $k, $datalin);

                }
                unset($list[0]);
                $createdata = [];
                $sv = new StudentValidate();
                foreach ($list as $vo) {

                    $savedata = array();
                    foreach ($datalin as $ks => $linval) {
                        if ($ks == 'birthday') {
                            $savedata[$ks] = strtotime(trim($vo[$linval]));
                        } else {
                            $savedata[$ks] = trim($vo[$linval]);
                        }
                    }
                    //验证数据
                    $vo = $sv->goCheck($checkfiled, $savedata);
                    if ($vo !== true) {
                        throw new \Exception($sv->getError());
                    }
                    $user_id = $this->createuser($savedata);
                    $savedata['school_user_id'] = $school_user_id;
                    $savedata['user_id'] = $user_id;
                    $createdata[] = $savedata;
                }
                StudentModel::saveAll($createdata);
            });
            if ($fileinfo['storage'] == 'aliyun') {
                // 处理完成后删除临时文件
                if (file_exists($filepath)) {
                    unlink($filepath);
                }
            }
            return $this->returnMsg('导入成功', 1);
        } catch (\Exception $e) {

            return $this->returnMsg($e->getMessage());
        }

    }
}