<?php
namespace api\action\v1;


use admin\action\sample\interioAction;
use api\action\baseAction;
use League\Csv\Exception;
use model\pro\packing;
use model\pro\pro;
use model\pro\product;

/**
 * Class proAction
 * @package api\action\v1
 */
class proAction extends baseAction
{
	 /**
     * 通过搜索
	 * @param  $gsp_num  string [选填] GS454-54454
	 * @param  $start_time  string [选填] 开始时间
	 * @param  $end_time  string [必填] 结束时间
	 * @param  $time_type  string [选填] create_time|update_time
	 * @param  $page  int [选填] 第几页
	 * @param  $page_size  int [选填] 每页数量 默认15
     */
    public function searchProduct()
    {
		ini_set('memory_limit', \mvc::$cfg['upload']['memory_limit']);
		set_time_limit(0);
        try {
            $params = $this->getParaam();
			$product = new product();
			$data = $product->searchProduct($params, $this->cfg);
			if(empty($data)) return $this->returnJson(0,'无数据',[]);
            return $this->returnJson(200,'ok',$data);
		}catch (Exception $e) {
            $this->returnJson(500,$e->getMessage());
        }
	}


	 /**
     * 询单系统 通过创建时间或者更新时间查找产品
	 * @param  $start_time  string [必填] 开始时间
	 * @param  $end_time  string [必填] 结束时间
	 * @param  $page  int [选填] 第几页
	 * @param  $page_size  int [选填] 每页数量 默认15
	 * @param  $time_type  string [选填] create_time|update_time
     */
    public function getProductByTime()
    {
		ini_set('memory_limit', \mvc::$cfg['upload']['memory_limit']);
		set_time_limit(0);
		errorLog($this->getParaam(),'getProductByTime');
		try {
			$params = $this->getParaam();
			if(empty($params['start_time'])) return $this->returnJson(0,'start_time参数异常',[]);
			if(empty($params['end_time'])) return $this->returnJson(0,'end_time参数异常',[]);
			if(!in_array($params['time_type'], ['create_time', 'update_time'])) return $this->returnJson(0,'time_type参数异常',[]);
			if(!is_array($params['block']))  return $this->returnJson(0,'block参数异常',[]);
			$product = new product();
			$data = $product->searchProListByRca($params);
			if(empty($data)) return $this->returnJson(0,'无数据',[]);
            return $this->returnJson(200,'ok',$data);
		}catch (Exception $e) {
            $this->returnJson(500,$e->getMessage());
        }
	}

    /**
     * 包装
     */
    public function packing()
    {
        try {
            $param = $this->getParaam();
            $data = [
                'pack' => $param['pack'],
                'miniqty_sales' => (int) $param['miniqty_packing'],
                'miniqty_packing' => (int) $param['miniqty_packing'],
                'miniqty_trays' => (int) $param['miniqty_trays'],
                'nilongsize' => $param['nilongsize'],
                'zhihesize' => $param['zhihesize'],
                'waixiangsize' => $param['waixiangsize'],
                'zhixiangsize' => $param['zhixiangsize'],
                'danzhong' => $param['danzhong']
            ];
            foreach ($data as $key => $value){
                if($key == 'miniqty_sales' || $key == 'miniqty_packing' || $key == 'miniqty_trays'){
                    continue;
                }
                if(mb_strlen($value) > 255){
                    $this->returnJson(500,$key.'长度超过了255');
                }
            }
            $pro = new pro();

            $brand = trim($param['brand']);
            $param['outnum'] = trim($param['outnum']);
            if (isset($param['outnum']) && !empty($param['outnum'])){
                $ppId = $pro->getNumberAndBrandByPid('p_outnum',$param['outnum'],$brand);
            }
            if(isset($param['innum']) && !isset($ppId)){
                $param['innum'] = trim($param['innum']);
                $ppId = $pro->getNumberAndBrandByPid('p_innum',$param['innum'],$brand);
            }

            if((int) $ppId <= 0){
				errorLog([$param,'找不到该号码'],'setParam');
                $this->returnJson(500,'找不到该号码');
            }
            $data['pp_id'] = (int) $ppId;
            $pack = new packing();
            $result = $pack->add($data);
            if ($result === false){
                $this->returnJson(500, '参数错误,  请稍后再试');
            }
            $this->returnJson(200,'ok');
        }catch (Exception $e) {
            $this->returnJson(500,$e->getMessage());
        }

    }
    
    /**
     * 参数
     */
    public function setParam()
    {
        try {
            $param = $this->getParaam();
            
            if ($result === false){
                $this->returnJson(500, '参数错误,  请稍后再试');
            }
			$proparam = new \model\pro\param();
			$res = $proparam->setProParamByApi($param);
            if(!empty($res['msg'])){
				errorLog([$param,$res],'setParam');
				$this->returnJson(500, $res['msg']);
			}
			$this->returnJson(200,'ok',$param);
        }catch (Exception $e) {
		   errorLog([$param,$e->getMessage()],'setParam');
           $this->returnJson(500,$e->getMessage());
        }
    }
    
    /**
     * 图纸
     */
    private function getFile($url, $save_dir = '', $filename = '',$token, $timeout = 300) {
        if (trim($url) == '') {
            return false;
        }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir.= '/';
        }
        //创建保存目录
        mkdirs($save_dir);
        //获取远程文件所采用的方法
		$content = ioGet($url,[],[],300);
        $size = strlen($content);

        if($size <= 0){
            return false;
        }
        //文件大小
        $fp2 = @fopen($save_dir . $filename, 'w');
        fwrite($fp2, $content);
        fclose($fp2);
        unset($content, $url);
        return $filename;
    }
    public function uploadLineFile()
    {
        try {
            $param = $this->getParaam();
            //file_type,url,code
            $code = $param['code'];
            if ($code==''){
                $this->returnJson(500, '内部编码 code 不能为空');
            }
            if ($param['url']==''){
                $this->returnJson(500, 'url 不能为空');
            }
            if ($param['file_type']==''){
                $this->returnJson(500, 'file_type 不能为空');
            }
            $pro = makeOne(\model\pro\pro::class);
            $p_id = $pro->getRowByFieldValue('p_outnum_format',formatNum($code),'p_id');
            if(!$p_id){
                $this->returnJson(500, '产品未找到');
            }
			/*
            $token = $this->getGspAPI1_token();
            if($token==''){
                $this->returnJson(500, '获取 GSP API1 TOKEN 失败');
            }*/
            $save_dir = \mvc::$cfg['dir']['files'].'/pro/line';
            $filename = $p_id.'.'.strtolower($param['file_type']);
			//errorLog($param,'uploaadLine');
            $res = $this->getFile($param['url'], $save_dir, $filename, $token);
            if($res){
                $pro->setValue($p_id,'p_lineimg',$filename);
                $pro->setValue($p_id,'p_lineimg_date',date('Y-m-d'));
            }
			$this->returnJson(200,'ok',[$filename]);
        }catch (Exception $e) {
			errorLog($param,'uploaadLine');
            $this->returnJson(500,$e->getMessage());
        }
    }
}