<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Db;
use helper\Dir;
use XYCms\Email as SendEmail;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\CompanyIndustry as CompanyIndustryModel;
use app\common\UploadFile;
use app\bsadmin\model\ApiRoute as ApiRouteModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\User as UserModel;
use app\common\model\School as SchoolModel;
use app\common\model\Specialities as SpecialitiesModel;
use XYCms\Push;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\model\Orders as OrdersModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\controller\Orders as OrdersController;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config as AliConfig;
use app\common\model\NotifyAlipay as NotifyAlipayModel;
use app\common\model\NotifyWxpay as NotifyWxpayModel;
use app\common\model\UserWx as UserWxModel;
use app\common\model\NotifyBaidu as NotifyBaiduModel;

class Test extends Base
{
    public function index()
    {
        $G=request()->get();
        if(!empty($G['action'])){
            switch ($G['action']) {
                case 'createMessage':
                    $this->createMessage();
                    break;
                case 'sendPush':
                    $this->sendPush();
                    break;
                case 'rights_handle':
                    $this->rights_handle();
                    break;
                case 'TRUNCATE':
                    $this->TRUNCATE_handle();
                    break;
                case 'init_vip':
                    $this->init_vip();
                    break;
                case 'createVersionPackage':
                    return $this->createVersionPackage();
                    break;
                case 'openZip':
                    $this->openZip();
                    break;
                case 'copyAppApi':
                    $this->copyAppApi();
                    break;
                case 'showApi':
                    $this->showApi();
                    break;
            }
        }
    }

    protected function createVersionPackage()
    {

        $version_name=request()->get('version_name');
        $root_path=root_path();
        $path=$root_path.'package/'.$version_name;
        $filelist=@file_get_contents($path.'/package.log');
        if(!$filelist)
            return '备份清单不存在';
        $filelist=array_unique(explode("\n",$filelist));
        $filename=$path.'/packages.zip';
        if(file_exists($filename))
            unlink($filename);
        $zip = new \ZipArchive;
        if($zip->open($filename,\ZIPARCHIVE::CREATE)!==TRUE){
            return '无法打开备份，或者备份创建失败';
        }
        foreach ($filelist as $k => $v) {
            if(!$v)break;
            $filepath=str_replace("\r",'',$root_path.$v);
            if(is_dir($filepath)){
                $this->addPathToZip($zip,$filepath,$root_path);
            }else{
                if(file_exists($filepath))
                    $zip->addFile($filepath,$v);
            }
        }
        $zip->close();
        return 'ok';
    }
    protected function addPathToZip($zip,$filepath,$root_path)
    {
        $files=Dir::tree($filepath);
        foreach ($files as $key => $value) {
            if(is_dir($value['path'])){
                $this->addPathToZip($zip,$value['path'],$root_path);
            }else{
                if(file_exists($value['path']))
                    $zip->addFile($value['path'],str_replace($root_path,'',$value['path']));
            }
        }
    }

    protected function openZip()
    {
        if(is_file(root_path().'app/common.php')){
            echo "string";
        }
        die;
    	$version_name=request()->get('version_name');
        $root_path=root_path();
        $path=$root_path.'package/'.$version_name;
        $filename=$path.'/packages.zip';
        $zip = new \ZipArchive;
        if($zip->open($filename)===TRUE){
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $contents = $zip->getNameIndex($i);
                p($contents);
            }
            $zip->close();
        }
        echo 'ok';
    }
    public function init_vip()
    {
        $UpdateUser=new \app\common\service\queue\UpdateUser;
        $UpdateUser->init_user_vip_handle();
    }
    public function TRUNCATE_handle()
    {
    	die;
    	$table=[
    		'xy_admin_log',
    		'xy_admin_login_log',
    		'xy_ads',
    		'xy_api_log',
    		'xy_app_version',
    		'xy_article',
    		'xy_article_content',
    		'xy_blacklist',
    		'xy_company',
    		'xy_company_attestation',
    		'xy_company_blacklist',
    		'xy_company_browse',
    		'xy_company_collection',
    		'xy_company_content',
    		'xy_company_demeanor',
    		'xy_company_development_history',
    		'xy_company_executives',
    		'xy_company_view',
    		'xy_feedback',
    		'xy_files',
    		'xy_im_contacts',
    		'xy_invite_aninterview',
    		'xy_invite_aninterview_video',
    		'xy_invoice',
    		'xy_invoice_info',
    		'xy_invoice_mail_address',
    		'xy_job_fair',
    		'xy_job_fair_booth',
    		'xy_job_fair_booth_cate',
    		'xy_job_fair_booth_status',
    		'xy_job_fair_company',
    		'xy_job_fair_contacts',
    		'xy_job_fair_content',
    		'xy_job_fair_resume',
    		'xy_job_fair_vip',
    		'xy_jobs',
    		'xy_jobs_browse',
    		'xy_jobs_collection',
    		'xy_jobs_contacts',
    		'xy_jobs_delivery_resume',
    		'xy_jobs_examine_log',
    		'xy_jobs_extension_log',
    		'xy_jobs_refresh_auto',
    		'xy_jobs_refresh_log',
    		'xy_jobs_report',
    		'xy_links',
    		'xy_notify_alipay',
    		'xy_notify_applepay',
    		'xy_notify_wxpay',
    		'xy_orders',
    		'xy_push_message',
    		'xy_push_message_content',
    		'xy_push_queue',
    		'xy_push_task',
    		'xy_resume',
    		'xy_resume_blacklist',
    		'xy_resume_browse',
    		'xy_resume_certificate',
    		'xy_resume_collection',
    		'xy_resume_consignment',
    		'xy_resume_downloaded',
    		'xy_resume_educational_experience',
    		'xy_resume_employment_intention',
    		'xy_resume_examine_log',
    		'xy_resume_language_ability',
    		'xy_resume_project_experience',
    		'xy_resume_refresh',
    		'xy_resume_refresh_log',
    		'xy_resume_report',
    		'xy_resume_self_description',
    		'xy_resume_specialty_label',
    		'xy_resume_training_experience',
    		'xy_resume_work_experience',
    		'xy_resume_works',
    		'xy_score_task_complete',
    		'xy_sms_send_log',
    		'xy_statistics',
    		'xy_user',
    		'xy_user_apple',
    		'xy_user_devices',
    		'xy_user_info',
    		'xy_user_invoice',
    		'xy_user_login_log',
    		'xy_user_mail_address',
    		'xy_user_notice',
    		'xy_user_qq',
    		'xy_user_real_name',
    		'xy_user_real_name_log',
    		'xy_user_score',
    		'xy_user_timer',
    		'xy_user_vip',
    		'xy_user_vip_rule',
    		'xy_user_vip_rule_log',
    		'xy_user_wx',
    	];
    	foreach ($table as $k => $v) {
    		Db::query('TRUNCATE TABLE '.$v);
    	}
    	Db::query('ALTER TABLE `xy_user` AUTO_INCREMENT = 100000');
    	echo "已删档";
    }
    public function insertExcel()
    {
        return;
        $inputFileName='./uploads/data3.xls';
        $sheetname = 'Sheet2';
        $inputFileType = IOFactory::identify($inputFileName);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setLoadSheetsOnly($sheetname);
        $spreadsheet = $reader->load($inputFileName);
        $workSheet = $spreadsheet->getActiveSheet();
        $Data=[];
        for ($i=1; $i <= 744; $i++) { 
            $Data[]=[
                'code'  => $workSheet->getCell('A'.$i)->getValue(),
                'specialities'  => $workSheet->getCell('B'.$i)->getValue(),
            ];
        }
        $SpecialitiesModel=new SpecialitiesModel;
        $SpecialitiesModel->saveAll($Data);
        return;
        $inputFileName='./uploads/data1.xls';
        $sheetname = 'sheet1';
        $inputFileType = IOFactory::identify($inputFileName);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setLoadSheetsOnly($sheetname);
        $spreadsheet = $reader->load($inputFileName);
        $workSheet = $spreadsheet->getActiveSheet();
        $Data=[];
        for ($i=1; $i <= 265; $i++) { 
            $Data[]=[
                'school_name'  => $workSheet->getCell('B'.$i)->getValue(),
                'school_code'  => $workSheet->getCell('C'.$i)->getValue(),
            ];
        }
        $SchoolModel=new SchoolModel;
        $SchoolModel->saveAll($Data);
    }
    public function rights_handle()
    {
        $orderList=OrdersModel::where(['status'=>1,'pay_type'=>5])->field('otrade,pay_type,oprice')->limit(5)->select()->toArray();
        foreach ($orderList as $k => $v) {
            OrdersController::ordersHandle($v);
        }
    }
    public function readCell($column, $row, $worksheetName = '')
    {
        //  选定区域
        if ($row >= 1 && $row <= 7) {
            if (in_array($column, range('A','B'))) {
                return true;
            }
        }
        return false;
    }
    public function run()
    {
        $this->createVersionPackage();
    }
    public function sendPush()
    {
        $t1=microtime(true);
        $PushTaskModel=PushTaskModel::where(['id'=>456])->field('id,uid,client,event,status,data')
            ->withAttr('client',function($v,$data){
                return $v?explode(',',$v):'';
            })
            ->withAttr('data',function($v,$data){
                return json_decode($v,true);
            })->find();
            Push::send($PushTaskModel->toArray());
        $t2=microtime(true);
        p($t1);
        p($t2);
        p($t2-$t1);
    }
    public function createMessage()
    {
        $msgData=json_encode(['title'=>'测试标题','desc'=>'测试描述','content'=>'测试内容'],JSON_UNESCAPED_UNICODE);
        $PushTaskModel=new PushTaskModel;
        $PushTaskModel->uid=100001;
        $PushTaskModel->client=null;
        $PushTaskModel->event='userNotice';
        $PushTaskModel->data=$msgData;
        $PushTaskModel->save();
    }
    public function hi()
    {
        $company_industry=CompanyIndustryModel::getCate();
        Cache::set('company_industry',$company_industry);
        p(Cache::get('company_industry'));die;
        return View::fetch();
    }
    public function copyAppApi()
    {
        $app_id=8;
        $to_app_id=10;
        // ->whereNotIn('api_id',[113,116,117,144,195])
        // where(['app_id'=>$app_id])
        $api=ApiRouteModel::where(['app_id'=>$app_id])->field('app_id,api_method, api_name, api_controller, api_action, api_url, api_param, api_allow, api_ext, api_is_login, api_status')->select()->toArray();
        foreach ($api as $k => $v) {
            $api[$k]['app_id']=$to_app_id;
            $api[$k]['is_copy']=1;
        }
        (new ApiRouteModel)->saveAll($api);
        echo "OK";
    }
    public function showApi()
    {
        $app_id=8;
        $to_app_id=10;
        // ->whereNotIn('api_id',[113,116,117,144,195])
        // where(['app_id'=>$app_id])
        $api=ApiRouteModel::where('api_id','=',826)->field('app_id,api_method, api_name, api_controller, api_action, api_url, api_param, api_allow, api_ext, api_is_login, api_status')->select()->toArray();
        echo json_encode($api,JSON_UNESCAPED_UNICODE);
        die;
    }
}
