<?php

namespace app\admin\controller\School;

use app\BaseController;
use app\common\model\School\Student as ModelStudent;
use app\common\model\School\StudentService as ModelStudentService;
use app\common\model\Product\Product as ModelProduct;
use app\common\model\Product\ProductType as ModelProductType;
use app\common\model\Product\ProductParts as ModelProductParts;
use app\common\model\User\User as ModelUser;
use app\Request;
use app\common\arw\adjfut\src\Traverse;
use think\Validate;
use think\exception\ValidateException;
use think\facade\Filesystem;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;
use think\facade\Db;
use think\facade\Env;
use app\common\exception\Map;


class Student extends BaseController
{
    public function index()
    {
        return $user_guid = Request::getCurrentUser()->user_guid;

        $jwd = Map::getLongitudeAndLatitude("广东省佛山市顺德区容桂街道保利·德胜湾保利外滩一号");
        return $jwd;
        // return date('Y-m-d H:i:s', strtotime('+3 month'));
    }

    /**
     * 获取学生列表
     */
    public function getStudentList(Request $request)
    {
        $params = $request->param();
        $con = [];
        $conOr = [];

        if (isset($params['student_name']) && $params['student_name']) {
            $con[] = ['student_name', 'LIKE', '%' . $params['student_name'] . '%'];
        };
        if (isset($params['studnet_phone']) && $params['studnet_phone']) {
            $con[] = ['studnet_phone', 'LIKE', '%' . $params['studnet_phone'] . '%'];
        };
        if (isset($params['student_id_card']) && $params['student_id_card']) {
            $con[] = ['student_id_card', 'LIKE', '%' . $params['student_id_card'] . '%'];
        };
        if (isset($params['student_email']) && $params['student_email']) {
            $con[] = ['student_email', 'LIKE', '%' . $params['student_email'] . '%'];
        };
        if (isset($params['student_sex']) && $params['student_sex']) {
            $con[] = ['student_sex', '=', $params['student_sex']];
        };
        if (isset($params['student_membe_type']) && $params['student_membe_type']) {
            $con[] = ['student_membe_type', '=', $params['student_membe_type']];
        };
        if (isset($params['student_audit_status']) && $params['student_audit_status']) {
            $con[] = ['student_audit_status', '=', $params['student_audit_status']];
        };
        if (isset($params['product_type']) && $params['product_type']) {
            $con[] = ['a.product_type', '=', $params['product_type']];
            $conOr[] = ['c.product_type_parent_guid', '=', $params['product_type']];
        };
        if (isset($params['product_guid']) && $params['product_guid']) {
            $con[] = ['a.product_guid', '=', $params['product_guid']];
        };
        if (isset($params['product_parts_guid']) && $params['product_parts_guid']) {
            $con[] = ['a.product_parts_guid', '=', $params['product_parts_guid']];
        };
        if (isset($params['student_brithday']) && $params['student_brithday']) {
            $con[] = ['student_brithday', 'BETWEEN', implode(',', $params['student_brithday'])];
        };

        // return $con;

        $query = ModelStudent::alias('a')
            ->leftjoin('user b', 'a.user_guid = b.user_guid')
            ->leftjoin('product_type c', 'a.product_type = c.product_type_guid')
            ->leftjoin('product d', 'a.product_guid = d.product_guid')
            ->leftjoin('product_parts e', 'a.product_parts_guid = e.product_parts_guid')
            ->leftjoin('classes f', 'a.classes_guid = f.classes_guid')
            ->where($con)
            ->whereOr(function ($query) use ($conOr) {
                $query->whereOr($conOr);
            });

        if (isset($params['student_member_time']) && $params['student_member_time']) {
            $query->where("
                    (
                        student_member_begin_time >= '{$params['student_member_time'][0]}'
                        AND
                        student_member_begin_time <= '{$params['student_member_time'][1]}'
                    )
                    OR
                    (
                        student_member_end_time >= '{$params['student_member_time'][0]}'
                        AND
                        student_member_end_time <= '{$params['student_member_time'][1]}'
                    )
                    OR
                    (
                        student_member_begin_time >= '{$params['student_member_time'][0]}'
                        AND
                        student_member_end_time <= '{$params['student_member_time'][1]}'
                    )
                        ");
        }



        $select = self::pageWrapper($query)
            ->field([
                'a.student_id',
                'a.student_guid',
                'a.student_name',
                'a.user_guid',
                'b.user_name',
                'a.classes_guid',
                'f.classes_name',
                'a.studnet_phone',
                'a.student_id_card',
                'a.student_email',
                'a.student_sex',
                'a.student_price',
                'a.student_brithday',
                'a.product_type',
                'c.product_type_name',
                'a.product_guid',
                'd.product_name',
                'a.product_parts_guid',
                'e.product_parts_name',
                'a.student_img',
                'a.student_banner_img',
                'a.student_attachment',
                'a.student_intro',
                'a.student_location',
                'a.longitude',
                'a.latitude',
                'a.student_membe_type',
                'a.student_member_begin_time',
                'a.student_member_end_time',
                'a.student_audit_status',
                'a.student_audit_user_guid',
                "(SELECT `user`.`user_name` FROM `user` WHERE `user`.user_guid = `a`.`student_audit_user_guid`) as student_audit_user_name",
            ])
            ->append([
                'student_member_time',
                'student_service',
            ])
            ->order('student_update_time', 'desc')
            ->select();

        $count = $query->count();

        return [
            'code' => 0,
            'data' => $select,
            'count' => $count,
            'msg' => 'ok'
        ];
    }

    /**
     * 编辑学生
     */
    public function editStudent(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'student_name|学生名称' => 'require',
            'user_guid|用户' => 'require',
            'classes_guid|班级' => 'require',
            'studnet_phone|手机号' => 'require',
            'student_id_card|身份证号' => 'require',
            'student_sex|性别' => 'require',
            'student_price|学生价格' => 'require',
            'product_type|产品类型' => 'require',
            'product_guid|产品' => 'require',
            'product_parts_guid|产品零件' => 'require',
            'student_img|头像' => 'require',
            'student_intro|简介' => 'require',
            'student_location|家庭住址' => 'require',
            'longitude|经度' => 'require',
            'latitude|纬度' => 'require'
        ]);
        $model = ModelStudent::where('student_guid', $params['student_guid'])->find();
        if (!$model) throwErrorMsg("该学生不存在", 1);


        $student_member_time = $params['student_member_time'];
        $params['student_member_begin_time'] = $student_member_time[0];
        $params['student_member_end_time'] = $student_member_time[1];

        // return $params;


        $model->allowField([
            'student_update_user_guid',
            'student_name',
            'user_guid',
            'classes_guid',
            'studnet_phone',
            'student_id_card',
            'student_email',
            'student_sex',
            'student_price',
            'student_brithday',
            'product_type',
            'product_guid',
            'product_parts_guid',
            'student_img',
            'student_banner_img',
            'student_attachment',
            'student_intro',
            'student_location',
            'longitude',
            'latitude',
            'student_membe_type',
            'student_member_begin_time',
            'student_member_end_time',
            'student_audit_status',
            'student_audit_user_guid'
        ])->save($params);

        // 学生服务编辑
        ModelStudent::editStudentService($params);

        return [
            'code' => 0,
            'msg' => '编辑成功'
        ];
    }

    /**
     * 添加学生
     */
    public function addStudent(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'student_name|学生名称' => 'require',
            'user_name|用户' => 'require',
            'classes_guid|班级' => 'require',
            'studnet_phone|手机号' => 'require',
            'student_id_card|身份证号' => 'require',
            'student_sex|性别' => 'require',
            'student_price|学生价格' => 'require',
            'product_type|产品类型' => 'require',
            'product_guid|产品' => 'require',
            'product_parts_guid|产品零件' => 'require',
            'student_img|头像' => 'require',
            'student_intro|简介' => 'require',
            'student_location|家庭住址' => 'require',
            'longitude|经度' => 'require',
            'latitude|纬度' => 'require',
            'student_membe_type|会员类型' => 'require',
        ]);

        $params = ModelStudent::initAdd($params);

        $model = ModelStudent::create($params, [
            'student_guid',
            'student_create_user_guid',
            'student_update_user_guid',
            'student_name',
            'user_guid',
            'classes_guid',
            'studnet_phone',
            'student_id_card',
            'student_email',
            'student_sex',
            'student_price',
            'student_brithday',
            'product_type',
            'product_guid',
            'product_parts_guid',
            'student_img',
            'student_banner_img',
            'student_attachment',
            'student_intro',
            'student_location',
            'longitude',
            'latitude',
            'student_membe_type',
            'student_member_begin_time',
            'student_member_end_time',
            'student_audit_status',
            'student_audit_user_guid'
        ]);

        if (!$model) throwErrorMsg("添加失败");
        $student_guid = $model->student_guid;

        // 添加学生服务
        ModelStudent::addStudentService($student_guid, $params);

        return [
            'code' => 0,
            'msg' => '添加成功'
        ];
    }

    /**
     * 删除学生
     */
    public function deleteStudent(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'student_guid' => 'require',
        ]);
        $student = ModelStudent::where([
            'student_guid' => explode(',', $params['student_guid'])
        ])->select();
        $student->delete();

        // 从学生服务(副表)查询出所有当前学生的服务，进行删除
        ModelStudentService::where('student_guid', $params['student_guid'])->select()->delete();

        return [
            'code' => 0,
            'msg' => "删除成功"
        ];
    }

    /**
     * 查找未绑定用户列表
     */
    public function notBindUserList(Request $request)
    {
        $user = $request->param('user');
        $con = [
            'user_status' => 1,
        ];
        $search = [];
        if ($user) {
            $search['user_name'] = $user;
        }

        $query = ModelUser::alias('a')
            ->join('student b', 'a.user_guid != b.user_guid')
            ->withSearch(array_keys($search), $search)->where($con)
            ->whereNotExists(function ($query) {
                $query->table('student')->alias('b')->where("a.user_guid = b.user_guid");
            });
        $select =  self::pageWrapper($query)->field([
            'a.user_name',
        ])
            ->group('user.user_guid')->order([
                'user.user_update_time' => 'desc'
            ])->select();
        $count =  $query->count();
        return [
            'code' => 0,
            'data' => $select,
            'count' => $count,
            'msg' => 'ok'
        ];
    }

    /**
     * 审核学生
     */
    public function auditStudent(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'student_guid|学生guid' => 'require',
            'student_audit_status|审核状态' => 'require|in:2,3',
        ]);

        ModelStudent::auditStudent($params);

        return [
            'code' => 0,
            'msg' => '审核成功'
        ];
    }

    /**
     * 导出Excel
     */
    public function exportExcel(Request $request)
    {
        $params = $request->param();
        return ModelStudent::exportStudent();
    }

    /**
     * 下载导入模板
     */
    public function downloadTemplate(Request $request)
    {
        $params = $request->param();
        $data = [
            ['学生名称', '用户', '班级', '手机号', '身份证号', '邮箱', '性别', '学生价格', '生日', '产品类型', '产品', '产品零件', '头像', '轮播图片', '简介', '家庭住址', '会员类型',]
        ];

        $data[] = ['张思', '负责人', '网络3+2', '19882556281', '110223790813697', '2679599887@163.com', '男', '99.99', '2023-02-19', '小米10', '小米10代手机 全面屏 3亿像素', '小米专属钢化膜', 'https://hjczx.net/intelligent_clique/public/uploads/hjczx//student_img/2022/459/210744-compression.jpg', 'http://aerwen.net/prod-api/student/20230218/C9B76FC1E616EE6A.jpg,http://aerwen.net/prod-api/key/20230217/628A9C1A391ABD61.jpg', '我是三好学生', '广东省佛山市顺德区容桂街道胡锦超职业技术学校', '季卡'];
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('学生导入模板.xlsx');
    }

    /**
     * 导入excel
     */
    public function importExcel(Request $request)
    {
        $file = new UploadFile('uploads', 'fileExt:xlsx');
        $file->putFile('student');

        $msg = ModelStudent::ImportStudent($file);
        return [
            'code' => 0,
            'msg' => $msg
        ];
    }


    /**
     * 获取点击后的产品列表
     */
    public function getClickProduct(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'product_type_guid|产品类型' => 'require',
        ]);

        $product_type_guid = $params['product_type_guid'];

        $products = ModelProduct::alias('a')
            ->leftjoin('product_type b', "a.product_type_guid = b.product_type_guid")
            ->where("a.product_type_guid = '$product_type_guid' or b.product_type_parent_guid = '$product_type_guid'")->select();
        return [
            'code' => 0,
            'data' => $products,
            'msg' => "获取点击后的产品列表成功"
        ];
    }

    /**
     * 获取点击后的产品零件列表
     */
    public function getClickProductParts(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'product_guid|产品' => 'require',
        ]);

        $products_parts = ModelProductParts::where('product_guid', $params['product_guid'])->select();
        return [
            'code' => 0,
            'data' => $products_parts,
            'msg' => "获取点击后的产品零件列表成功"
        ];
    }


    /**
     * 获取侧边产品数据
     */
    public function getProductTree(): array
    {
        $data = [];
        $product_types = ModelProductType::field([
            'product_type_name',
            'product_type_guid',
            'product_type_parent_guid',
        ])->select();
        foreach ($product_types as $key => $value) {
            $product_type_guid = $value['product_type_guid'];
            $product_type_parent_guid = $value['product_type_parent_guid'];
            $data[] = [
                'id' => $product_type_guid,
                'parent_id' => $product_type_parent_guid,
                'name' => $value['product_type_name'],
                'type' => 'product_type',
                'data' => [
                    'parent_id' => $product_type_parent_guid,
                    'product_type_guid' => $value['product_type_guid']
                ],
            ];
        }
        $products = ModelProduct::field([
            'product_name',
            'product_guid',
            'product_type_guid',
        ])->select();
        foreach ($products as $value) {
            $product_guid = $value['product_guid'];
            $product_type_guid = $value['product_type_guid'];
            $id = $product_guid;
            $data[] = [
                'id' => $id,
                'parent_id' => $product_type_guid,
                'name' => $value['product_name'],
                'type' => 'product',
                'data' => [
                    'product_type_guid' => $product_type_guid,
                    'product_guid' => $product_guid
                ],
            ];

            $product_parts = ModelProductParts::field([
                'product_parts_name',
                'product_parts_guid',
                'product_guid',
            ])->where('product_guid', $product_guid)->select();
            foreach ($product_parts as $value) {
                $product_parts_guid = $value['product_parts_guid'];
                $product_guid = $value['product_guid'];
                $id = $product_parts_guid;
                $data[] = [
                    'id' => $id,
                    'parent_id' => $product_guid,
                    'name' => $value['product_parts_name'],
                    'type' => 'product_parts',
                    'data' => [
                        'product_type_guid' => $product_type_guid,
                        'product_guid' => $product_guid,
                        'product_parts_guid' => $product_parts_guid
                    ],
                ];
            }
        }
        // return $data;
        $Traverse = new Traverse('id', 'parent_id');
        return $Traverse->tree($data, '0', function (array $value) {
            return $value;
        });
        return [
            'code' => 0,
            'data' => $data,
            'msg' => 'ok'
        ];
    }
}
