<?php
class Warehouse_FrozenInventoryController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "warehouse/views/frozen_inventory/";
        $this->serviceClass = new Service_Warehouse();
    }
	
    /**
     * [listAction description]
     * @return [type] [description]
     */
    public function listAction()
    {
        $countryArray = Common_DataCache::getCountry();
        $statusArray = Common_Type::status('auto');
        if ($this->_request->isPost()) {
            $return = array(
                "state" => 0,
                "message" => "No Data"
            );
            $customerCode = $this->_request->getParam('customer_code', '');
            if(empty($customerCode)){
                $return['message'] = '请输入客户代码。';
                die(Zend_Json::encode($return));
            }
            $isFrozen = $this->_request->getParam('is_frozen', 0);
            $condition = array(
                'customer_code' => $customerCode,
                'is_frozen' => $isFrozen,
            );
            $count = Service_Customer::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count) {
                $rows = Service_Customer::getByCondition($condition, array('customer_id', 'customer_code', 'is_frozen', 'customer_status'), 0, 1);
                //print_r($rows);
                foreach ($rows as $key => $val) {
                    //可用库存量
                    $inventory_data = Service_ProductInventory::getBycondition(array('customer_id'=>$val['customer_id']), array('pi_sellable', 'product_id'));
                    $inventory_sum = $inventory_value = 0;
                    if(!empty($inventory_data) && is_array($inventory_data)){
                        foreach ($inventory_data as $inventory_row) {
                            $inventory_sum += $inventory_row['pi_sellable'];
                            $product_row = Service_Product::getByField($inventory_row['product_id'], 'product_id', array('product_declared_value'));
                            $inventory_value += $inventory_row['pi_sellable'] * $product_row['product_declared_value'];
                        }
                    }
                    //冻结客户
                    if($val['is_frozen']){
                        $rows[$key]['is_frozen_text'] = '是';
                        //可用库存量
                        $rows[$key]['inventory_sum'] = 0;
                        //风控冻结库存量
                        $rows[$key]['fk_inventory_sum'] = $inventory_sum;
                        //库存货值
                        $rows[$key]['inventory_value'] = $inventory_value;
                    //非冻结客户                        
                    }else {
                        $rows[$key]['is_frozen_text'] = '否';
                        $rows[$key]['inventory_sum'] = $inventory_sum;
                        //风控冻结库存量
                        $rows[$key]['fk_inventory_sum'] = 0;
                        //库存货值
                        $rows[$key]['inventory_value'] = $inventory_value;
                    }
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $language = Ec::getLang();
        $this->view->countryArray = $countryArray;
        $this->view->statusArr = Common_Type::status($language);
        echo Ec::renderTpl($this->tplDirectory . "index.tpl", 'layout');
    }

    /**
     * [editAction description]
     * @return [type] [description]
     */
    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage' => array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(

                'warehouse_id' => '',
                'warehouse_code' => '',
                'warehouse_status' => '',
                'country_id' => '',
                'state' => '',
                'city' => '',
                'contacter' => '',
                'phone_no' => '',
                'street_address1' => '',
                'street_address2' => '',
                'warehouse_desc' => '',
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            $paramId = $row['warehouse_id'];
            if (!empty($row['warehouse_id'])) {
                unset($row['warehouse_id']);
            }
            $errorArr = $this->serviceClass->validator($row);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message' => '',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }

            if (!empty($paramId)) {
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }

        }
        die(Zend_Json::encode($return));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'warehouse_id')) {
            $rows = $this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }
    
    /**
     * [frozenCustomerAction 冻结客户]
     * @return [type] [description]
     */
    function frozenCustomerAction(){
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $customer_id = $this->_request->getPost('customer_id', '');
            $is_frozen = $this->_request->getPost('frozen', 0);
            $frozen_reason =  $this->_request->getPost('frozen_reason', '');
            if(!empty($customer_id)){
                $db = Service_Customer::getModelInstance()->getAdapter();
                $db->beginTransaction();
                try {
                    $customerData = Service_Customer::getByField($customer_id, 'customer_id', array('customer_code'));
                    if(empty($customerData)){
                        throw new Exception('客户不存在');
                    }
                    if(Service_Customer::update(array('is_frozen' => $is_frozen, 'frozen_reason'=>$frozen_reason, 'customer_update_time' => date('Y-m-d H:i:s')), $customer_id, 'customer_id') === false){
                        throw new Exception('客户['.$customerData['customer_code'].']冻结状态更新失败');
                    }
                    if($is_frozen){
                        $cl_note = '客户冻结，冻结原因:'.$frozen_reason;
                    }else {
                        $cl_note = '客户解冻，解冻原因:'.$frozen_reason;
                    }
                    $customerLogRow = array(
                        'cl_customer_id' => $customer_id,
                        'cl_customer_code' => $customerData['customer_code'],
                        'cl_user_id' => $this->_userAuth->userId,
                        'cl_ip' => Common_Common::getRealIp(),
                        'cl_note' => $cl_note,
                        'cl_add_time' => date('Y-m-d H:i:s'),
                        'cl_update_time' => date('Y-m-d H:i:s')
                    );
                    if(Service_CustomerLog::add($customerLogRow) === false ){
                        throw new Exception('客户['.$customerData['customer_code'].']日志写入异常');
                    }
                    $db->commit();
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }catch (Exception $e){
                    $db->rollBack();
                    $result['message'] = $e->getMessage();
                }
            }
        }
        die(Zend_Json::encode($result));
    }
    
}
