<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 15-12-29
 * Time: 下午4:30
 * To change this template use File | Settings | File Templates.
 */
class Product_SendProductGoodsInfoController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "product/views/product/";
    }

    public function listAction() {
        $fmlState   =   array('-2'=>'发送失败' , '-1'=>'未提交' , '0'=>'未同步' ,'1'=>'已同步', '2'=>'备案成功', '3'=>'同步失败' , '4'=>'海关审核退单' , '5'=>'业务人员还未接单' , '6'=>'未知状态');
        $pgStatus   =   array('0'=>'未备案' , '1'=>'备案成功' , '2'=>'备案中' , '3'=>'备案失败','4'=>'备案不通过');

        if ($this->_request->isPost()) {
            $return = array(
                "state" => 0,
                "message" => "No Data"
            );
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $productSku       =   $this->_request->getParam('product_sku','');
            $goodsCode       =   $this->_request->getParam('goods_code','');
            $customer_code =   $this->_request->getParam('customer_code','');
            $pg_status =   $this->_request->getParam('pg_status','');
            $fml_status =   $this->_request->getParam('fml_status','');
            $hs_code = $this->_request->getParam('hs_code','');

            $condition =   array();
            $condition['product_sku']    =   $productSku;
            $condition['goods_code']    =   $goodsCode;
            $condition['pg_status']    =   $pg_status;
            $condition['fml_status']    =   $fml_status;
            $condition['customer_code'] =   $customer_code;
            $condition['hs_code'] =   $hs_code;
            /*if(isset($this->_userAuth->user['customer_code']) && $this->_userAuth->user['customer_code'] != ''){
                $condition['customer_code'] =  $this->_userAuth->user['customer_code'];
            }else{
                $condition['customer_code'] =   $customer_code;
            }*/
            $count =   Service_ProductGoods::getProductByCondition($condition, 'count(*)');

            if($count > 0)
            {
                $rows = Service_ProductGoods::getProductByCondition($condition, '*' , $pageSize , $page , 'pg_id DESC');
                foreach($rows as $key=>$value){
                    $where['product_id'] = $value['product_id'];
                    $list = Service_HsElementMap::listByWhere($where);
                    $elements = array();
                    foreach($list as $row) {
                        if( is_scalar( $row['hem_detail'] ) ) {
                            $tmpElement = trim($row['hem_detail']);
                            if( $tmpElement!=="" ) {
                                $elements[] = $tmpElement;
                            }
                        }
                    }
                    $rows[$key]['G_MODEL'] = implode('|', $elements);
                    $hsUomMap = Service_HsUomMap::getByField($value['product_id'],"product_id","*");
                    $rows[$key]['hum_quantity_law'] = $hsUomMap['hum_quantity_law'];
                    $rows[$key]['hum_quantity_second'] = $hsUomMap['hum_quantity_second'];
                    $hm = Service_HsUom::getByField($hsUomMap['hu_id'],'hu_id',"*");
                    $fproductUom = Service_ProductUom::getByField($hm['pu_code_law'],'pu_code',"*");
                    $rows[$key]['pu_name'] = $fproductUom['pu_name'];
                    $sproductUom = Service_ProductUom::getByField($hm['pu_code_second'],"pu_code","*");
                    $rows[$key]['pu_name_second'] = $sproductUom['pu_name'];
                    $product = Service_Product::getByField($value['product_id'],'product_id',"*");
                    $pum = Service_ProductUom::getByField($product['pu_code'],"pu_code","*");
                    $rows[$key]['unit'] = $pum['pu_name'];
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['fml_status']   =   $fmlState;
                $return['pg_status']    =   $pgStatus;
            }
            $return['total'] = $count;
            $return['size'] = $pageSize;
            $return['page'] = $page;
            die(Zend_Json::encode($return));
        }
        $this->view->pgStatus  =   $pgStatus;
        $this->view->fmlState  =   $fmlState;
        echo Ec::renderTpl($this->tplDirectory . "send_product_goods_info_index.tpl", 'layout');
    }
    
    public function beianNotpassAction(){
        $pgidArr = $this->_request->getParam("pgids","");
        $result = array(
            'ask'=>1,
            'msgArr'=>array(),
        );
        foreach($pgidArr as $v){
            $pgRow = Service_ProductGoods::getByField($v,"pg_id","*");
            if($pgRow['pg_status'] !=0){
                $result['msgArr'][] = "<font color='red'>料件号[".$pgRow['goods_code']."]不是处于未备案状态,不允许此操作</font>";
            }else{
                $updataPg = array(
                    'pg_status'=>4,
                );
                Service_ProductGoods::update($updataPg,$v,"pg_id");
                $result['msgArr'][] = "<font color='green'>料件号[".$pgRow['goods_code']."]已提交到备案不通过状态</font>";
            }
        }
        die(Zend_Json::encode($result));
    }

    public function beianAction(){
        $pgidArr = $this->_request->getParam("pgids","");
        $result = array(
            'ask'=>1,
            'msgArr'=>array(),
        );
        foreach($pgidArr as $v){
            $pgRow = Service_ProductGoods::getByField($v,"pg_id","*");
            $updataPg = array(
                'pg_status'=>2,
            );
            Service_ProductGoods::update($updataPg,$v,"pg_id");
            $result['msgArr'][] = "料件号[".$pgRow['goods_code']."]已提交到备案中状态";
        }
        die(Zend_Json::encode($result));
    }

    public function uploadTemplateAction(){
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH."/../data/xls".'/ljh-batchbeian.xls';
        //方法2
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        //     header("Content-Transfer-Encoding: binary");
        //     header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

    public function batchBeianAction(){
        $result = array("ask"=>1,'data'=>array());
        $xlsData = Service_Product::getXLSData($_FILES,'filename');
        if(count($xlsData[0])!=1||($xlsData[0][0]!="料件号")){
            $result['ask'] = "0";
            $result['error'] = "文件格式错误，首行不是按照料件号排列!";
            die(json_encode($result));
        }
        foreach($xlsData as $key=>$value){
            if($key==0) continue;
            $pgRow = Service_ProductGoods::getByField($value[0],"goods_code","*");
            if(empty($pgRow)){
                $data = array(
                    'ask'=>0,
                    'goods_code'=>$value[0],
                    'message'=>"第".($key+1)."行料件号[".$value[0]."]不存在!",
                );
                $result['data'][] = $data;
                continue;
            }else{
                if($pgRow['pg_status']!="0"){
                    $data = array(
                        'ask'=>0,
                        'goods_code'=>$value[0],
                        'message'=>"第".($key+1)."行料件号[".$value[0]."]不是未备案状态!",
                    );
                    $result['data'][] = $data;
                    continue;
                }else{
                    $updataPg = array(
                        'pg_status'=>2,
                    );
                    Service_ProductGoods::update($updataPg,$pgRow['pg_id'],"pg_id");
                    $data = array(
                        'ask'=>1,
                        'goods_code'=>$value[0],
                        'message'=>"第".($key+1)."行料件号[".$pgRow['goods_code']."]已提交到备案中状态",
                    );
                    $result['data'][] = $data;
                    //$result['msgArr'][] = "第".($key+1)."行料件号[".$pgRow['goods_code']."]已提交到备案中状态";
                }
            }
        }
        die(json_encode($result));
    }

    public function exportAction(){
        error_reporting(E_ERROR);
        set_time_limit(0);
        @ini_set('memory_limit','2048M');
        $filename = "goodsCode".date("YmdHis");
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->getDefaultStyle()->getFont()->setSize(10);
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("料件号");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('B')->setWidth(15);
        $objActSheet->getColumnDimension('C')->setWidth(15);
        $objActSheet->getColumnDimension('D')->setWidth(15);
        $objActSheet->getColumnDimension('E')->setWidth(15);
        $objActSheet->getColumnDimension('F')->setWidth(25);
        $objActSheet->getColumnDimension('G')->setWidth(10);
        $objActSheet->getColumnDimension('H')->setWidth(15);

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','产品sku');
        $objActSheet->setCellValue('C1','料件号');
        $objActSheet->setCellValue('D1','海关编码');
        $objActSheet->setCellValue("E1",'海关品名');
        $objActSheet->setCellValue('F1','海关申报要素');
        $objActSheet->setCellValue('G1','单位');
        $objActSheet->setCellValue('H1','法定单位');
        $params = $this->_request->getParams();
        $condition =   array();
        if($params['exportType'] == '1'){
            $condition['pg_id_array'] = $this->_request->getParam('pgids','');
        }else{
            $productSku       =   $this->_request->getParam('product_sku','');
            $goodsCode       =   $this->_request->getParam('goods_code','');
            $customer_code =   $this->_request->getParam('customer_code','');
            $pg_status =   $this->_request->getParam('pg_status','');
            $fml_status =   $this->_request->getParam('fml_status','');
            $hs_code = $this->_request->getParam('hs_code','');

            $condition['product_sku']    =   $productSku;
            $condition['goods_code']    =   $goodsCode;
            $condition['pg_status']    =   $pg_status;
            $condition['fml_status']    =   $fml_status;
            $condition['customer_code'] =   $customer_code;
            $condition['hs_code'] =   $hs_code;
        }
        $count =  Service_ProductGoods::getProductByCondition($condition, 'count(*)');
        $index = 2;
        if($count>0){
            $pageSize = 100;
            $totalPage = ceil($count/$pageSize);
            for($page=1;$page<=$totalPage;$page++){
                $rows = Service_ProductGoods::getProductByCondition($condition, '*' , $pageSize , $page , 'pg_id DESC');
                foreach($rows as $key=>$value){
                    $where['product_id'] = $value['product_id'];
                    $list = Service_HsElementMap::listByWhere($where);
                    $elements = array();
                    foreach($list as $row) {
                        $elements[] = $row['hem_detail'] ? trim($row['hem_detail']) : '';
                    }
                    $rows[$key]['G_MODEL'] = implode('|', $elements);
                    $hsUomMap = Service_HsUomMap::getByField($value['product_id'],"product_id","*");
                    $rows[$key]['hum_quantity_law'] = $hsUomMap['hum_quantity_law'];
                    $rows[$key]['hum_quantity_second'] = $hsUomMap['hum_quantity_second'];
                    if(!empty($hsUomMap)){
                        $hm = Service_HsUom::getByField($hsUomMap['hu_id'],'hu_id',"*");
                        $fproductUom = Service_ProductUom::getByField($hm['pu_code_law'],'pu_code',"*");
                        $rows[$key]['pu_name'] = $fproductUom['pu_name'];
                        $sproductUom = Service_ProductUom::getByField($hm['pu_code_second'],"pu_code","*");
                        $rows[$key]['pu_name_second'] = $sproductUom['pu_name'];
                    }

                    $objActSheet->setCellValue('A'.$index,$value['customer_code']);
                    $objActSheet->setCellValueExplicit('B'.$index,$value['product_sku'],PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit('C'.$index,$value['goods_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit('D'.$index,$value['hs_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValue("E".$index,$value['hs_goods_name']);
                    $objActSheet->setCellValue('F'.$index,$rows[$key]['G_MODEL']);
                    $lawquantity = "第一:".$rows[$key]['hum_quantity_law']." ".$rows[$key]['pu_name'];
                    if($rows[$key]['hum_quantity_second']!=""&&$rows[$key]['hum_quantity_second']!="0"){
                        $lawquantity.="  \r\n第二:".$rows[$key]['hum_quantity_second']." ".$rows[$key]['pu_name_second'];
                    }
                    $product = Service_Product::getByField($value['product_id'],'product_id',"*");
                    $pum = Service_ProductUom::getByField($product['pu_code'],"pu_code","*");
                    $objActSheet->setCellValue('G'.$index,$pum['pu_name']);
                    $objActSheet->setCellValue('H'.$index,$lawquantity);
                    $index++;
                }
            }
        }
        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=Manifest.xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=gb2312");
        $objWriter->save('php://output');
    }
}
