<?php

/**
 * Class Shipment_CustomController
 * 清关数据处理
 */
require_once 'PHPExcel.php';
require_once "PHPExcel/IOFactory.php";
class Clearance_RecordController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "clearance/views/record/";
    }
    public function getCondition(){
        $dateFor = $this->_request->getParam('dateFor', "");
        $dateTo = $this->_request->getParam('dateTo', "");
        $timeType = $this->_request->getParam('timeType', '');
        $params = $this->_request->getParams();
        Common_Common::trim_blank($params);
        $serviceClass = new Service_BillBook();
        $condition = $serviceClass->getMatchFields($params);
        if ($timeType !== '') {
            switch ($timeType) {
                case '0':
                    $condition['bill_time_from'] = $dateFor;
                    $condition['bill_time_to'] = $dateTo;
                    break;
                case '1':
                    $condition['add_time_from'] = $dateFor;
                    $condition['add_time_to'] = $dateTo;
                    break;
                default:
                    break;
            }
        }
        $idArray = array();
        if (!empty($params['product_sku'])) {
            $billBookProduct = Service_BillBookProduct::getByCondition(array('product_sku' => $params['product_sku']));
            if (!empty($billBookProduct)) {
                foreach ($billBookProduct as $bp) {
                    $idArray[] = $bp['bill_book_id'];
                }
            } else {
                $idArray[] = '-1';
            }
        }
        if(!empty($params['product_sku_batch'])){
            $batchList = array_unique(array_filter(preg_split("/\r\n|\r|,/",$params['product_sku_batch'])));
            $billBookProduct = Service_BillBookProduct::getByCondition(array('product_sku_in' =>$batchList));
            if (!empty($billBookProduct)) {
                foreach ($billBookProduct as $bp) {
                    $idArray[] = $bp['bill_book_id'];
                }
            } else {
                $idArray[] = '-1';
            }
        }
        if(!empty($params['recode_no_batch'])){
            $recodeNoList  = array_unique(array_filter(preg_split("/\r\n|\r|,/",$params['recode_no_batch'])));
            $condition['recorde_no_list'] = $recodeNoList;

        }
        $condition['id_array'] = $idArray;
        return $condition;
    }
    /**
     * Note:
     * User: Yao
     * Date: 2018/12/20
     * Time: 11:23
     */
    public function listAction()
    {

        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data",
                'status'=>Service_BillBook::getState(),
            );
            $condition = $this->getCondition();
            $serviceClass = new Service_BillBook();
            $count = Service_BillBook::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count) {
                $showFields = array(
                    'id',
                    'warehous_account_no',
                    'recorde_no',
                    'product_title',
                    'hs_code',
                    'specification',
                    'country_code',
                    'decalare_unit',
                    'in_quantity',
                    'stock_quantity',
                    'ie_port',
                    'bill_time',
                    'goods_code',
                    'add_time',
                    'can_use_quantity',
                    'frozen_quantity',
                    'lock_quantity',
                    'ie_port',
                    'state',
                );
                $showFields = $serviceClass->getFieldsAlias($showFields);
                $rows = Service_BillBook::getByCondition($condition, $showFields, $pageSize, $page, array('id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . 'list.tpl', 'layout');
    }

    /**
     * Note:账册导入
     * User: Yao
     * Date: 2018/12/20
     * Time: 15:21
     */
    public function importAction()
    {
        set_time_limit(3600);
        // error_reporting(E_ALL);
        $return = array(
            'state' => '0',
            'data' => '',
            'message' => '上传文件失败失败',
            'error' => array(),
            'error_file'=>'',
        );
        if ($this->_request->isPost()) {
            $field = 'uploadfilename';
            $user = $this->_userAuth;
            $userId = $user->userId;
            $path = APPLICATION_PATH . '/../data/customUpload/';
            $path .= $userId;
            if (!file_exists($path)) {
                if (!mkdir($path, 0700, true)) {
                    $return['error'] = array('上传目录不存在创建文件目录失败');
                    die(json_encode($return));
                }
            }
            $config = array();
            $config['upload_path'] = $path;
            $config['allowed_types'] = 'xls|xlsx|csv';
            $config['max_size'] = '4000';
            $config['encrypt_name'] = true;
            $upload = new Common_UploadFile($config);
            $upload->set_upload_path($path);
            if (!$upload->do_upload($_FILES, $field)) {
                $return['error'] = array($upload->display_errors());
                die(json_encode($return));
            }
            $resultArray = $upload->data();
            $full_path = $resultArray['full_path'];
            if (empty($resultArray) || empty($full_path)) {
                $return['error'] = array('数据不存在');
                die(json_encode($return));
            }
            $tile = array(
                '仓库账册号' => 'warehous_account_no',
                '备案号' => 'recorde_no',
                '商品料号' => 'goods_code',
                '商品名称' => 'product_title',
                // 'SKU' => 'product_sku',
                // '系统料件号' => 'sys_goods_code',
                '商品编码' => 'hs_code',
                '商品规格型号' => 'specification',
                '国别代码' => 'country_code',
                '库存' => 'stock_quantity',
                '申报计量单位' => 'decalare_unit',
                '法定计量单位' => 'legal_unit',
                '第二法定计量单位' => 'second_legal_unit',
                '申报单价金额' => 'decalar_price',
                '申报币制代码' => 'decalar_currency',
                '平均美元单价' => 'avg_dollar_price',
                '库存美元总价' => 'total_dollar_price',
                '入仓数量' => 'in_quantity',
                '入仓法定数量' => 'in_legal_quantity',
                '第二入仓法定数量' => 'in_seconde_legal_quantity',
                '实增数量' => 'real_increa_quantity',
                '实减数量' => 'real_reduce_quantity',
                '预增数量' => 'pre_increa_quantity',
                '预减数量' => 'pre_reduce_quantity',
                '存储(监管）期限' => 'storage_date',
                '记账清单编号' => 'bill_no',
                '记账清单商品序号' => 'bill_serial',
                // '进出标志' => 'ie_port',
                '记账时间' => 'bill_time',
                '报关单编号' => 'custom_code',
                '总价' => 'total_price',
                '最终目的国'=>'aim_country',
                '生产销售单位名称'=>'product_seller',
            );
            $data = Common_Upload::readXlsFromTitle($full_path, $tile, true);
            if (empty($data)) {
                $return['error'] = array('上传文件数据为空或者格式错误');
                die(json_encode($return));
            }

            //读的数据是从第二行开始
            $checkData = $data[2];
            foreach ($tile as $key => $value) {
                if (!isset($checkData[$value])) {
                    $return['error'][] = $key . '列不存在，请检查模板是否正确';
                }
            }
            if (count($data) > 5000) {
                $return['error'][] = '上传文件行数大于5000行，请分多次上传';
            }
            if (!empty($return['error'])) {
                die(json_encode($return));
            }
            $inserRow = array();
            $insertBillProduct = array();
            $sysTime = date('Y-m-d H:i:s');
            $ip = Common_Common::getRealIp();
            $failInfo = array();
            foreach ($data as $key => $row) {
                if(isset($error) && !empty($error)){
                    $failInfo[$key-1]='第 '.($key-1).'行错误信息：'.implode(',',$error);
                }
                $error = array();
                if (empty($row['warehous_account_no'])) {
                    $error[] = '仓库账册号为空';
                    continue;
                }
                if (empty($row['goods_code'])) {
                    $error[] = $key . '商品料号为空';
                    continue;
                }
                if (empty($row['recorde_no'])) {
                    $error[] = '备案号为空';
                    continue;
                }
                $customInventroy = Service_BillBook::getByCondition(
                    array(
                        'warehous_account_no' => $row['warehous_account_no'],
                        'recorde_no' => $row['recorde_no'],
                        // 'product_title' => trim($row['product_title']),
                        // 'hs_code' => $row['hs_code'],
                        // 'country_code' => $row['country_code'],
                        // 'specification' => $row['specification'],
                        // 'decalare_unit' => $row['decalare_unit']
                    ),
                    '*', 1, 1
                );
                $row = $this->changeChineseToCode($row);
                $oneRow = $row;
                $oneRow['json_row'] = json_encode($oneRow);
                if ($customInventroy) {
                    $oneRow['id'] = $customInventroy[0]['id'];
                    $oneRow['json_row_before'] = $customInventroy[0]['json_row'];
                    $error[] ='账册号系统已存在,不能上传，只能核增，核减库存';
                }
                unset($oneRow['sys_goods_code']);
                $oneRow['add_time'] = $sysTime;
                $inserRow[$key] = $oneRow;
                $productRow = array();
                if ($row['sys_goods_code']) {
                    $sysGoodsCodeError = false;
                    $sysGoodCodeList = preg_split('/[，,]/', $row['sys_goods_code']);
                    $sysGoodCodeList = array_filter($sysGoodCodeList);
                    if (empty($sysGoodCodeList)) {
                        $sysGoodCodeList = array();
                    }
                    foreach ($sysGoodCodeList as $sycode) {
                        $productRow = Service_Product::getByField(trim($sycode), 'goods_id');
                        if (empty($productRow)) {
                            $sysGoodsCodeError = true;
                            $error[] =  '行料件号' . $sycode . '系统不存在';
                            continue;
                        }
                        $errorMessage = Service_BillBook::validatorBookAndProduct($productRow, $row);
                        if (!empty($errorMessage)) {
                            $error[] = implode(',', $errorMessage);
                        }
                        if (!empty($oneRow['id'])) {
                            $billProduct = Service_BillBookProduct::getByCondition(array(
                                'bill_book_id' => $oneRow['id'],
                                'product_id' => $productRow['product_id']
                            ));
                            if (!$billProduct) {
                                $biilProuduct = array(
                                    'product_sku' => $productRow['product_sku'],
                                    'product_id' => $productRow['product_id'],
                                    'customer_code' => $productRow['customer_code'],
                                    'add_time' => $sysTime,
                                );
                                $insertBillProduct[$key][] = $biilProuduct;
                            }
                        } else {
                            $biilProuduct = array(
                                'product_sku' => $productRow['product_sku'],
                                'product_id' => $productRow['product_id'],
                                'customer_code' => $productRow['customer_code'],
                                'add_time' => $sysTime,
                            );
                            $insertBillProduct[$key][] = $biilProuduct;
                        }
                    }
                    if ($sysGoodsCodeError) {
                        continue;
                    }
                } else {
                    $productRow = Service_Product::getByField($row['goods_code'], 'goods_id');
                    // if(empty($productRow)){
                    //     if($row['ie_port'] == 'I') {
                    //         $error[] = $key . '行海关料件号系统不存在，请提供系统料件号';
                    //         continue;
                    //     }
                    // }
                    if (!empty($productRow)) {
                        $errorMessage = Service_BillBook::validatorBookAndProduct($productRow, $row);
                        if (!empty($errorMessage)) {
                            $error[] = implode(',', $errorMessage);
                        }
                    }else{
                        // $error[] = "料号".$row['goods_code'].'系统不存在此商品';
                    }
                    if (!empty($oneRow['id'])) {
                        $billProduct = Service_BillBookProduct::getByCondition(array(
                            'bill_book_id' => $oneRow['id'],
                            'product_id' => $productRow['product_id']
                        ));
                        if (!$billProduct && !empty($productRow)) {
                            $biilProuduct = array(
                                'product_sku' => $productRow['product_sku'],
                                'product_id' => $productRow['product_id'],
                                'customer_code' => $productRow['customer_code'],
                                'add_time' => $sysTime,
                            );
                            $insertBillProduct[$key][] = $biilProuduct;
                        }
                    } else {
                        if (!empty($productRow)) {
                            $biilProuduct = array(
                                'product_sku' => $productRow['product_sku'],
                                'product_id' => $productRow['product_id'],
                                'customer_code' => $productRow['customer_code'],
                                'add_time' => $sysTime,
                            );
                            $insertBillProduct[$key][] = $biilProuduct;
                        }
                    }
                }
            }
            if(!empty($error)){
                $failInfo[$key] = '第'.($key+1).'行错误信息：'.implode($error);
            }
            if (!empty($failInfo)) {
                $return['error'] = $failInfo;
                $phpExcel = PHPExcel_IOFactory::load($full_path);
                $sheet = $phpExcel->getSheet(0);
                $sheet ->setCellValue('AF1','错误信息');
                $sheet ->setCellValue('AG1','客户代码');
                foreach($failInfo as $key=>$error){
                    $sheet ->setCellValue('AF'.$key,$error);
                    if($insertBillProduct[$key]){
                        $customerCode = array();
                        foreach($insertBillProduct[$key] as $billProduct){
                            $customerCode[]=$billProduct['customer_code'];
                        }
                        $sheet ->setCellValue('AG'.$key,implode(',',$customerCode));
                    }
                }
                $savePath = $path.'/recode_result'.date('Ymdhis').rand(10,99).'.xls';
                $writer = PHPExcel_IOFactory::createWriter($phpExcel,'Excel5');
                $writer->save($savePath);
                $return['error_file'] = basename($savePath);
                die(json_encode($return));
            }
            $db = Zend_Registry::get('db');
            $db->beginTransaction();
            try {
                $log = array(
                    'sys_add_time' => $sysTime,
                    'operator_ip' => $ip,
                    'operator_id' => $userId,
                );
                foreach ($inserRow as $key => $row) {
                    if (isset($row['id'])) {
                        // $lastId = $row['id'];
                        // $log['operate_type'] = '1';
                        // $log['json_row_before'] = $row['json_row_before'];
                        //
                        // unset($row['json_row_before']);
                        // $d = Service_BillBook::update($row, $row['id']);
                    } else {
                        $log['operate_type'] = '-1';
                        $log['json_row_before'] = '';
                        $row['can_use_quantity'] = $row['stock_quantity'];
                        $lastId = Service_BillBook::add($row);
                        Service_BillStockLog::add([
                            'warehous_account_no'=>$row['warehous_account_no'],
                            'recode_no'=>$row['recorde_no'],
                            'incre_quantity'=>$row['stock_quantity'],
                            'reference_no'=>'',
                            'add_time'=>date("Y-m-d H:i:s"),
                            'note'=>'添加新账册,核增库存',
                        ]);
                    }
                    $log['goods_id'] = $row['goods_code'];
                    $log['bill_book_id'] = $lastId;
                    $log['json_row'] = $row['json_row'];
                    if (isset($insertBillProduct[$key])) {
                        foreach ($insertBillProduct[$key] as $inp) {
                            $inp['bill_book_id'] = $lastId;
                            Service_BillBookProduct::add($inp);
                        }
                    }
                    Service_BillBookLog::add($log);
                }
                $db->commit();
                $return['state'] = 1;
                $return['message'] = '上传成功';
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(json_encode($return));
        }
    }
    /**
     * Note:库存核增核减
     * User: Yao
     * Date: 2020/8/5
     * Time: 10:09
     */
    public function importBillStockAction(){
            $path = APPLICATION_PATH.'/../data/bill-stock';
            $return = [
                'state'=>'0',
                'message'=>'fail',
                'error'=>[],
                'data'=>[],
            ];
            try{
                $upload = new Process_Upload();
                $result = $upload->uploadXls($path,'bill_stock_file');
                if($result['state']!=1){
                    throw new Exception($result['message']);
                }
                $filePatch = $result['path'];
                $title =[
                    '仓库账册号'=>'warehouse_account',
                    '账册备案序号'=>'record_no',
                    '核增可用数量'=>'incre_quantity',
                    '核减可用数量'=>'reduce_quantity',
                    '锁定库存数量'=>'lock_quantity',
                    '解锁库存数量'=>'unlock_quantity',
                    '备注'=>'note',
                    '关联单号'=>'reference_no',
                ];
                $data = Common_Upload::readXlsFromTitle($filePatch,$title);
                $errorInfo = [];
                foreach ($data as $key=>$value){
                    $err = Service_BillBook::validateBillStock($value);
                    if(!empty($err)){
                        $errorInfo[]="第".$key.'行错误'.implode(',',$err);
                    }
                }
                if(!empty($errorInfo)){
                    $return['error'] = $errorInfo;
                    throw new Exception('上传失败');
                }
                $saveError = [];
                $billStock = new Process_BillBook();
                $success = 0;
                $total = 0;
                foreach ($data as $key=>$value) {
                    $total ++;
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try{
                        $billBook = Service_BillBook::getByCondition([
                            'recorde_no'=>$value['record_no'],
                            'warehous_account_no'=>$value['warehouse_account']
                        ]);
                        if(empty($billBook)){
                            throw new Exception('账册号不存在');
                        }
                        if(count($billBook)>1){
                            throw new Exception('账册备案序号有多个');
                        }
                        $billStock->setBillBookFromId($billBook[0]['id'])->setNote($value['note'])->setReferenceNo($value['reference_no']);
                        if($value['incre_quantity']){
                             $billStock->increQuanity($value['incre_quantity']);
                        }elseif($value['reduce_quantity']){
                            $billStock->reduceQuanity($value['reduce_quantity']);
                        }elseif ($value['lock_quantity']){
                            if($value['lock_quantity'] == 'ALL'){
                                $value['lock_quantity'] = $billBook[0]['can_use_quantity'];
                                if(empty($value['lock_quantity'])){
                                    throw new Exception('锁定可用库存为0');
                                }
                            }
                            $billStock->lockQuantity($value['lock_quantity']);
                        }elseif ($value['unlock_quantity']){
                            if($value['unlock_quantity'] == 'ALL'){
                                $value['unlock_quantity'] = $billBook[0]['lock_quantity'];
                                if(empty($value['unlock_quantity'])){
                                    throw new Exception('解锁可用库存为0');
                                }
                            }
                            $billStock->unlockQuantity($value['unlock_quantity']);
                        }
                        $success++;
                        $db->commit();
                    }catch (Exception $e){
                        $db->rollBack();
                        $saveError[]="账册号：".$value['record_no'].'操作失败:'.$e->getMessage();
                    }
                }
                if(!empty($saveError)){
                    $return['error'] = $saveError;
                }
                $return['state'] = 1;
                $return['message'] ='上传成功:总计：'.$total.'条记录'.'成功'.$success.'条'.'失败'.($total-$success).'条记录';
            }catch (Exception $e){
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
    }
    /**
     * Note:下载模板
     * User: Yao
     * Date: 2018/12/20
     * Time: 15:21
     */
    public function templateAction()
    {
        $type = $this->_request->getParam('type');
        if ($type == 'recode') {
            $file = 'custom_record.xls';
            $fileName = '账册模板.xls';
        }
        if ($type == 'differ') {
            $file = 'kl_differ.xls';
            $fileName = '考拉商品模板.xls';
        }
        if($type =='bill_stock_file'){
            $file='bill_stock_file.xls';
            $fileName ='账册库存调整模板.xls';
        }
        if($type =='custom_differ'){
            $file='custom_differ.xls';
            $fileName ='综保账册模板.xls';
        }
        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" . '/' . $file;
        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;
    }

    /**
     * Note:下载导入账册校验结果文件
     * User: Yao
     * Date: 2019/3/20
     * Time: 11:03
     */
    public function downloadResulErrorAction()
    {
        $file = $this->_request->getParam('file');
        $user = $this->_userAuth;
        $userId = $user->userId;
        $path = APPLICATION_PATH . '/../data/customUpload/';
        $path .= $userId;
        $fullPath =$path.'/'.$file;
        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');
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header = "Content-Disposition: attachment; filename={$file};";
        header($header);
        //     header("Content-Transfer-Encoding: binary");
        //     header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }


    /**
     * Note:删除账册
     * User: Yao
     * Date: 2019/3/13
     * Time: 14:24
     */
    public function delAction()
    {
        $return = array(
            'state' => '0',
            'message' => 'fail'
        );
        $id = $this->_request->getParam('id');
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if (empty($id)) {
                throw new Exception('参数不存在');
            }
            $billBook = Service_BillBook::getByField($id);
            if (empty($billBook)) {
                throw new Exception('账册信息不存在');
            }
            if (Service_BillBook::delete($id)) {
                Service_BillBookProduct::delete($id, 'bill_book_id');
                $user = $this->_userAuth;
                $userId = $user->userId;
                $log = array(
                    'sys_add_time' => date('Y-m-d H:i:s'),
                    'operator_ip' => Common_Common::getRealIp(),
                    'operator_id' => $userId,
                    'bill_book_id' => $billBook['id'],
                    'goods_id' => $billBook['goods_code'],
                    'json_row_before' => $billBook['json_row'],
                    'json_row' => ''
                );
                Service_BillBookLog::add($log);
                $return['state'] = 1;
                $return['message'] = '删除成功';
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(json_encode($return));
    }

    /**
     * Note:账册修改
     * User: Yao
     * Date: 2019/1/25
     * Time: 14:15
     */
    public function editAction()
    {
        $billId = $this->_request->getParam('bill_id');
        if (empty($billId)) {
            die('参数错误');
        }
        $billBook = Service_BillBook::getByField($billId);
        if (empty($billBook)) {
            die('参数错误');
        }
        $billproduct = Service_BillBookProduct::getByCondition(array('bill_book_id' => $billBook['id']));
        foreach ($billproduct as &$bp) {
            $productInfo = Service_Product::getByField($bp['product_id']);
            $barcode = array(
                $productInfo['product_barcode'],
                $productInfo['product_barcode2'],
                $productInfo['product_barcode3'],
                $productInfo['product_barcode4']
            );
            $bp['product_code'] = implode("<br/>", array_filter($barcode));
        }
        if ($this->_request->isPost()) {
            $return = array(
                'state' => '0',
                'message' => 'fail'
            );
            $params = $this->_request->getParams();
            $title = array(
                '仓库账册号' => 'warehous_account_no',
                '备案号' => 'recorde_no',
                '商品名称' => 'product_title',
                'SKU' => 'product_sku',
                '商品编码' => 'hs_code',
                '商品规格型号' => 'specification',
                '国别代码' => 'country_code',
                '申报计量单位代码' => 'decalare_unit',
                '法定计量单位代码' => 'legal_unit',
                '第二法定计量单位代码' => 'second_legal_unit',
                '申报单价金额' => 'decalar_price',
                '申报币制代码' => 'decalar_currency',
                '平均美元单价' => 'avg_dollar_price',
                '库存美元总价' => 'total_dollar_price',
                '入仓数量' => 'in_quantity',
                '入仓法定数量' => 'in_legal_quantity',
                '第二入仓法定数量' => 'in_seconde_legal_quantity',
                '实增数量' => 'real_increa_quantity',
                '实减数量' => 'real_reduce_quantity',
                '预增数量' => 'pre_increa_quantity',
                '预减数量' => 'pre_reduce_quantity',
                '存储(监管）期限' => 'storage_date',
                '记账清单编号' => 'bill_no',
                '记账清单商品序号' => 'bill_serial',
                '库存' => 'stock_quantity',
                '进出标志' => 'ie_port',
                '记账时间' => 'bill_time',
                '商品料号' => 'goods_code',
                '报关单编号' => 'custom_code',
                '总价' => 'total_price',
            );
            $rgex = array(
                'warehous_account_no' => array('length[1,50]'),
                'recorde_no' => array('length[1,50]'),
                'product_title' => array('length[1,200]'),
                'product_sku' => array('length[0,50]'),
                'hs_code' => array('length[1,30]'),
                'specification' => array('mblength[1,255]'),
                'country_code' => array('length[1,3]'),
                'decalare_unit' => array('length[1,3]'),
                'legal_unit' => array('length[1,3]'),
                'second_legal_unit' => array('length[1,3]'),
                'decalar_price' => array('numric'),
                'decalar_currency' => array('numric'),
                'avg_dollar_price' => array('numric'),
                'total_dollar_price' => array('numric'),
                'in_quantity' => array('integer'),
                'in_legal_quantity' => array('numric'),
                'in_seconde_legal_quantity' => array('numric'),
                'real_increa_quantity' => array('integer'),
                'real_reduce_quantity' => array('integer'),
                'pre_increa_quantity' => array('integer'),
                'pre_reduce_quantity' => array('integer'),
                'storage_date' => array('dateTime'),
                'bill_no' => array('length[1,30]'),
                'bill_serial' => array('length[1,30]'),
                'stock_quantity' => array('integer'),
                'ie_port' => array('length[1,255]'),
                'bill_time' => array('dateTime'),
                'goods_code' => array('length[1,30]'),
                'custom_code' => array('length[1,30]'),
                'total_price' => array('numric'),
            );
            $validate = array();
            $update = array();
            foreach ($title as $name => $key) {
                if (isset($params[$key])) {
                    $validate[] = array('name' => $name, 'value' => $params[$key], 'regex' => $rgex[$key]);
                    if ($billBook[$key] != $params[$key]) {
                        $update[$key] = $params[$key];
                    }
                }
            }
            $error = Common_Validator::formValidator($validate);
            if (!empty($error)) {
                $return['error'] = $error;
                die(json_encode($return));
            }
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                Service_BillBook::update($update, $billBook['id']);
                $newBill = Service_BillBook::getByField($billBook['id']);
                $user = $this->_userAuth;
                $userId = $user->userId;
                $log = array(
                    'sys_add_time' => date('Y-m-d H:i:s'),
                    'operator_ip' => Common_Common::getRealIp(),
                    'operator_id' => $userId,
                    'bill_book_id' => $billBook['id'],
                    'goods_id' => $billBook['goods_code'],
                    'json_row_before' => $billBook['json_row'],
                    'json_row' => json_encode($newBill),
                );
                Service_BillBookLog::add($log);
                $db->commit();
                $return['state'] = 1;
                $return['message'] = '修改成功';
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }

            die(json_encode($return));
        }
        $this->view->billBook = $billBook;
        $this->view->billProduct = $billproduct;
        $this->view->state = Service_BillBook::getState();
        $this->view->log = Service_BillBookLog::getByCondition(array('bill_book_id' => $billBook['id']),'*','','','bbl_id desc');
        echo Ec::renderTpl($this->tplDirectory . 'edit.tpl', 'layout');
    }

    /**
     * Note:删除账册产品
     * User: Yao
     * Date: 2019/1/25
     * Time: 17:02
     */
    public function delProductAction()
    {
        $return = array(
            'state' => '0',
            'message' => 'fail'
        );
        try {
            $billProductId = $this->_request->getParam('bill_product_id');
            if (empty($billProductId)) {
                throw new Exception('参数错误');
            }
            $billProductInfo = Service_BillBookProduct::getByField($billProductId);
            if (empty($billProductInfo)) {
                throw new Exception('参数错误');
            }
            Service_BillBookProduct::delete($billProductId);
            $return['state'] = 1;
            $return['message'] = '删除成功';
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(json_encode($return));
    }

    /**
     * Note:添加账册产品
     * User: Yao
     * Date: 2019/1/28
     * Time: 11:35
     */
    public function addProductAction()
    {
        $return = array(
            'state' => '0',
            'message' => 'fail'
        );
        try {
            $productSku = $this->_request->getParam('product_sku');
            $customerCode = $this->_request->getParam('customer_code');
            $id = $this->_request->getParam('bill_book_id');
            Common_Common::trim_blank($productSku);
            Common_Common::trim_blank($customerCode);
            if (empty($productSku)) {
                throw new Exception('产品sku必填');
            }
            if (empty($customerCode)) {
                throw new Exception('客户代码必填');
            }
            if (empty($id)) {
                throw  new Exception('参数错误');
            }
            $billBook = Service_BillBook::getByField($id);
            if (empty($billBook)) {
                throw new Exception('参数错误');
            }
            $customerInfo = Service_Customer::getByField($customerCode, 'customer_code');
            if (empty($customerInfo)) {
                throw new Exception('客户代码不存在');
            }
            $billProductInfo = Service_Product::getByCondition(array('product_sku' => $productSku, 'customer_code' => $customerInfo['customer_code']));
            if (empty($billProductInfo)) {
                throw new Exception('该产品不存在');
            }
            $billProductInfo = $billProductInfo[0];
            $billBook = Service_BillBook::getByField($id);
            $checkBill = Service_BillBookProduct::getByCondition(array('bill_book_id' => $id, 'product_id' => $billProductInfo['product_id']));
            if (!empty($checkBill)) {
                throw new Exception('该产品已经存在');
            }
            $error = Service_BillBook::validatorBookAndProduct($billProductInfo, $billBook);
            if (!empty($error)) {
                throw new Exception(implode(',', $error));
            }
            $add = array(
                'bill_book_id' => $id,
                'product_sku' => $billProductInfo['product_sku'],
                'product_id' => $billProductInfo['product_id'],
                'customer_code' => $billProductInfo['customer_code'],
                'add_time' => date('Y-m-d H:i:s'),
            );
            $billProductId = Service_BillBookProduct::add($add);
            $return['data'] = array(
                'product_sku' => $billProductInfo['product_sku'],
                'product_barcode' => $billProductInfo['product_barcode'],
                'customer_code' => $billProductInfo['customer_code'],
                'bil_prdouct_id' => $billProductId
            );
            $return['state'] = 1;
            $return['message'] = '添加成功';
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(json_encode($return));
    }

    /**
     * Note:考拉系统账册信息比对
     * User: Yao
     * Date: 2019/3/13
     * Time: 14:34
     */
    public function differAction()
    {
        require_once "PHPExcel.php";
        require_once 'PHPExcel/IOFactory.php';
        $return =array(
            'state'=>0,
            'message'=>'',
            'file'=>'',
        );
        $field = 'differ_file';
        $user = $this->_userAuth;
        $userId = $user->userId;
        $path = APPLICATION_PATH . '/../data/KaolaUpload/';
        $path .= $userId;
        if (!file_exists($path)) {
            if (!mkdir($path, 0700, true)) {
                $return['error'] = array('上传目录不存在创建文件目录失败');
                die(json_encode($return));
            }
        }
        $config = array();
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'xls|xlsx|csv';
        $config['max_size'] = '4000';
        $config['encrypt_name'] = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES, $field)) {
            $return['error'] = array($upload->display_errors());
            die(json_encode($return));
        }
        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if (empty($resultArray) || empty($full_path)) {
            $return['error'] = array('数据不存在');
            die(json_encode($return));
        }
        $title = array(
            '客户代码' => 'customer_code',
            '商品条码' => 'product_sku',
            '原产国' => 'country_code_of_origin',
            '海关编码' => 'hs_code',
            '申报单位' => 'pu_code',
        );
        $data = Common_Upload::readXlsFromTitle($full_path, $title);
        if (empty($data)) {
            $return['error'] = array('数据不存在');
            die(json_encode($return));
        }
        foreach ($data as $row) {
            $row['user_id'] = $userId;
            Service_UploadProductDiffer::add($row);
        }
        $productData = Service_UploadProductDiffer::getLeftJoinProduct(array('user_id' => $userId,'same_customer_code'=>true));
        if (empty($productData)) {
            $return['error'] = array('导入数据失败，请重新导入');
            die(json_encode($return));
        }
        $title = array(
            '考拉sku',
            '考拉原产国',
            '考拉海关编码',
            '考拉申报单位',
            '系统产品ID',
            '系统sku',
            '系统海关编码',
            '系统申报单位',
            '系统原产国',
            '账册号',
            '账册海关编码',
            '账册申报单位',
            '账册原产国',
            '系统申报要素',
            '账册申报要素',
            '修改oms原产国',
            '修改账册原产国',
            '原产国都要修改',
            '修改oms海关编码',
            '修改账册海关编码',
            '海关编码都要修改',
            '修改oms申报单位',//T
            '修改考拉申报单位',//U
            '申报单位都要修改',//V
            '多个账册信息',
        );
        $phpExcel = new PHPExcel();
        $sheet = $phpExcel->getSheet(0);
        $tradeCountry = array();
        $exportData = array();
        $uomMap = array();
        $i = 0 ;
        foreach ($productData as $data) {
            $exportData[$i] = array(
                'kl_product_sku'=>$data['product_sku'],
                'kl_country_code_of_origin'=>$data['country_code_of_origin'],
                'kl_hs_code'=>$data['hs_code'],
                'kl_pu_code'=>$data['pu_code'],
                's_product_id'=>$data['p_product_id'],
                's_product_sku'=>$data['p_product_sku'],
                's_hs_code'=>$data['p_hs_code'],
                's_pu_code'=>$data['p_pu_code'],
                's_country_code_of_origin'=>$data['p_country_code_of_origin'],
                'recode_no'=>'',
                'recode_hs_code'=>'',
                'recode_pu_code'=>'',
                'recode_country_code_of_origin'=>'',
                'update_oms_country'=>'',
                'update_recode_country'=>'',
                'update_all_country'=>'',
                'update_oms_hs_code'=>'',
                'update_recode_hs_code'=>'',
                'update_all_hs_code'=>'',
                'update_oms_pu_code'=>'',
                'update_recode_pu_code'=>'',
                'update_kl_pu_code'=>'',
                'update_all_pu_code'=>'',
                'more_recode_info'=>'',
                'oms_hs_element'=>'',
                'recode_hs_element'=>'',
            );
            if(!empty($data['p_country_code_of_origin']) && !isset($tradeCountry[$data['p_country_code_of_origin']])){
                $countryInfo = Service_Country::getByField($data['p_country_code_of_origin'], 'country_code');
                $tradeCountry[$data['p_country_code_of_origin']] = $countryInfo['country_name'];
            }
            $exportData[$i]['s_country_code_of_origin']=$tradeCountry[$data['p_country_code_of_origin']];
            if(!empty($data['p_pu_code'])) {
                if (empty($uomMap[$data['p_pu_code']])) {
                    $productUom = Service_ProductUom::getByField($data['p_pu_code'], 'pu_code');
                    $uomMap[$data['p_pu_code']] = $productUom['pu_name'];
                }
            }
            $exportData[$i]['s_pu_code']=$uomMap[$data['p_pu_code']];
            if(!empty($data['p_product_id'])) {
                $heElement = Service_HsElementMap::getByCondition(array('product_id' => $data['p_product_id']));
                $hsMap = array();
                $biId = array();
                foreach($heElement as $he){
                    $hsMap[] = $he['hem_detail'];
                }
                $exportData[$i]['oms_hs_element'] = implode('|',$hsMap);
                $bilPr = Service_BillBookProduct::getByCondition(array('product_id'=>$data['p_product_id']));
                $oldData = $exportData[$i];
                if(empty($bilPr)){
                    $i++;
                    continue;
                }
                foreach($bilPr as $bp){
                    $biId[]=$bp['bill_book_id'];
                }
                $billBook = Service_BillBook::getByCondition(array('id_array'=>$biId,'stock_quantity_gt'=>'0'));
                $billBookCount = count($billBook);
                foreach($billBook as $bb){
                    if(!$uomMap[$bb['decalare_unit']]){
                        $unitName = Service_ProductUom::getByField($bb['decalare_unit'],'pu_code');
                        $uomMap[$bb['decalare_unit']] = $unitName['pu_name'];
                    }
                    if(!empty($bb['country_code']) && !isset($tradeCountry[$bb['country_code']])){
                        $countryInfo = Service_Country::getByField($bb['country_code'], 'trade_country');
                        $tradeCountry[$bb['country_code']] = $countryInfo['country_name'];
                    }
                    $recodeInfo = array(
                        'recode_no'=>$bb['recorde_no'],
                        'recode_hs_code'=>$bb['hs_code'],
                        'recode_pu_code'=> $uomMap[$bb['decalare_unit']],
                        'recode_country_code_of_origin'=>$tradeCountry[$bb['country_code']],
                        'recode_hs_element'=> $bb['specification'],
                        'recode_count'=>$billBookCount,
                    );
                    $exportData[$i] = array_merge($oldData,$recodeInfo);
                    $i++;
                }
            }
            $i++;

        }
        foreach($title as $key=>$t){
            $rowKey = PHPExcel_Cell::stringFromColumnIndex($key);
            $sheet->setCellValue($rowKey.'1',$t);
        }
        $exportObj = new Service_Export_DifferRecode();
        foreach($exportData as &$data){
                if($data['recode_count']>1){
                    $error = array();
                    $erro1 = $exportObj->differColumWithRecode($data,'s_pu_code','recode_pu_code','kl_pu_code','申报单位');
                    $erro2 = $exportObj->differColumWithRecode($data,'s_hs_code','recode_hs_code','kl_hs_code','海关编码');
                    $erro3 = $exportObj->differColumWithKl($data,'s_country_code_of_origin','recode_country_code_of_origin','kl_country_code_of_origin','原产国');
                    $error = array_merge($erro1,$erro2,$erro3);
                    $data['more_recode_info'] = implode('|',$error);
                }else{
                    $erro1 = $exportObj->differColumWithRecode($data,'s_pu_code','recode_pu_code','kl_pu_code','申报单位');
                    if(!empty($erro1)){
                        if($erro1['all_error']){
                            $data['update_all_pu_code'] = '系统，考拉，账册申报单位都不一致';
                        }
                        if($erro1['sys_error']){
                            $data['update_oms_pu_code'] = '系统,账册申报单位不一致';
                        }
                        if($erro1['kl_error']){
                            $data['update_kl_pu_code'] = '考拉,账册申报单位不一致';
                        }
                    }
                    $erro1 = $exportObj->differColumWithRecode($data,'s_hs_code','recode_hs_code','kl_hs_code','海关编码');
                    if(!empty($erro1)){
                        if($erro1['all_error']){
                            $data['update_all_hs_code'] = '系统，考拉，账册海关编码都不一致';
                        }
                        if($erro1['sys_error']){
                            $data['update_oms_hs_code'] = '系统,账册海关编码不一致';
                        }
                        if($erro1['kl_error']){
                            $data['update_kl_hs_code'] = '考拉,账册海关编码不一致';
                        }
                    }
                    $erro1 = $exportObj->differColumWithKl($data,'s_country_code_of_origin','recode_country_code_of_origin','kl_country_code_of_origin','原产国');
                    if(!empty($erro1)){
                        if($erro1['all_error']){
                            $data['update_all_country'] = '系统，考拉，账册原产国都不一致';
                        }
                        if($erro1['sys_error']){
                            $data['update_oms_country'] = '系统,账册原产国不一致';
                        }
                        if($erro1['recod_error']){
                            $data['update_recode_country'] = '考拉,账册原产国不一致';
                        }
                    }
                }
        }
        $dataType = PHPExcel_Cell_DataType::TYPE_STRING;
        $index = 2;
        foreach($exportData as $value){
            $sheet->setCellValueExplicit('A'.$index,$value['kl_product_sku'],$dataType);//'考拉sku',
            $sheet->setCellValueExplicit('B'.$index,$value['kl_country_code_of_origin'],$dataType);//考拉原产国
            $sheet->setCellValueExplicit('C'.$index,$value['kl_hs_code'],$dataType);//考拉海关编码
            $sheet->setCellValueExplicit('D'.$index,$value['kl_pu_code'],$dataType);//考拉申报单位
            $sheet->setCellValueExplicit('E'.$index,$value['s_product_id'],$dataType);//系统产品ID
            $sheet->setCellValueExplicit('F'.$index,$value['s_product_sku'],$dataType);//系统sku
            $sheet->setCellValueExplicit('G'.$index,$value['s_hs_code'],$dataType);//系统海关编码
            $sheet->setCellValueExplicit('H'.$index,$value['s_pu_code'],$dataType);//系统申报单位
            $sheet->setCellValueExplicit('I'.$index,$value['s_country_code_of_origin'],$dataType);//系统原产国
            $sheet->setCellValueExplicit('J'.$index,$value['recode_no'],$dataType);//账册号
            $sheet->setCellValueExplicit('K'.$index,$value['recode_hs_code'],$dataType);//账册海关编码
            $sheet->setCellValueExplicit('L'.$index,$value['recode_pu_code'],$dataType);//账册申报单位
            $sheet->setCellValueExplicit('M'.$index,$value['recode_country_code_of_origin'],$dataType);//账册原产国
            $sheet->setCellValueExplicit('N'.$index,$value['oms_hs_element'],$dataType);//系统申报要素
            $sheet->setCellValueExplicit('O'.$index,$value['recode_hs_element'],$dataType);//账册申报要素
            $sheet->setCellValueExplicit('P'.$index,$value['update_oms_country'],$dataType);//修改oms原产国
            $sheet->setCellValueExplicit('Q'.$index,$value['update_recode_country'],$dataType);//修改账册原产国
            $sheet->setCellValueExplicit('R'.$index,$value['update_all_country'],$dataType);//原产国都要修改
            $sheet->setCellValueExplicit('S'.$index,$value['update_oms_hs_code'],$dataType);//修改oms海关编码
            $sheet->setCellValueExplicit('T'.$index,$value['update_recode_hs_code'],$dataType);//修改账册海关编码
            $sheet->setCellValueExplicit('U'.$index,$value['update_all_hs_code'],$dataType);//海关编码都要修改
            $sheet->setCellValueExplicit('V'.$index,$value['update_oms_pu_code'],$dataType);//修改oms申报单位
            $sheet->setCellValueExplicit('W'.$index,$value['update_kl_pu_code'],$dataType);//修改考拉申报单位
            $sheet->setCellValueExplicit('X'.$index,$value['update_all_pu_code'],$dataType);//申报单位都要修改
            $sheet->setCellValueExplicit('Y'.$index,$value['more_recode_info'],$dataType);//多个账册信息

            $index++;
        }
        $writer = PHPExcel_IOFactory::createWriter($phpExcel,'Excel5');
        $saveFile = $path.'/'.date('Ymdhis').rand(100,999).'result.xls';
        $writer->save($saveFile);
        $return['state'] = 1;
        $return['file'] = basename($saveFile);
        die(Zend_Json::encode($return));
    }

    /**
     * Note:下载账册比对结果文件
     * User: Yao
     * Date: 2018/12/20
     * Time: 15:21
     */
    public function downloadResultAction()
    {
        $file = $this->_request->getParam('file');
        $path = APPLICATION_PATH . '/../data/KaolaUpload/';
        $user = $this->_userAuth;
        $userId = $user->userId;
        $path .= $userId;
        $user = $this->_userAuth;
        $userId = $user->userId;
        if(!empty($userId)) {
            Service_UploadProductDiffer::delete($userId, 'user_id');
        }
        if(empty($file)){
            exit('文件不存在');
        }
        $fullPath = $path .'/' . $file;
        if(!is_file($fullPath)){
            exit('文件不存在');
        }
        $fileName = basename($fullPath);
        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');
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header = "Content-Disposition: attachment; filename={$fileName};";
        header($header);
        echo file_get_contents($fullPath);
        exit;
    }
    private function changeChineseToCode($billBookRow){
        static $uomMap;
        static $countryMap;
        static $currencyMap;
        if(!empty($billBookRow['country_code']) && !preg_match("/^\d+$/",$billBookRow['country_code'])){
            if($billBookRow['country_code'] == '台澎金马关税区'){
                $billBookRow['country_code'] = '中国台湾';
            }
            if($countryMap[$billBookRow['country_code']]){
                $billBookRow['country_code'] = $countryMap[$billBookRow['country_code']];
            }else {
                $country = Service_Country::getByCondition([
                    'country_name' => $billBookRow['country_code']
                ]);
                if ($country) {
                    $countryMap[$billBookRow['country_code'] =$country[0]['country_code']] ;
                    $billBookRow['country_code'] = $country[0]['trade_country'];
                }
            }
        }
        if(!empty($billBookRow['decalare_unit']) && !preg_match("/^\d+$/",$billBookRow['decalare_unit'])){
            if($uomMap[$billBookRow['decalare_unit']]){
                $billBookRow['decalare_unit'] = $uomMap[$billBookRow['decalare_unit']];
            }else {
                $productUom = Service_ProductUom::getByField($billBookRow['decalare_unit'], 'pu_name');
                if ($productUom) {
                    $uomMap[$billBookRow['decalare_unit']] = $productUom['pu_code'];
                    $billBookRow['decalare_unit'] = $productUom['pu_code'];
                }
            }
        }
        if(!empty($billBookRow['legal_unit']) && !preg_match("/^\d+$/",$billBookRow['legal_unit'])){
            if($uomMap[$billBookRow['legal_unit']]){
                $billBookRow['legal_unit'] = $uomMap[$billBookRow['legal_unit']];
            }else {
                $productUom = Service_ProductUom::getByField($billBookRow['legal_unit'], 'pu_name');
                if ($productUom) {
                    $uomMap[$billBookRow['legal_unit']] = $productUom['pu_code'];
                    $billBookRow['legal_unit'] = $productUom['pu_code'];
                }
            }
        }
        if(!empty($billBookRow['second_legal_unit']) && !preg_match("/^\d+$/",$billBookRow['second_legal_unit'])){
            if($uomMap[$billBookRow['second_legal_unit']]) {
                $billBookRow['second_legal_unit'] = $uomMap[$billBookRow['second_legal_unit']];
            }else {
                $productUom = Service_ProductUom::getByField($billBookRow['second_legal_unit'], 'pu_name');
                if ($productUom) {
                    $uomMap[$billBookRow['second_legal_unit']] = $productUom['pu_code'];
                    $billBookRow['second_legal_unit'] = $productUom['pu_code'];
                }
            }
        }
        if(!empty($billBookRow['decalar_currency']) && !preg_match("/^\d+$/",$billBookRow['decalar_currency'])){
            if($currencyMap[$billBookRow['decalar_currency']]) {
                $currencyMap['decalar_currency'] = $currencyMap[$billBookRow['decalar_currency']];
            }else {
                $currency = Service_Currency::getByField($billBookRow['decalar_currency'], 'currency_name');
                if ($currency) {
                    $currencyMap[$billBookRow['decalar_currency']] = $currency['currency_code'];
                    $billBookRow['decalar_currency'] = $currency['currency_code'];
                }
            }
        }
        return $billBookRow;
    }

    /**
     * Note:打开上传比对页面时把之前的数据清空了
     * User: Yao
     * Date: 2019/3/15
     * Time: 15:15
     */
    public function cleanDataAction(){
        $user = $this->_userAuth;
        $userId = $user->userId;
        if(!empty($userId)) {
            Service_UploadProductDiffer::delete($userId, 'user_id');
        }
    }
    /**
     * Note:导出账册流水
     * User: Yao
     * Date: 2020/12/30
     * Time: 9:40
     */
    public function exportBillLogAction(){
        $return = [
            'state'=>0,
            'message'=>'fail',
            'file'=>''
        ];
        try{
            $bookId = $this->_request->getParam('book_id');
            if(empty($bookId)){
                throw new Exception('参数错误');
            }
            $billBook = Service_BillBook::getByField($bookId);
            if(empty($billBook)){
                throw new Exception('参数错误');
            }
            $recodeNo = $billBook['recorde_no'];
            $startTime = $this->_request->getParam('bill_start_time');
            $endTime = $this->_request->getParam('bill_end_time');
            $billStockLogCondtion = [
                'recode_no'=>$recodeNo,
                'warehous_account_no'=>$billBook['warehous_account_no'],
            ];
            if($startTime){
                $billStockLogCondtion['add_time_start']=date("Y-m-d H:i:s",strtotime($startTime));
            }
            if($endTime){
                $billStockLogCondtion['add_time_end'] = date("Y-m-d H:i:s",strtotime($endTime));
            }
            $billStockLogCount = Service_BillStockLog::getByCondition($billStockLogCondtion,'count(*)');
            if($billStockLogCount){
                $path = APPLICATION_PATH . '/../data/KaolaUpload/';
                $user = $this->_userAuth;
                $userId = $user->userId;
                $path .= $userId;
                if(!is_dir($path)){
                    mkdir($path,0777,true);
                }
                $xlsx = new \XLSXWriter();
                $filePath = $path.'/'.'billstocklog'.date("Ymdhis").'.xlsx';
                $xlsx->writeSheetHeader('sheet1',[
                    '账册号'=>'string',
                    '仓库账册号'=>'string',
                    '核增冻结库存'=>'integer',
                    '核减冻结库存'=>'integer',
                    '增加可用库存'=>'integer',
                    '核减可用库存'=>'integer',
                    '增加核销库存'=>'integer',
                    '核减核销库存'=>'integer',
                    '核增锁定库存'=>'integer',
                    '核减锁定库存'=>'integer',
                    '关联单号'=>'string',
                    '备注'=>'string',
                    '添加时间'=>'string',
                ]);
                $pageSize = 500;
                $totalPage = ceil($billStockLogCount/$pageSize);
                for($i=1;$i<=$totalPage;$i++){
                    $logList = Service_BillStockLog::getByCondition($billStockLogCondtion,'*',$pageSize,$i);
                    foreach ($logList as $log)
                    $xlsx->writeSheetRow('sheet1',[
                        $log['recode_no'],
                        $log['warehous_account_no'],
                        $log['incre_fronzen_quantity'],
                        $log['reduce_fronzen_quantity'],
                        $log['incre_quantity'],
                        $log['reduce_quantity'],
                        $log['incre_desotry_quantity'],
                        $log['reduce_destory_quantity'],
                        $log['incre_lock_quantity'],
                        $log['reduce_lock_quantity'],
                        $log['reference_no'],
                        $log['note'],
                        $log['add_time']
                    ]);
                }
                $xlsx->writeToFile($filePath);
                $return['state'] = 1;
                $return['file'] = basename($filePath);
                $return['message'] = '导出成功';
            }else{
                throw new Exception('没有数据');
            }
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * Note:综保库存和系统库存对比
     * User: Yao
     * Date: 2021/6/29
     * Time: 17:41
     */
    public function customRecodeDiffAction()
    {
        require_once "PHPExcel.php";
        require_once 'PHPExcel/IOFactory.php';
        $return =array(
            'state'=>0,
            'message'=>'',
            'file'=>'',
        );
        $field = 'custom_differ_file';
        $user = $this->_userAuth;
        $userId = $user->userId;
        $path = APPLICATION_PATH . '/../data/KaolaUpload/';
        $path .= $userId;
        if (!file_exists($path)) {
            if (!mkdir($path, 0700, true)) {
                $return['error'] = array('上传目录不存在创建文件目录失败');
                die(json_encode($return));
            }
        }
        $config = array();
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'xls|xlsx|csv';
        $config['max_size'] = '4000';
        $config['encrypt_name'] = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES, $field)) {
            $return['error'] = array($upload->display_errors());
            die(json_encode($return));
        }
        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if (empty($resultArray) || empty($full_path)) {
            $return['error'] = array('数据不存在');
            die(json_encode($return));
        }
        $phpExcel = PHPExcel_IOFactory::load($full_path);
        $sheet = $phpExcel->getSheet(0);
        $maxColumn = $sheet->getHighestColumn();
        $maxRow = $sheet->getHighestRow();
        $titleArray =[];

        for($i=0;$i<=PHPExcel_Cell::columnIndexFromString($maxColumn);$i++){
            $columnName = PHPExcel_Cell::stringFromColumnIndex($i);
            $titleArray[$columnName] = $sheet->getCell($columnName.'1')->getValue();
        }
        $warhosueAccountColumn='';
        $recodeColum ='';
        $quantitiColum ='';
        foreach ($titleArray as $column =>$value) {
            if (strstr($value, '仓库账册号') !== false||strstr($value, '账册编号')!==false) {
                $warhosueAccountColumn = $column;
            }
            if (strstr($value, '备案号') !== false ||strstr($value,'明细账册项号')!==false) {
                $recodeColum = $column;
            }
            if (strstr($value, '库存数量') !== false||$value =='库存') {
                $quantitiColum = $column;
            }
        }
        $billQuantityColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($maxColumn));
        $differColum = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($maxColumn)+1);
        $fayiColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($maxColumn)+2);
        $feibaoColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($maxColumn)+3);
        $sheet->setCellValue($billQuantityColumn.'1','系统库存');
        $sheet->setCellValue($differColum.'1','差异数量');
        $sheet->setCellValue($fayiColumn.'1','发一数量');
        $sheet->setCellValue($feibaoColumn.'1','非保入仓数量');
        for($i=2;$i<=$maxRow;$i++){
            $warehouseAccount = $sheet->getCell($warhosueAccountColumn.$i)->getValue();
            $recodeNo = $sheet->getCell($recodeColum.$i)->getValue();
            $quanity = $sheet->getCell($quantitiColum.$i)->getValue();
            if($warehouseAccount && $recodeNo){
                $billRecode = Service_BillBook::getByCondition([
                    'warehous_account_no'=>$warehouseAccount,
                    'recorde_no'=>$recodeNo,
                ]);
                if(!empty($billRecode)){
                    $sysQantity = $billRecode[0]['frozen_quantity']+$billRecode[0]['can_use_quantity']+$billRecode[0]['lock_quantity'];
                    if($warehouseAccount == 'FB52252161005001'){
                        $billProduct = Service_BillBookProduct::getByField($billRecode[0]['id'],'bill_book_id');
                        $hsUomMap = Service_HsUomMap::getByField($billProduct['product_id'],'product_id');
                        $sheet->setCellValue($billQuantityColumn.$i,$sysQantity);
                        $sheet->setCellValue($differColum.$i,bcdiv($quanity,$hsUomMap['hum_quantity_law'])-$sysQantity);
                        $sheet->setCellValue($fayiColumn.$i,$hsUomMap['hum_quantity_law']);
                        $sheet->setCellValue($feibaoColumn.$i,$quanity/$hsUomMap['hum_quantity_law']);
                    }else{
                        $sheet->setCellValue($billQuantityColumn.$i,$sysQantity);
                        $sheet->setCellValue($differColum.$i,$quanity-$sysQantity);
                    }
                }else{
                    $sheet->setCellValue($billQuantityColumn.$i,0);
                    $sheet->setCellValue($differColum.$i,$quanity);
                }
            }
        }
        $writer = PHPExcel_IOFactory::createWriter($phpExcel,'Excel5');
        $saveFile = $path.'/'.date('Ymdhis').rand(100,999).'result.xls';
        $writer->save($saveFile);
        $return['state'] = 1;
        $return['file'] = basename($saveFile);
        die(Zend_Json::encode($return));
    }
    /**
     * Note:导出账册信息
     * User: Yao
     * Date: 2021/7/28
     * Time: 16:44
     */
    public function exportAction(){
        //echo "<pre>";
        set_time_limit(600);
        $recodeList = $this->_request->getParam('recode');
        $xlsx = new \XLSXWriter();
        $xlsx->writeSheetHeader('sheet1',[
            '仓库账册号'=>'string',
            '备案序号'=>'string',
            '海关料件号'=>'string',
            '海关编码'=>'string',
            '产品名称'=>'string',
            '商品规格'=>'string',
            '可用库存'=>'integer',
            '锁定库存'=>'integer',
            '冻结库存'=>'integer',
            '原产国'=>'string',
            '原产国名称'=>'string',
            '申报币制代码'=>'string',
            '单价'=>'string',
            '申报计量单位代码'=>'string',
            '法定计量单位代码'=>'string',
            '第二法定计量单位代码'=>'string',
            '锁定状态'=>'string',
            '添加时间'=>'string',
        ]);
        $state = Service_BillBook::getState();
        $country = [];
        $hsuom =[];
        if(!empty($recodeList)){
            foreach ($recodeList as $billId){
                $billBook = Service_BillBook::getByField($billId);
                if(!$country[$billBook['country_code']]){
                    $countryInfo = Service_Country::getByField($billBook['country_code'],'trade_country');
                    $country[$billBook['country_code']] = $countryInfo['country_name'];
                }
                if(!$hsuom[$billBook['decalare_unit']]){
                    $productUom = Service_ProductUom::getByField($billBook['decalare_unit'],'pu_code');
                    $hsuom[$billBook['decalare_unit']] = $productUom['pu_name'];
                }
                if(!$hsuom[$billBook['legal_unit']]){
                    $productUom = Service_ProductUom::getByField($billBook['legal_unit'],'pu_code');
                    $hsuom[$billBook['legal_unit']] = $productUom['pu_name'];
                }
                if($billBook['second_legal_unit']){
                    if(!$hsuom[$billBook['second_legal_unit']]){
                        $productUom = Service_ProductUom::getByField($billBook['second_legal_unit'],'pu_code');
                        $hsuom[$billBook['second_legal_unit']] = $productUom['pu_name'];
                    }
                }
                $xlsx->writeSheetRow('sheet1',[
                    $billBook['warehous_account_no'],//'仓库账册号'
                    $billBook['recorde_no'],//'备案序号'=>'string',
                    $billBook['goods_code'],//'海关料件号'=>'string',
                    $billBook['hs_code'],//'海关编码'=>'string',
                    $billBook['product_title'],//'产品名称'=>'string',
                    $billBook['specification'],//'商品规格'=>'string',
                    $billBook['can_use_quantity'],//'可用库存'=>'integer',
                    $billBook['lock_quantity'],//'锁定库存'=>'integer',
                    $billBook['frozen_quantity'],//'冻结库存'=>'integer',
                    $billBook['country_code'],//'原产国'=>'string',
                    $country[$billBook['country_code']],//原产国名称
                    $billBook['decalar_currency'],//'申报币制代码'=>'string',
                    $billBook['decalar_price'],//'单价'=>'string',
                    $billBook['decalare_unit'].'-'.$hsuom[$billBook['decalare_unit']] ,//'申报计量单位代码'=>'string',
                    $billBook['legal_unit'].'-'.$hsuom[$billBook['legal_unit']],//'法定计量单位代码'=>'string',
                    $billBook['second_legal_unit']?$billBook['second_legal_unit'].'-'.$hsuom[$billBook['second_legal_unit']]:'',//'第二法定计量单位代码'=>'string',
                    $state[$billBook['state']],
                    $billBook['add_time'],//'添加时间'=>'string',
                ]);
            }
        }else{
            $condition = $this->getCondition();
            print_r($condition);
            $pageSize = 500;
            $list = Service_BillBook::getByCondition($condition,'*',$pageSize,1,'id asc');
            exit;
            while ($list){
                //print_r($list);
                foreach ($list as $billBook){
                    if(!$country[$billBook['country_code']]){
                        $countryInfo = Service_Country::getByField($billBook['country_code'],'trade_country');
                        $country[$billBook['country_code']] = $countryInfo['country_name'];
                    }
                    if(!$hsuom[$billBook['decalare_unit']]){
                        $productUom = Service_ProductUom::getByField($billBook['decalare_unit'],'pu_code');
                        $hsuom[$billBook['decalare_unit']] = $productUom['pu_name'];
                    }
                    if(!$hsuom[$billBook['legal_unit']]){
                        $productUom = Service_ProductUom::getByField($billBook['legal_unit'],'pu_code');
                        $hsuom[$billBook['legal_unit']] = $productUom['pu_name'];
                    }
                    if($billBook['second_legal_unit']){
                        if(!$hsuom[$billBook['second_legal_unit']]){
                            $productUom = Service_ProductUom::getByField($billBook['second_legal_unit'],'pu_code');
                            $hsuom[$billBook['second_legal_unit']] = $productUom['pu_name'];
                        }
                    }
                    $xlsx->writeSheetRow('sheet1',[
                        $billBook['warehous_account_no'],//'仓库账册号'
                        $billBook['recorde_no'],//'备案序号'=>'string',
                        $billBook['goods_code'],//'海关料件号'=>'string',
                        $billBook['hs_code'],//'海关编码'=>'string',
                        $billBook['product_title'],//'产品名称'=>'string',
                        $billBook['specification'],//'商品规格'=>'string',
                        $billBook['can_use_quantity'],//'可用库存'=>'integer',
                        $billBook['lock_quantity'],//'锁定库存'=>'integer',
                        $billBook['frozen_quantity'],//'冻结库存'=>'integer',
                        $billBook['country_code'],//'原产国'=>'string',
                        $country[$billBook['country_code']],//原产国名称
                        $billBook['decalar_currency'],//'申报币制代码'=>'string',
                        $billBook['decalar_price'],//'单价'=>'string',
                        $billBook['decalare_unit'].'-'.$hsuom[$billBook['decalare_unit']] ,//'申报计量单位代码'=>'string',
                        $billBook['legal_unit'].'-'.$hsuom[$billBook['legal_unit']],//'法定计量单位代码'=>'string',
                        $billBook['second_legal_unit']?$billBook['second_legal_unit'].'-'.$hsuom[$billBook['second_legal_unit']]:'',//'第二法定计量单位代码'=>'string',
                        $state[$billBook['state']],
                        $billBook['add_time'],//'添加时间'=>'string',
                    ]);
                }
                $condition['last_id'] = $billBook['id'];
                $list = Service_BillBook::getByCondition($condition,'*',$pageSize,1,'id asc');
            }
        }
        $filename ='账册库存'.date("Y-m-d").'.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/force-download');
        header("Content-Disposition: attachment;filename=\"$filename\"");
        header("Content-Transfer-Encoding: binary");
        header('Cache-Control: max-age=0');
        $xlsx->writeToStdOut();
    }

    /**
     * Note:
     * User: Yao
     * Date: 2021/7/30
     * Time: 11:14
     */
    public function lockAction(){
        $return =[
            'state'=>0,
            'message'=>'fail',
            'data'=>[],
        ];
        $total = 0;
        $success = 0;
        try{
            $recodeId = $this->_request->getParam('recode');
            if(empty($recodeId)){
                throw new Exception('请选择要锁定的记录');
            }
            $reason = $this->_request->getParam('lock_reason');
            if(empty($reason)){
                throw new Exception('请填写原因');
            }
            $recodeId = explode(',',$recodeId);
            $ip = Common_Common::getRealIp();
            $userId = $this->_userAuth->userId;
            foreach ($recodeId as $billbookId){
                $total++;
                $billBook = Service_BillBook::getByField($billbookId);
                if($billBook){
                    if($billBook['state'] == 0) {
                        $db = Common_Common::getAdapter();
                        $db->beginTransaction();
                        try {
                            $update = [
                                'state' => 1
                            ];
                            Service_BillBook::update($update, $billBook['id']);
                            $log = array(
                                'sys_add_time' => date("Y-m-d H:i:s"),
                                'operator_ip' => $ip,
                                'bill_book_id' => $billBook['id'],
                                'goods_id' => $billBook['goods_code'],
                                'operator_id' => $userId,
                                'operate_type' => 1,
                                'remark' => '锁定记录:' . $reason
                            );
                            Service_BillBookLog::add($log);
                            $success++;
                            $db->commit();
                        }catch (Exception $e){
                            $db->rollBack();
                            $return['data'][]="备案序号".$billBook['recorde_no'].'锁定失败';
                        }
                    }else{
                        $return['data'][]="备案序号".$billBook['recorde_no'].'不是正常状态';
                    }
                }
            }
            if($success){
                $return['state'] = 1;
                $return['message']="锁定记录成功：总计".$total.'条记录，成功'.$success.'条记录，失败'.($total-$success).'条记录';
            }else{
                $return['message']="锁定的失败：没有符合条件的记录";
            }

        }catch (Exception $e){
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:
     * User: Yao
     * Date: 2021/7/30
     * Time: 11:14
     */
    public function unlockAction(){
        $return =[
            'state'=>0,
            'message'=>'fail',
            'data'=>[],
        ];
        $total = 0;
        $success = 0;
        try{
            $recodeId = $this->_request->getParam('recode');
            $reason = $this->_request->getParam('lock_reason');
            if(empty($recodeId)){
                throw new Exception('请选择要解锁的记录');
            }
            if(empty($reason)){
                throw new Exception('请填写原因');
            }
            $recodeId = explode(',',$recodeId);
            $ip = Common_Common::getRealIp();
            $userId = $this->_userAuth->userId;
            foreach ($recodeId as $billbookId){
                    $total++;
                    $billBook = Service_BillBook::getByField($billbookId);
                    if ($billBook) {
                        if ($billBook['state'] == 1) {
                            $db = Common_Common::getAdapter();
                            $db->beginTransaction();
                            try {
                                $update = [
                                    'state' => 0
                                ];
                                $billBook = Service_BillBook::getByIdForUpdate($billbookId);
                                Service_BillBook::update($update, $billBook['id']);
                                $log = array(
                                    'sys_add_time' => date("Y-m-d H:i:s"),
                                    'operator_ip' => $ip,
                                    'bill_book_id' => $billBook['id'],
                                    'goods_id' => $billBook['goods_code'],
                                    'operator_id' => $userId,
                                    'operate_type' => 1,
                                    'remark' => '解锁记录:' . $reason
                                );
                                Service_BillBookLog::add($log);
                                $success++;
                                $db->commit();
                            }catch (Exception $e){
                                $return['data'][] = "备案序号" . $billBook['recorde_no'] . '解锁失败';
                                $db->rollBack();
                            }
                        } else {
                            $return['data'][] = "备案序号" . $billBook['recorde_no'] . '不是锁定状态';
                        }
                    }
            }
            if($success){
                $return['state'] = 1;
                $return['message']="解锁成功：总计".$total.'条记录，成功'.$success.'条记录，失败'.($total-$success).'条记录';
            }else{
                $return['message']="解锁失败：没有符合条件的记录";
            }
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

}
