<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 16-10-19
 * Time: 下午5:50
 * To change this template use File | Settings | File Templates.
 */
class Product_ProductInfoController  extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "product/views/product/";
        $this->serviceClass = new Service_Product();
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $this->user_id = $userAuth->userId;
    }

    public function listAction(){
        $status=Service_ProductProcess::getProductStatus();
        $receiving=Service_ProductProcess::getProductReceivingStatus();
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
            $isSellable = trim($this->_request->getParam('pi_sellable', ''));
            $warehoseId = trim($this->_request->getParam('warehouse_id', ''));

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();
         

            $condition = $this->serviceClass->getMatchFields($params);

            if ('largeZero' === $isSellable && '' !== $warehoseId) {
                $condition['pi_sellable'] = 'largeZero';
                $condition['warehouse_id'] = $warehoseId;
            }
            $condition['dateFor'] = isset($params['dateFor'])?$params['dateFor']:'';
            $condition['dateTo'] = isset($params['dateTo'])?$params['dateTo']:'';
            $user = Service_User::getByField($this->user_id,"user_id","*");
            if($user['customer_code']!=""){
                $customerCodeArr = explode(";",$user['customer_code']);
                $condition['customerCodeArr'] = $customerCodeArr;
            }
            //echo "<pre>";
            //var_dump($condition);
            //echo "</pre>";
            $count = $this->serviceClass->getAllByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    'product_sku',
                    'customer_code',
                    'product_title_en',
                    'product_title',
                    'product_status',
                    'product_receive_status',
                    'product_weight',
                    'pc_id',
                    'product_id',
                    'pce_title',
                    'product_category_ebay.pce_title',
                    'product_barcode',
                    'customer_id',
                    'product_type',
                    'goods_id',
                    'hs_code',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);

                $rows = $this->serviceClass->getAllByCondition($condition,$showFields, $pageSize, $page, array('product.product_id desc'));
                foreach($rows as $key=>$value){
                    if($value['E3']==""){
                        $customer = Service_Customer::getByField($value['E4'],'customer_id',"*");
                        $rows[$key]['E3'] = $customer['customer_code'];
                    }
                    $productCategory = Service_ProductCategory::getByField($value['E21'],'pc_id',"*");
                    $rows[$key]['pc_name'] = isset($productCategory['pc_name'])?$productCategory['pc_name']:"";
                }
                //print_r($rows);die();
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['status'] = $status;
                $return['receiving'] = $receiving;
                $return['message'] = "";
                $userRight = Service_UserRight::getByField("/product/product/beian","ur_url","*");
                $urmCondition = array(
                    'ur_id'=>$userRight['ur_id'],
                    'user_id'=>$this->user_id
                );
                $userRightMap = Service_UserRightMap::getByCondition($urmCondition,"count(*)");
              
                if($userRightMap){
                    $return['beianAuth'] = 1;
                }else{
                    $return['beianAuth'] = 0;
                }
            }
            die(Zend_Json::encode($return));
        }
        //var_dump($return);die;
        $this->view->status=$status;
        $this->view->receiving=$receiving;
        echo Ec::renderTpl($this->tplDirectory . "product_info_index.tpl", 'layout');
    }

    /*产品详细*/
    public function detailAction(){
        $skuid = $this->_request->getParam("skuid","");
        $productRow= $this->serviceClass->getByField($skuid, 'product_id');
        //$pUm = Service_ProductUom::getByField($productRow['pu_code'],'pu_code',"*");
        $productCategory  = Service_ProductCategory::getByField($productRow['pc_id'],'pc_id',"*");
        $productRow['pc_name'] = $productCategory['pc_name'];
        // $country = Service_Country::getByField($productRow['country_code_of_origin'],"country_code","*");
        // $productRow['country_name'] = $country['country_name'];
        //$productRow['pu_name'] = $pUm['pu_name'];
        if(empty($productRow['pu_code'])){ $productRow['pu_code'] = '007';}
        if($productRow['pu_code']){
            $pUm = Service_ProductUom::getByField($productRow['pu_code'],'pu_code',"*");
            $productRow['pu_name'] = $pUm['pu_name'];
        }else{
            $productRow['pu_name'] = "";
        }

        // 供应商信息
        if ($productRow['distributor_id']) {
            $productRow['distributor'] = Service_Distributor::getByPrimaryKey($productRow['distributor_id']);
        }

        $this->view->product = $productRow;//产品日记
        $logService = new Service_ProductLog();
        $logs = $logService->getByCondition(array('product_id'=>$skuid),"*");
        foreach($logs as $key=>$value){
            $customerService = new Service_Customer();
            $c = $customerService->getByField($value['customer_id'],"customer_id","*");
            $logs[$key]['customer_code'] = $c['customer_code'];
            if($value['user_id']=="-1"){
                if($value['account_id']=="0"){
                    $logs[$key]['operater'] = $c['customer_code'];
                }else{
                    $account = Service_Account::getByField($value['account_id'],"account_id","*");
                    $logs[$key]['operater'] = $account['account_name'];
                }
            }else{
                $user = Service_User::getByField($value['user_id'],'user_id',"*");
                $logs[$key]['operater'] = $user['user_name'];
            }
        }
        $this->view->logs = $logs;//产品日记

        $productInventory = new Service_ProductInventory();
        $inventory = $productInventory->getByCondition(array('product_id'=>$skuid),"*");
        foreach($inventory as $key=>$value){
            $warehouse = new Service_Warehouse();
            $w = $warehouse->getByField($value['warehouse_id'],"warehouse_id","*");
            $inventory[$key]['warehouse_code'] = $w['warehouse_code'];
        }
        $this->view->productInventory = $inventory;//产品库存

        $opService = new Service_OrderProduct();
        $orderProduct = $opService->getByCondition(array('product_id'=>$skuid),"*");
        $this->view->orderProduct = $orderProduct;//产品订单

        $oaService = new Service_ReceivingDetail();
        $productAsn = $oaService->getByCondition(array('product_id'=>$skuid),"*");
        $this->view->productAsn = $productAsn;//产品ASN
        $swapOrderDetail=new Service_SwapOrderDetail();
        $swapOrderout = $swapOrderDetail->getByCondition(array('product_id'=>$skuid),"*");
        $swapOrderin = Service_SwapOrderDetail::getByCondition(array('to_product_id'=>$skuid),"*");
        $this->view->swapOrderout = $swapOrderout;//易货单
        $this->view->swapOrderin = $swapOrderin;
        $inventoryBatchService = new Service_InventoryBatch();
        $inventoryBatchList = $inventoryBatchService->getByCondition(array('product_id'=>$skuid),"*");
        $this->view->inventoryBatchList = $inventoryBatchList;//产品批次库存

        $hsElementMap = Service_HsElementMap::getByCondition(array('product_id'=>$skuid),"*");
        if(!empty($hsElementMap)){
            foreach($hsElementMap as $k=>$v){
                $HE = Service_HsElement::getByField($v['he_id'],"he_id","*");
                $hsElementMap[$k]['HE'] = $HE;
                $HUM = Service_HsUomMap::getByField($v['product_id'],"product_id","*");
                $hsElementMap[$k]['HUM'] = $HUM;
                $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                $productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                $HU['pu_name'] = $productUom['pu_name'];
                $productUomSecond = Service_ProductUom::getByField($HU['pu_code_second'],"pu_code","*");
                $HU['pu_name_second'] = $productUomSecond['pu_name'];
                $hsElementMap[$k]['HU'] = $HU;
            }
        }else{
            $row = array();
            $HUM = Service_HsUomMap::getByField($skuid,"product_id","*");
            if($HUM){
                $row['HUM'] =  $HUM;
                $row['HE']['hs_code'] =  $productRow['hs_code'];
                $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                $productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                $HU['pu_name'] = $productUom['pu_name'];
                $productUomSecond = Service_ProductUom::getByField($HU['pu_code_second'],"pu_code","*");
                $HU['pu_name_second'] = $productUomSecond['pu_name'];
                $row['HU'] = $HU;

            }

            $hsElementMap[] = $row;
        }
        $userRight = Service_UserRight::getByField("/product/product/change","ur_url","*");
        $urmCondition = array(
            'ur_id'=>$userRight['ur_id'],
            'user_id'=>$this->user_id
        );
        $userRightMap = Service_UserRightMap::getByCondition($urmCondition,"count(*)");
        $userEditPg = Service_UserRight::getByField("/product/product/editpg","ur_url","*");
        $this->view->userEditPg = Service_UserRightMap::getByCondition(array( 'ur_id'=>$userEditPg['ur_id'],),"count(*)");
        $this->view->changeAuth = $userRightMap;
        $this->view->hsElementMap = $hsElementMap;

        echo Ec::renderTpl($this->tplDirectory . "product-detail-finance.tpl", 'layout');
    }

    public function exportProductAction() {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $file   = 'product-' . date('YmdHis');
        /*header('Content-Type: application/vnd.ms-excel;charset=gbk');
        header("Content-Disposition: attachment;filename={$file}");
        header('Cache-Control: max-age=0');*/
        require_once("PHPExcel.php");
        require_once("PHPExcel/Reader/Excel2007.php");
        require_once("PHPExcel/Reader/Excel5.php");
        require_once ('PHPExcel/IOFactory.php');

        $objExcel = new PHPExcel();
        $objProps = $objExcel->getProperties();
        $objProps->setCreator('EC');
        $objProps->setTitle('Template');
        $objExcel->setActiveSheetIndex(0);

        $objActSheet = $objExcel->getActiveSheet();

        $objActSheet->getColumnDimension('A')->setWidth(25);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(25);
        $objActSheet->getColumnDimension('E')->setWidth(10);
        $objActSheet->getColumnDimension('F')->setWidth(10);
        $objActSheet->getColumnDimension('G')->setWidth(10);

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','产品SKU');
        $objActSheet->setCellValue('C1','产品条码');
        $objActSheet->setCellValue('D1','产品名称');
        $objActSheet->setCellValue("E1",'申报价值');
        $objActSheet->setCellValue('F1','申报币种');
        $objActSheet->setCellValue('G1','可用数量');


        //$exportData[0] = array('客户代码','产品SKU','产品条码','产品名称','申报价值','申报币种','可用数量');

        $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'])  : '';


            $condition     = array(
                'product_type' => '0', // 只能导出普通产品
            );

            if ('' !== $productSku) {
                $condition['product_sku'] = $productSku;
            }

            if ('' !== $customerCode) {
                $condition['customer_code'] = $customerCode;
            }

            if ('' !== $productBracode) {
                $condition['product_barcode'] = (string) $productBracode;
            }

            $condition['dateFor'] = isset($params["dateFor"])? trim($params['dateFor']):"";
            $condition['dateTo'] = isset($params["dateTo"])? trim($params['dateTo']):"";
            $user = Service_User::getByField($this->user_id,"user_id","*");
            if($user['customer_code']!=""){
                $customerCodeArr = explode(";",$user['customer_code']);
                $condition['customerCodeArr'] = $customerCodeArr;
            }
        }else{
            if ($params['pid']) {
                $condition['product_id_array'] = explode('|', $params['pid']);
            }else{
                //echo Common_Export::exportCsvForNotKey($exportData);
                die("无数据");
            }
        }


        $count = Service_Product::getByCondition($condition , 'count(*)');
        if(!$count){
            //echo Common_Export::exportCsvForNotKey($exportData);
            die("无数据");
        }
        $index = 1;
        $pagesize = 20;
        $pages = ceil($count / $pagesize);

        $index = 2;
        for ($page=1; $page <= $pages; $page++) {
            $proudctRows = Service_Product::getByCondition($condition , '*' , $pagesize ,$page);
            foreach ($proudctRows as $key => $value) {
                $pi = Service_ProductInventory::getByField($value['product_id'],"product_id","*");
                $piSellable = isset($pi['pi_sellable'])?$pi['pi_sellable']:"0";

                $exportData[$index]	=	array( $value['customer_code'] , $value['product_sku'], $value['product_barcode'] , $value['product_title'] , $value['product_declared_value'] , $value['currency_code'] ,$piSellable);

                $objActSheet->setCellValue('A'.$index,$value['customer_code']);
                $objActSheet->setCellValueExplicit('B'.$index,$value['product_sku'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit('C'.$index,$value['product_barcode'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValue('D'.$index, $value['product_title']);
                $objActSheet->setCellValue("E".$index,$value['product_declared_value']);
                $objActSheet->setCellValue('F'.$index,$value['currency_code']);
                $objActSheet->setCellValue('G'.$index,$piSellable);

                $index++;
            }

        }

        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="' . $file . '.xls');
        header("Content-Disposition:inline;filename=" . $file . '.xls');
        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
        $objWriter->save('php://output');

    }

}
