<?php


namespace api\modules\v1\controllers;


use api\common\controllers\Controller;
use common\helpers\CodeImgGenerate;
use common\helpers\Util;
use common\modules\config\models\Config;
use common\models\Survey;
use Yii;
use yii\helpers\ArrayHelper;
use api\common\behaviors\QueryParamAuth;
use yii\captcha\CaptchaAction;
use common\enums\CodeEnum;
use common\models\Policy;

class SurveyController extends Controller {

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => QueryParamAuth::className(),
                'tokenParam' => 'token',
                'optional' => ['index','submit','enterprise','captcha']
            ]
        ]);
    }
    
    
    public function actionCaptcha()
    {
        $CodeImgGenerate = new CodeImgGenerate(\Yii::$app->controller->id,\Yii::$app->controller);
        $codeInfo = $CodeImgGenerate->inline();                  // 验证码二进制流
        header("Content-type: image/png");                       // 输出图片
        exit($codeInfo);
    }

    /**
     * @api {get} /v1/survey 列表
     * @apiVersion 1.0.0
     * @apiName index
     * @apiGroup Survey
     *
     *
     */
    public function actionIndex()
    {
        $type = request()->get('type');
        if(empty($type)) $type = 'industry';
        
        $lists = ArrayHelper::toArray(Config::find()->select(['name','value','extra','description','type'])->where(['group' => $type])->all());

		foreach ($lists as &$value) {
			$value['value'] = explode("\r\n",$value['extra']);

			foreach($value['value'] as &$val){
				$val = trim($val);
			}


			unset($value['extra']);
        }

        return ['data' => $lists];
    }

	public function actionEnterprise()
    {
		$params = request()->post();
  
       
// 		$params = [
// 			'name'=>'企业名称1',
// 			'address'=>'企业注册地',
// 			'estdate'=>'2023-10-23',
// 			'busAddress'=>'企业实际经营地',
// 			'propertyNumber'=>1, //企业有效l类知识产权数
// 			'propertyNumber2'=>2, //有效、高企认定中未使用过的II类知识产权数
// 			'propertyMode'=>1, //知识产权获取方式 1：自主研发 2：仅有受让、受赠和并购等
//  			'isStandard'=>0, //企业参与编制国家标准、行业标准、检测方法、技术规范的情况  1：是 0：否
// 			'achievementNumber'=>1, //科技成果数,

// 			'manageLevel1'=>1, //定制了企业研究开发组织管理制度
// 			'manageLevel2'=>1, //建立了研发投入核算体系
// 			'manageLevel3'=>1,  //编制了研发费用辅助帐
// 			'manageLevel4'=>1,  //设立了内部科技技术研究开发机构并具备相应的科研条件
// 			'manageLevel5'=>1,  //与国内外研究开发机构开展多种形式的产学研合作
// 			'manageLevel6'=>1,  //建立了科技成果转化的组织实施与激励奖励制度
// 			'manageLevel7'=>1,  //建立开放式的创新创业平台
// 			'manageLevel8'=>1,  //建立了科技人员的培养进修制度
//             'manageLevel9'=>1,  //建立了职工技能培训制度
            
// 			'netAssets1'=>111, //第1年   净资产
// 			'netAssets2'=>222, //第2年   净资产
// 			'netAssets3'=>333, //第3年   净资产
// 			'saleRevenue1'=>444, //第1年  销售收入
// 			'saleRevenue2'=>555, //第2年  销售收入
// 			'saleRevenue3'=>666 //第3年  销售收入
// 		];
        
        //知识产权数量
        $numberScore = 0;
        if($params['propertyNumber2'] == 1 || $params['propertyNumber2'] == 2) $numberScore = 2;
        if($params['propertyNumber2'] == 3 || $params['propertyNumber2'] == 4) $numberScore = 4;
        if($params['propertyNumber2'] >= 5) $numberScore = 6;
        if($params['propertyNumber'] > 1) $numberScore = 8;
        
        //知识产权获得方式
        $modeScore = 0;
        if($params['propertyMode'] == 1) $numberScore = 6;
        if($params['propertyMode'] == 2) $numberScore = 3;
        
        //企业参与编制国家标准、行业标准、检测方法、技术规范的情况
        $standardScore = 0;
        if($params['isStandard'] == 1) $standardScore = 2;
        
        //科技成果转化能力
        $techniquesAchieveScore = 0;
        if($params['achievementNumber'] == 1) $techniquesAchieveScore = 6;
        if($params['achievementNumber'] == 2) $techniquesAchieveScore = 12;
        if($params['achievementNumber'] == 3) $techniquesAchieveScore = 18;
        if($params['achievementNumber'] == 4) $techniquesAchieveScore = 25;
        if($params['achievementNumber'] >= 5) $techniquesAchieveScore = 30;
        
        //研究开发组织管理水平
        $manageLevelScore = 0;
        if($params['manageLevel1'] == 1) $manageLevelScore += 2;
        if($params['manageLevel2'] == 1) $manageLevelScore += 2;
        if($params['manageLevel3'] == 1) $manageLevelScore += 2;
        if($params['manageLevel4'] == 1) $manageLevelScore += 3;
        if($params['manageLevel5'] == 1) $manageLevelScore += 3;
        if($params['manageLevel6'] == 1) $manageLevelScore += 2;
        if($params['manageLevel7'] == 1) $manageLevelScore += 2;
        if($params['manageLevel8'] == 1) $manageLevelScore += 2;
        if($params['manageLevel9'] == 1) $manageLevelScore += 2;
        
        //净资产增长率
        $growthRate = (0.5 * ($params['netAssets2'] / $params['netAssets1'] + $params['netAssets3'] / $params['netAssets2']) - 1) * 100;
        
        $growthRateScore = 0;
        if($growthRate > 0) $growthRateScore = 2;
        if($growthRate > 5) $growthRateScore = 4;
        if($growthRate > 10) $growthRateScore = 6;
        if($growthRate > 20) $growthRateScore = 9;
        
        //销售收入增长率
        $saleRate = (0.5 * ($params['saleRevenue2'] / $params['saleRevenue1'] + $params['saleRevenue3'] / $params['saleRevenue2']) - 1) * 100;
        
        $saleRateScore = 0;
        if($saleRate > 0) $saleRateScore = 2;
        if($saleRate > 10) $saleRateScore = 4;
        if($saleRate > 20) $saleRateScore = 6;
        if($saleRate > 30) $saleRateScore = 7;
        
        
		$result = [ 
			'totalScore'=>8 + 8 + $numberScore + $modeScore + $standardScore +  $numberScore + $modeScore + $standardScore + $techniquesAchieveScore + $manageLevelScore + $growthRateScore + $saleRateScore, //企业评测总得分
			'basic'=>[
				'name'=>$params['name'],
				'address'=>$params['address'],
				'estdate'=>$params['estdate'],
				'busAddress'=>$params['busAddress'],
				'propertyNumber'=>$params['propertyNumber'],
				'propertyNumber2'=>$params['propertyNumber2'],
				'propertyMode'=>$params['propertyMode'],
				'isStandard'=>$params['isStandard'],
				'achievementNumber'=>$params['achievementNumber'],
			],
			'knowledgeVo'=>[
				'knowledgeTotalScore'=>$numberScore + $modeScore + $standardScore + 8 + 8, //知识产权
				'techniquesScore'=>8, //技术的先进程度  
				'effectScore'=>8, //对主要产品(服务)在技术上发挥核心支持作用(8分)
				'numberScore'=>$numberScore, //知识产权数量
				'modeScore'=>$modeScore, //知识产权获得方式
				'standardScore'=>$standardScore  //企业参与编制国家标准、行业标准、检测方法、技术规范的情况
			],
			'techniquesAchieveScore'=>$techniquesAchieveScore, //科技成果转化能力
			'manageLevelScore'=>$manageLevelScore,  //研究开发组织管理水平
			'enterpriseGrowthVo'=>[
				'totalScore'=>$growthRateScore + $saleRateScore, //企业成长性
				'growthRateScore'=>$growthRateScore, //净资产增长率得分
				'saleRateScore'=>$saleRateScore, //销售收入增长率得分
				
			]
		];
	
        return ['data' => $result];
    }

	public function actionSubmit()
    {
		
		$data = request()->post();
		$type = request()->get('type');
        if(empty($type)) $type = 'industry';
        
		$survey = Survey::find()->where(['type' => $type])->all();

        $captcha = new CodeImgGenerate(\Yii::$app->controller->id,\Yii::$app->controller);

        $result = $captcha->validate($data['code']);
        
         if(!$result){
             return ['errcode' => CodeEnum::CODE_ERROR, 'errmsg' => '验证码错误'];
         }

		$list = [];
		foreach ($survey as $key=>$value) {
		    $filter = json_decode($value['filter'],true);
			foreach ($filter as $key=>$value1) {
			    if(!empty($value1)){
			        $str = join('|',(array)$value1);
			        if(array_key_exists($key,$data) && !empty($data[$key])){
                        if(strpos($str,(string)$data[$key]) !== false){
                            $list[] = [
                                'id'=>$value['id'],
                                'title'=>$value['title'],
                                'content'=>$value['content']
                            ];
                            continue;
                        }
                    }
			    }
			}
		}
        //去重复
		$cengci = [];      
        foreach ($list as $value) {       
            if(isset($cengci[$value['title']])){
                unset($value['title']);
            }else{
                $cengci[$value['title']] = $value;
            }  
        }
        $cengci = array_values($cengci);


        $query = Policy::find()->select('id,title,author,content,created_at,summary');
        //过滤匹配类型的政策
        $query->andWhere(new \yii\db\Expression('FIND_IN_SET("'. Policy::TYPE_SURVEY .'", type)'));
        if(!empty($cengci)){
            foreach ($cengci as $value) {
		         $query->orWhere(new \yii\db\Expression('FIND_IN_SET("'.$value['title'].'", cengci)'));
    		}
            $list = $query->all();
        }


        return ['data'=>$list,'cengci'=>$cengci];

    }

    /**
     * @api {get} /v1/category/id:\d+ 分类详情
     * @apiVersion 1.0.0
     * @apiName view
     * @apiGroup Category
     *
     */
    public function actionView($id)
    {
        $model = Category::find()->where(['id' => $id])->one();

        return ['data' => $model];
    }


}