<?php
/**
 * *
 *  * ============================================================================
 *  * Created by PhpStorm.
 *  * User: Ice
 *  * 邮箱: ice@sbing.vip
 *  * 网址: https://sbing.vip
 *  * Date: 2019/9/19 下午3:33
 *  * ============================================================================.
 */

namespace app\api\controller;

use app\api\BaseController;
use app\api\middleware\Auth;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Config;
use app\common\model\Area;
use app\common\model\Version;
use app\common\model\Attachment;
use think\facade\Db;
use think\facade\Env;
use think\facade\Event;

/**
 * 公共接口.
 */
class Common extends BaseController
{

    /**
     * 控制器中间件 [不需要鉴权]
     * @var array
     */
    protected $middleware = [
        Auth::class => ['except' 	=> ['init','category','categorys','upload','get_area','get_street','get_village','idcard','get_all_category','get_all_category_health','get_brigade'] ]
    ];
    /**
     * 加载初始化.
     *
     * @param  string  $version  版本号
     * @param  string  $lng  经度
     * @param  string  $lat  纬度
     */
    public function init()
    {
        if ($version = get_params('version')) {
            $lng = get_params('lng');
            $lat = get_params('lat');
            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => Config::get('upload'),
                'coverdata'   => Config::get('cover'),
            ];
            $this->apiSuccess('', $content);
        } else {
            $this->apiError('参数不正确');
        }
    }

//    /**
//     * 上传文件.
//     * @ApiMethod (POST)
//     *
//     * @param  File  $file  文件流
//     */
//    public function upload()
//    {
//        $file = $this->request->file('file');
//        if (empty($file)) {
//            $this->apiError('未上传文件或超出服务器上传限制');
//        }
//
//        //判断是否已经存在附件
//        $sha1 = $file->hash();
//
//        $upload = Config::get('upload');
//
//        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
//        $type = strtolower($matches[2]);
//        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
//        $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
//        $fileInfo['name'] = $file->getOriginalName(); //上传文件名
//        $fileInfo['type'] = $file->getOriginalMime(); //上传文件类型信息
//        $fileInfo['tmp_name'] = $file->getPathname();
//        $fileInfo['size'] = $file->getSize();
//        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
//        $suffix = $suffix && preg_match('/^[a-zA-Z0-9]+$/', $suffix) ? $suffix : 'file';
//
//        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
//        $typeArr = explode('/', $fileInfo['type']);
//
//        //禁止上传PHP和HTML文件
//        if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm', 'phar', 'phtml']) || preg_match("/^php(.*)/i", $suffix)) {
//            $this->apiError('上传文件格式受限制');
//        }
//
//        //Mimetype值不正确
//        if (stripos($fileInfo['type'], '/') === false) {
//            $this->apiError('上传文件格式受限制');
//        }
//
//        //验证文件后缀
//        if ($upload['mimetype'] !== '*' &&
//            (
//                !in_array($suffix, $mimetypeArr)
//                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
//            )
//        ) {
//            $this->apiError('上传文件格式受限制');
//        }
//
//        //验证是否为图片文件
//        $imagewidth = $imageheight = 0;
//        if (in_array($fileInfo['type'],
//                ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix,
//                ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
//            $imgInfo = getimagesize($fileInfo['tmp_name']);
//            if (! $imgInfo || ! isset($imgInfo[0]) || ! isset($imgInfo[1])) {
//                $this->apiError('上传文件不是有效的图片文件');
//            }
//            $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
//            $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
//        }
//
//        $_validate[] = 'filesize:'.$size;
//        if ($upload['mimetype']) {
//            $_validate[] = 'fileExt:'.$upload['mimetype'];
//        }
//        $validate = implode('|', $_validate);
//
//        $event_config = Event::trigger('upload_init', $upload,true);
//        if($event_config){
//            $upload = array_merge($upload, $event_config);
//        }
//        try {
//            $savename = upload_file($file, $upload['driver'], 'uploads', $validate, $upload['cdnurl']);
//        } catch (\Exception $e) {
//            $savename = false;
//            $this->apiError($e->getMessage());
//        }
//        if (! $savename) {
//            $this->apiError('上传失败');
//        }
//        $category = request()->post('category');
//        $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
////        $urls= Env::get('APP.URL_MY')? Env::get('APP.URL_MY'):'https://ceshi.excellentkk.cn';
//        $params = [
//            'admin_id'    => 0,
//            'user_id'     => (int) JWT_UID,
//            'category'    => $category,
//            'filename'    => mb_substr(htmlspecialchars(strip_tags($fileInfo['name'])), 0, 100),
//            'filesize'    => $fileInfo['size'],
//            'imagewidth'  => $imagewidth,
//            'imageheight' => $imageheight,
//            'imagetype'   => $suffix,
//            'imageframes' => 0,
//            'mimetype'    => $fileInfo['type'],
//            'url'         => $savename,
//            'uploadtime'  => time(),
//            'storage'     => $upload['driver'],
//            'sha1'        => $sha1,
//        ];
//        $attachment = new Attachment();
//        $attachment->data(array_filter($params));
//        $attachment->save();
//        \think\facade\Event::trigger('upload_after', $attachment);
//        $this->apiSuccess('上传成功', [
//            'url' =>$savename,
//        ]);
//    }

    //上传文件
    public function upload()
    {
        $param = get_params();
        //var_dump($param);exit;
        $sourse = 'file';
        if(isset($param['sourse'])){
            $sourse = $param['sourse'];
        }
        if($sourse == 'file' || $sourse == 'tinymce'){
            if(request()->file('file')){
                $file = request()->file('file');
            }
            else{
                return to_assign(1, '没有选择上传文件');
            }
        }
        else{
            if (request()->file('editormd-image-file')) {
                $file = request()->file('editormd-image-file');
            } else {
                return to_assign(1, '没有选择上传文件');
            }
        }
        // 获取上传文件的hash散列值
        $sha1 = $file->hash('sha1');
        $md5 = $file->hash('md5');
        $rule = [
            'image' => 'jpg,png,jpeg,gif',
            'doc' => 'doc,docx,ppt,pptx,xls,xlsx,pdf',
            'file' => 'zip,gz,7z,rar,tar',
            'video' => 'mpg,mp4,mpeg,avi,wmv,mov,flv,m4v',
        ];
        $fileExt = $rule['image'] . ',' . $rule['doc'] . ',' . $rule['file'] . ',' . $rule['video'];
        //1M=1024*1024=1048576字节
        $fileSize = 100 * 1024 * 1024;
        if (isset($param['type']) && $param['type']) {
            $fileExt = $rule[$param['type']];
        }
        if (isset($param['size']) && $param['size']) {
            $fileSize = $param['size'];
        }
        $validate = \think\facade\Validate::rule([
            'image' => 'require|fileSize:' . $fileSize . '|fileExt:' . $fileExt,
        ]);
        $file_check['image'] = $file;
        if (!$validate->check($file_check)) {
            return to_assign(1, $validate->getError());
        }
        // 日期前綴
        $dataPath = date('Ym');
        $use = 'thumb';
        $accessKeyId = "LTAI5t7mhH3ij2cNWs1zhPmv"; ;
        $accessKeySecret = "gqo2wMpvi8h5bDBmCpMje6BaiXvcPu";
        $endpoint = "oss-cn-chengdu.aliyuncs.com";
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            return to_assign(1, $e->getMessage());
        }
        $bucket = "lihai001";
        $object = 'storage/'.$dataPath.'/'.$md5.'.jpg';
//        $filename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file, function () use ($md5) {
//            return $md5;
//        });
        try {
            $filename=$ossClient->uploadFile($bucket, $object,$file);
        } catch (OssException $e) {
            return to_assign(1, $e->getMessage());
        }
        if ($filename) {
            //写入到附件表
            $data = [];
            $path = get_config('filesystem.disks.public.url');
            $data['filepath'] = $filename['info']['url'];
            $data['name'] = $file->getOriginalName();
            $data['mimetype'] = $file->getOriginalMime();
            $data['fileext'] = $file->extension();
            $data['filesize'] = $file->getSize();
            $data['filename'] = $object;
            $data['sha1'] = $sha1;
            $data['md5'] = $md5;
            $data['module'] = \think\facade\App::initialize()->http->getName();
            $data['action'] = app('request')->action();
            $data['uploadip'] = app('request')->ip();
            $data['create_time'] = time();
            $data['user_id'] = JWT_UID ? JWT_UID : 0;
            if ($data['module'] = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status'] = 1;
                $data['admin_id'] = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use'] = request()->has('use') ? request()->param('use') : $use; //附件用处
            $res['id'] = Db::name('file')->insertGetId($data);
            $res['filepath'] = $data['filepath'];
            $res['name'] = $data['name'];
            $res['filename'] = $data['filename'];
//            add_log('upload', $data['user_id'], $data);
            if($sourse == 'editormd'){
                //editormd编辑器上传返回
                return json(['success'=>1,'message'=>'上传成功','url'=>$data['filepath']]);
            }
            else if($sourse == 'tinymce'){
                //tinymce编辑器上传返回
                return json(['success'=>1,'message'=>'上传成功','location'=>$data['filepath']]);
            }
            else{
                //普通上传返回
//                return to_assign(0, '上传成功', $res);
                $this->apiSuccess('上传成功', [
                    'url' =>$data['filepath'],
                ]);
            }
        } else {
            return to_assign(1, '上传失败,请重试');
        }
    }
    public function category($id=0,$type='',$pid=0,$is_category=false){

        if ($is_category){
            if ($pid==162){
                $data=[['id'=>1,'name'=>'全部'],['id'=>2,'name'=>'未结束'],['id'=>3,'name'=>'已结束']];
                return $this->apiSuccess('ok',$data);
            }
            if ($pid==1){
                $data=[['id'=>1,'name'=>'全部'],['id'=>2,'name'=>'户主']];
                return $this->apiSuccess('ok',$data);
            }
            $solve=[165,147,148,149];
            if (in_array($pid,$solve)){
                $data=[['id'=>1,'name'=>'全部'],['id'=>2,'name'=>'未处理'],['id'=>3,'name'=>'已处理']];
                return $this->apiSuccess('ok',$data);
            }
            $order=[164,163,152,160,161];
            if (in_array($pid,$order)){
                $data=[['id'=>1,'name'=>'降序'],['id'=>2,'name'=>'升序']];
                return $this->apiSuccess('ok',$data);
            }
        }
        if ($type){
            $where[]=['type','=',$type];
        }
        if ($id){
            $where[]=['id','=',$id];
        }
        if ($id==0 && $type==''){
            return $this->apiError('参数不能为空,请填写参数');
        }
        if($pid){
            $where[]=['pid','=',$pid];
        }else{
            $where[]=['pid','<>',0];
        }

        $where[]=['status','=','normal'];
        $select=Db::table('fa_category')->where($where)->select();
        return $this->apiSuccess('ok',$select);
    }

    public function categorys($id=0,$type='',$pid=0,$is_category=false){

        if ($is_category){
            if ($pid==162){
                $data=[['id'=>1,'name'=>'全部'],['id'=>2,'name'=>'未结束'],['id'=>3,'name'=>'已结束']];
                return $this->apiSuccess('ok',$data);
            }
            if ($pid==1){
                $data=[['id'=>1,'name'=>'全部'],['id'=>2,'name'=>'户主']];
                return $this->apiSuccess('ok',$data);
            }
            $solve=[165,147,148,149];
            if (in_array($pid,$solve)){
                $data=[['id'=>1,'name'=>'全部'],['id'=>2,'name'=>'未处理'],['id'=>3,'name'=>'已处理']];
                return $this->apiSuccess('ok',$data);
            }
            $order=[164,163,152,160,161];
            if (in_array($pid,$order)){
                $data=[['id'=>1,'name'=>'降序'],['id'=>2,'name'=>'升序']];
                return $this->apiSuccess('ok',$data);
            }
        }
        if ($type){
            $where[]=['type','=',$type];
        }
        if ($id){
            $where[]=['id','=',$id];
        }
        if ($id==0 && $type==''){
            return $this->apiError('参数不能为空,请填写参数');
        }
        if($pid){
            $where[]=['pid','=',$pid];
        }else{
            $where[]=['pid','<>',0];
        }
        $where[]=['status','=','normal'];
        $select=Db::table('fa_category')->where($where)->field('id as category_id,name as topic_name,image as pic,pid')->select()->toArray();
        foreach ($select as $k=>$v){
            if($v['pid'] == 0){
                $select[$k]['children'] = Db::table('fa_category')->where('pid',$v['category_id'])->field('id as category_id,name as topic_name,image as pic')->select();
            }
        }
        return $this->apiSuccess('ok',$select);
    }
    public function idcard($code){
        $user_id = $this->request->get('user_id');
        if($user_id){
            $www[] = [['user_id','=',$user_id],['idcard','=',$code]];
        }else{
            $www = [];
        }
        $where[] = ['idcard','=',$code];
        $where[] = ['is_hz','=',1];
        $find=Db::table('fa_szxc_information_usermsg')->where($where)->whereOr($www)->field('user_id,name,age')->find();
//        dump(Db::table('fa_szxc_information_usermsg')->getLastSql());die;
        return $this->apiSuccess('ok',$find);

    }
    //区县数据
    public function get_area($city_code){
        $select=Db::table('fa_geo_area')->where('city_code',$city_code)->field('area_id id,area_code code,area_name name')->select();
        return $this->apiSuccess('ok',$select);
    }
    //街道 乡镇数据
    public function get_street($area_code){
        $select=Db::table('fa_geo_street')->where('area_code',$area_code)->field('street_id id,street_code code,street_name name')->select();
        return $this->apiSuccess('ok',$select);
    }
    //村数据
    public function get_village($street_code){
        $select=Db::table('fa_geo_village')->where('street_code',$street_code)->field('village_id id,village_code code,village_name name')->select();
        return $this->apiSuccess('ok',$select);
    }

    //大队数据
    public function get_brigade(){
        $select=Db::table('fa_geo_brigade')->field('id,brigade_name as name')->select();
        $this->apiSuccess('ok',$select);
    }

    public function get_all_category(){
        $nation=Db::table('fa_category')->where('type','=','nation')->where('pid','<>','0')->select();
        $Zzmm=Db::table('fa_category')->where('type','=','Zzmm')->where('pid','<>','0')->select();
        $Education=Db::table('fa_category')->where('type','=','Education')->where('pid','<>','0')->select();
        $Occupation=Db::table('fa_category')->where('type','=','Occupation')->where('pid','<>','0')->select();
        $Car=Db::table('fa_category')->where('type','=','Car')->where('pid','<>','0')->select();
        $House=Db::table('fa_category')->where('type','=','House')->where('pid','<>','0')->select();
        $Family=Db::table('fa_category')->where('type','=','Family')->where('pid','<>','0')->select();
        $Marriage=Db::table('fa_category')->where('type','=','Marriage')->where('pid','<>','0')->select();
        $select=[
            'nation' =>$nation,
            'occupation' =>$Occupation,
            'car' =>$Car,
            'house' =>$House,
            'zzmm' =>$Zzmm,
            'education' =>$Education,
            'family' =>$Family,
            'marriage' =>$Marriage
        ];
        return $this->apiSuccess('ok',$select);
    }
    public function get_all_category_insurance(){
        $Grade=Db::table('fa_category')->where('type','=','Grade')->select();//等级
        $Insurance_one=Db::table('fa_category')->where('pid','=','194')->select();//商业保险
        $Insurance_two=Db::table('fa_category')->where('pid','=','193')->select();//农业保险
        $Whether_disabled=Db::table('fa_category')->where('type','=','Whether_disabled')->select();//残疾状况
        $Medical_insurance_type=Db::table('fa_category')->where('type','=','Medical_insurance_type')->select();//残疾状况
        $select=[
            'grade' =>$Grade,
            'Insurance_one' =>$Insurance_one,
            'Insurance_two' =>$Insurance_two,
            'Whether_disabled' =>$Whether_disabled,
            'Medical_insurance_type' =>$Medical_insurance_type,
        ];
        return $this->apiSuccess('ok',$select);
    }
    public function get_all_category_health(){
        $Blood_type=Db::table('fa_category')->where('type','=','Blood_type')->select();
        $Insurance_type=Db::table('fa_category')->where('type','=','Insurance_type')->select();
        $Drug_allergy=Db::table('fa_category')->where('type','=','Drug_allergy')->select();
        $Exposure_history=Db::table('fa_category')->where('type','=','Exposure_history')->select();
        $History_of_disease=Db::table('fa_category')->where('type','=','History_of_disease')->select();
        $whether_disabled=Db::table('fa_category')->where('type','=','whether_disabled')->select();
        $cfpfss=Db::table('fa_category')->where('type','=','cfpfss')->select();
        $fuel_type=Db::table('fa_category')->where('type','=','fuel_type')->select();
        $Drinking_water=Db::table('fa_category')->where('type','=','Drinking_water')->select();
        $Toilet_msg=Db::table('fa_category')->where('type','=','Toilet_msg')->select();
        $Poultry_corral=Db::table('fa_category')->where('type','=','Poultry_corral')->select();
        $FamilyHistory=Db::table('fa_category')->where('type','=','FamilyHistory')->select();
        $select=[
            'Blood_type' =>$Blood_type,
            'Insurance_type' =>$Insurance_type,
            'Drug_allergy' =>$Drug_allergy,
            'Exposure_history' =>$Exposure_history,
            'History_of_disease' =>$History_of_disease,
            'whether_disabled' =>$whether_disabled,
            'cfpfss' =>$cfpfss,
            'fuel_type' =>$fuel_type,
            'Drinking_water' =>$Drinking_water,
            'Toilet_msg' =>$Toilet_msg,
            'Poultry_corral' =>$Poultry_corral,
            'FamilyHistory' =>$FamilyHistory,
        ];
        return $this->apiSuccess('ok',$select);
    }
}