<?php
class Product_ProductExportController extends Ec_Controller_Action {
	public function preDispatch() {
		$productUnit           = Service_ProductUom::getByCondition();
		$this->productUnit     = array();
		$this->productCategory = Common_DataCache::getProductCategory();

		foreach ($productUnit as $item) {
		$this->productUnit[$item['pu_code']] = $item;
		}
	}


	public function exportProductAction() {		
		set_time_limit(0);
	    ini_set('memory_limit', '1024M');
	    $file   = 'product-' . date('YmdHis') . '.csv';
	    header('Content-Type: application/vnd.ms-excel;charset=gbk');
	    header("Content-Disposition: attachment;filename={$file}");
	    header('Cache-Control: max-age=0');

	    $exportData[0] = array('客户代码','产品SKU','条码类型','产品代码','产品名称','英文名',
		'状态','单位','申报币种','申报价值','产品重量（KG）','海关编码','招海料号','产品品类',
		'供应商代码','长（CM）','宽（CM）','高（CM）','产品接收类型','质检类型','产品分类',
		'产品添加时间','是否属于零件类','有无发票','产品型号','海关品名','是否带电池',
		'电池类型','法定单位' , '法定数量' , '第二法定单位' , '第二法定数量');

	    $params        = $this->getRequest()->getParams();
	    if($params['type'] == '1'){   	
		    $productSku    = isset($params['E1'])  ? trim($params['E1'])  : '';
		    $productBracode  = isset($params['E2'])  ? trim($params['E2'])  : '';
		    $customerCode  = isset($params['E3'])  ? trim($params['E3'])  : '';
		    $productStatus = isset($params['E7'])  ? trim($params['E7'])  : '';
		    $productIsQc   = isset($params['E18']) ? trim($params['E18']) : '';
		    $goods_id  = isset($params['E25'])  ? trim($params['E25'])  : '';
		    $has_invoice = isset($params["E26"])? trim($params['E26']):"";
            $hsGoodsName = isset($params["E29"])? trim($params['E29']):"";
		    $hs_code = isset($params["E27"])? trim($params['E27']):"";
		    

		    $condition     = array(
		      'product_type' => '0', // 只能导出普通产品
		    );

		    if ('' !== $productSku) {
		      $condition['product_sku'] = $productSku;
		    }

		    if ('' !== $customerCode) {
		      $condition['customer_code'] = $customerCode;
		    }

		    if ('' !== $productStatus) {
		      $condition['product_status'] = (string) $productStatus;
		    }

		    if ('' !== $productIsQc) {
		      $condition['product_is_qc'] = (string) $productIsQc;
		    }

		    if ('' !== $has_invoice) {
		        $condition['has_invoice'] = (string) $has_invoice;
		    }
		    if ('' !== $goods_id) {
		        $condition['goods_id'] = (string) $goods_id;
		    }
		    if ('' !== $hs_code) {
		        $condition['hs_code'] = (string) $hs_code;
		    }
		    if ('' !== $productBracode) {
		        $condition['product_barcode'] = (string) $productBracode;
		    }
            if(''!=$hs_code){
                $condition['hs_code'] = $hs_code;
            }
            if(''!= $hsGoodsName){
                $condition['hs_goods_name'] = $hsGoodsName;
            }

		    $condition['dateFor'] = isset($params["dateFor"])? trim($params['dateFor']):"";
		    $condition['dateTo'] = isset($params["dateTo"])? trim($params['dateTo']):"";
		}else{
		    if ($params['pid']) {
		      $condition['product_id_array'] = explode('|', $params['pid']);
		    }else{
		    	 echo Common_Export::exportCsvForNotKey($exportData);
	    		die();
		    }
		}
	    $maxHsCount = $this->getElementCount($condition);
		
		for ($i = 0; $i < $maxHsCount; ++$i) {
			$exportData[0][] = '要素代码';
			$exportData[0][] = '要素名称';
			$exportData[0][] = '申报要素内容';
		}

		$count = Service_Product::getByCondition($condition , 'count(*)');
		if(!$count){
			echo Common_Export::exportCsvForNotKey($exportData);
	    	die();
	    }
		$index = 1;
		$pagesize = 20;
		$pages = ceil($count / $pagesize);

		for ($page=1; $page <= $pages; $page++) {
			$proudctRows = Service_Product::getByCondition($condition , '*' , $pagesize ,$page);
			foreach ($proudctRows as $key => $value) {
				//条码类型
				$product_barcode_type = $this->getStatusText($value['product_barcode_type'], 'BARCODE');
				//状态
				$product_status = $this->getStatusText($value['product_status'], 'PS');
				//单位 
				$pu_code = $this->getStatusText($value['pu_code'], 'UNIT');
				//品类
				$pc_id =	$this->getStatusText($value['pc_id'], 'CATEGORY');
				//供应商代码
				$distributor     = array();
				if (0 != $value['distributor_id']) {
				  $distributor = Service_Distributor::getByPrimaryKey($value['distributor_id']);
				}
				$distributor_code = $distributor ? $distributor['distributor_code'] : '';

				//产品接收类型
				$product_receive_status = $this->getStatusText($value['product_receive_status'], 'PRS');
				//质检类型
				$product_is_qc = $this->getStatusText($value['product_is_qc'], 'QC');
				//产品分类
				$product_type = $this->getStatusText($value['product_type'], 'PT');
				// 是否属于零件类
				$is_accessories = $this->getStatusText($value['is_accessories'], 'PART');
				//有无发票
				$has_invoice = $this->getStatusText($value['has_invoice'], 'INVOICE');

				$pc_id = $this->getStatusText($item['pc_id'], 'CATEGORY');

				$with_battery = $value['with_battery'] == 1 ? '是' : '否' ;

				$battery_type = $value['with_battery'] == 1 ? $this->getStatusText($value['battery_type'], 'batteryType') : "";

				$exportData[$index]	=	array( $value['customer_code'] , $value['product_sku'] , $product_barcode_type
					, $value['product_barcode'] , $value['product_title'] , $value['product_title_en'] , $product_status , $pu_code , $value['currency_code'] , $value['product_declared_value'] , $value['product_weight'] , $value['hs_code'] ,  $value['goods_id'] , $pc_id , $distributor_code , $value['product_length'] , $value['product_width'] , $value['product_height'] , $product_receive_status , $product_is_qc , $product_type , $value['product_add_time'] , $is_accessories , $has_invoice , $value['model_serial'] , $value['hs_goods_name'] , $with_battery , $battery_type);

				//法定单位
				$first_unit = '';
				//法定数量
				$first_quantity = '';
				//第二法定单位
				$second_unit = '';
				//第二法定数量
				$second_quantity = '';
				//
				$hs_info = array();
				if ('' !== trim($value['hs_code'])) { // 有海关编码才去数据库检索数据
					$hsUnit = Service_HsUom::getByCondition(array( // 法定单位
						'hs_code'   => $value['hs_code'],
						'hu_status' => 1,
					));
					if (!empty($hsUnit)) {
				  		$hsUnit = $hsUnit[0];

						if ('' !== $hsUnit['pu_code_law']) {
							$first_unit = $this->getStatusText($hsUnit['pu_code_law'], 'UNIT');
						}

						if ('' !== $hsUnit['pu_code_second']) {
							$second_unit = $this->getStatusText($hsUnit['pu_code_second'], 'UNIT');
						}

					  	// 凭法定单位ID提取法定数量
						$hum_condition    = array(
							'hu_id'         => (int) $hsUnit['hu_id'],
							'product_id'    => $value['product_id'],
						);
						$hsQuantity                         = Service_HsUomMap::getByCondition($hum_condition);
						$first_quantity  = (!empty($hsQuantity)) ? $hsQuantity[0]['hum_quantity_law']    : '';
						$second_quantity = (!empty($hsQuantity)) ? $hsQuantity[0]['hum_quantity_second'] : '';
					}

					$hsElement = Service_HsElement::getByCondition(array( // 申报要素
						'hs_code'   => $value['hs_code'],
						'he_status' => 1,
					));

					if (!empty($hsElement)) {
						foreach ($hsElement as $e) {
							$hem_condition              = array(
							    'he_id'         => (int) $e['he_id'],
							    'product_id'    => $value['product_id'],
							);
							$hsElementMap               = Service_HsElementMap::getByCondition($hem_condition);
							$hs_info[] = array(
							  'code'        => $e['he_code'],
							  'name'        => $e['he_name'],
							  'description' => (!empty($hsElementMap)) ? $hsElementMap[0]['hem_detail'] : '',
							);
						}
					}

	            }

	            $exportData[$index][] = $first_unit;
	            $exportData[$index][] = $first_quantity;
	            $exportData[$index][] = $second_unit;
	            $exportData[$index][] = $second_quantity;
	           
	            if($hs_info){
	            	foreach($hs_info as $e){
	            		$exportData[$index][] = $e['code'];
					    $exportData[$index][] = $e['name'];
					    $exportData[$index][] = $e['description'];     
	            	}
	            }	            

	            $index++;
			}

			echo Common_Export::exportCsvForNotKey($exportData);
			// unset($exportData);
			$exportData = array();
		}
		exit();
	}

	
	private function getElementCount($condition)
	{

		$count = Service_Product::getByCondition($condition , 'count(*)');

		$max = 1;
		$pagesize = 20;
		$pages = ceil($count / $pagesize);

		for ($page=1; $page <= $pages; $page++) {
		  $proudctRows = Service_Product::getByCondition($condition , ['hs_code'] , $pagesize ,$page);
		  foreach ($proudctRows as $key => $value) {
		    if($value['hs_code'] != ''){
		      $count = Service_HsElement::getByCondition(array( // 申报要素
		          'hs_code'   => $value['hs_code'],
		          'he_status' => 1,
		        ),'count(*)');
		      $max = $count > $max ? $count : $max;
		    }
		  }
		}
		return $max;
	}
	private function calc($size,$digits=2){
	  $unit= array('','K','M','G','T','P');
	  $base= 1024;
	  $i   = floor(log($size,$base));
	  $n   = count($unit);
	  if($i >= $n){
      $i=$n-1;
    	}
    	return round($size/pow($base,$i),$digits).' '.$unit[$i] . 'B';
	}
	private function getStatusText($status, $type) {
		$status = $status;
		$type = strtoupper($type);
		$text = array(
			'PT' => array( // 产品类型
				0 => '普通产品',
				1 => '组合产品',
			),
			'PS' => array( // 产品状态
				0 => '备案中',
				1 => '已备案',
				2 => '草稿',
			),
			'BARCODE' => array( // 条码类型
				0 => '默认条码',
				1 => '自定义条码',
				2 => '序列号',
			),
			'QC' => array( // 是否质检
				0 => '不质检',
				1 => '质检',
			),
			'PART' => array( // 是否零件
				0 => '否',
				1 => '是',
			),
			'INVOICE' => array( // 是否带发票
				1 => '有',
				2 => '无',
			),
			'UNIT' => array(
				'EA'   => '个',
				'KG'   => '公斤',
				'MT'   => '米',
				'CASE' => '盒',
				'PC'   => '件',
				'SET'  => '套',
			),
			'PRS' => array( // 产品接收类型
				0 => '新产品',
				1 => '已收过货产品',
			),
			'BATTERYTYPE' => array(
		        '1'=>"配置电池",
		        "2"=>"内置电池",
		        "3"=>"纽扣电池",
		        "4"=>"锂金属电池",
		        "0"=>"不带"
		    )
		);

		if ('UNIT' === $type && isset($this->productUnit[$status])) {
			return $this->productUnit[$status]['pu_name'];
		}
		elseif ('CATEGORY' === $type && isset($this->productCategory[$status])) {
			return $this->productCategory[$status]['pc_name'];
		}
		elseif (isset($text[$type][$status])) {
			return $text[$type][$status];
		}

		return '';
	}

}