<?php

/**
 * Class Clearance_DesMessageController
 * User: Yao
 * Date: 2019/12/27
 * Note:核注清单
 */

use Customs\Dg\Hmzb\Delivery\Base;
use Customs\Dg\Hmzb\Delivery\Decl;
use Customs\Dg\Hmzb\Delivery\Xml;
use Customs\Dg\Hmzb\Delivery\Send;
use Customs\Dg\Hmzb\Delivery\Ve;

class Clearance_InvDeliveryController extends Ec_Controller_Action
{
    protected $tplDirectory = '';

    public function preDispatch() {
        $this->tplDirectory = "clearance/views/inv-delivery/";
    }

    /**
     * Note:获取列表的提交参数，导出和查询都会用到，放在一个地方
     * User: Yao
     * Date: 2019/2/16
     * Time: 11:20
     */
    private function getCondition() {
        $condition = array();
        $dateFor = $this->_request->getParam('dateFor', '');
        $dateTo = $this->_request->getParam('dateTo', '');
        $isSearchDate = false;
        $conditionTemp['dateFor'] = !empty($dateFor) ? $dateFor : '';
        $conditionTemp['dateTo'] = !empty($dateTo) ? $dateTo : '';
        if (!empty($conditionTemp['dateFor'])) {
            $isSearchDate = true;
            $conditionTemp['dateFor'] = date('Y-m-d H:i:s', strtotime($conditionTemp['dateFor']));
        }
        if (!empty($conditionTemp['dateTo'])) {
            $isSearchDate = true;
            $conditionTemp['dateTo'] = date('Y-m-d H:i:s', strtotime($conditionTemp['dateTo']));
        }
        $params = $this->_request->getParams();
        Common_Common::trim_blank($params);
        $service = new Service_InvtDeliveryBase();
        $condition = $service->getMatchFields($params);
        if ($isSearchDate) {
            $condition['dateFor'] = $conditionTemp['dateFor'];
            $condition['dateTo'] = $conditionTemp['dateTo'];
        }
        return $condition;
    }

    /**/
    public function listAction() {
        if ($this->_request->isPost()) {
            $return = array(
                "state" => 0,
                "message" => "No Data"
            );
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;
            $condition = $this->getCondition();
            $showFields = array(
                'idb_id',
                'pre_del_no',
                'del_no',
                'decl_type',
                'io_flag',
                'target',
                'gross_weight',
                'pack_no',
                'idb_type',
                'buss_type',
                'add_time',
                'last_update',
                'idb_status',
                'idb_zb_status'
            );
            $service = new Service_InvtDeliveryBase();
            $showFields = $service->getFieldsAlias($showFields);
            $count = Service_InvtDeliveryBase::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count > 0) {
                $rows = Service_InvtDeliveryBase::getByCondition($condition, $showFields, $pageSize, $page, 'idb_id desc');
                $return['state'] = $count ? 1 : 0;
                $return['data'] = $rows;
            }
            $return['ioFlag'] = Service_InvtDeliveryBase::getIoFlag();
            $return['zbStatus'] = Service_InvtEntHead::getZbStatus();
            $return['status'] = Service_InvtDeliveryBase::getStatus();
            $return['bussType'] = Service_InvtDeliveryBase::getBussType();
            $return['target'] = Service_InvtDeliveryBase::getTarget();
            $return['size'] = $pageSize;
            $return['page'] = $page;
            die(Zend_Json::encode($return));
        }
        $this->view->bussType = Service_InvtDeliveryBase::getBussType();
        $this->view->zbStatus = Service_InvtEntHead::getZbStatus();
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }
    /**
     * Note:非金二核放单确认
     * User: Yao
     * Date: 2021/5/18
     * Time: 11:24
     */
    public function confirmAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $iddId = $this->_request->getParam('idd_id');
            if (empty($iddId)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $total = 0;
            $success = 0;
            $invList = Service_InvtDeliveryBase::getByField($iddId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            $inv = new Process_InvDelivery();
            $result = $inv->confirm($invList);
            if ($result !== true) {
                throw new Exception('确认失败:' . $result);
            }
            $db->commit();
            $return['state'] = 1;
            $return['message'] = "操作成功";
        } catch (Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
            $return['data'][] = $invList['EtpsInnerInvtNo'] . $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * Note:核放单完成
     * User: Yao
     * Date: 2021/5/18
     * Time: 13:58
     */
    public function completeAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $invtId = $this->_request->getParam('inv_id');
            if (empty($invtId)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $invList = Service_InvtDeliveryBase::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            $delNo = $this->_request->getParam('del_no');
            if(empty($invList['del_no'])){
                if(empty($delNo)){
                    throw new Exception('请填写核放单号');
                }
                $update = [
                    'del_no'=>trim($delNo),
                ];
                Service_InvtDeliveryBase::update($update,$invList['idb_id']);
                $log = [
                    'il_id' => $invList['idb_id'],
                    'note' => '完成',
                    'add_time' => date("Y-m-d H:i:s"),
                    'status_from' => $invList['idb_status'],
                    'status_to' =>$invList['idb_status'],
                    'operater'=>Service_User::getUserId()
                ];
                Service_InvtListLog::add($log);
            }
            $inv = new Process_InvDelivery();
            $result = $inv->complete($invList);
            if ($result !== true) {
                throw new Exception('完成失败');
            }
            $return['state'] = 1;
            $return['message'] = "操作成功";
            $db->commit();
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:添加
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:54
     */
    public function addAction() {
        $return = [
            'state' => 0,
            'message' => ''
        ];
        $id = $this->_request->getParam('id', '');
        $entId = $this->_request->getParam('ent_id','');
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $data = $params['detail'];
                $ve = $params['ve'];
                unset($params['detail']);
                $body = json_decode($data, true);
                $ve = json_decode($ve, true);
                $inv = new Process_InvDelivery();
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                $error = $headerError;
                if(empty($body)){
                    throw new Exception('请添加核放单关联单证表体信息');
                }
                if(empty($ve)){
                    throw new Exception('请添加车辆信息');
                }
                if (!empty($body)) {
                    $bodyError = $inv->validateDecl($body);
                    $error = array_merge($error, $bodyError);
                }
                if (!empty($ve)) {
                    $veError = $inv->validateVe($ve);
                    $error = array_merge($error, $veError);
                }
                if (!empty($error)) {
                    throw new Exception(implode('<br/>', $error));
                }
                $code = $inv->doSave($params, $body, $ve);
                $db->commit();
                $return['state'] = 1;
                $return['message'] = "添加成功：企业内部单号【" . $code . "】";
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
        $this->view->ilId = empty($id) ? '' : $id;
        $this->view->target = Service_InvtDeliveryBase::getTarget();
        $this->view->country = Service_Country::getByCondition([
            'trade_country_not_empty' => true,
        ]);
        $this->view->ioFlag = Service_InvtDeliveryBase::getIoFlag();
        $this->view->bussType = Service_InvtDeliveryBase::getBussType();
        $this->view->customCode = Service_InvtDeliveryBase::getCustomCode();
        $this->view->locationCode = Service_InvtDeliveryBase::getLoactionCode();
        $this->view->reType = Service_InvtDeliveryBase::getRetType();
        $this->view->entId = $entId;
        echo Ec::renderTpl($this->tplDirectory . 'add.tpl', 'layout');
    }

    /**
     * Note:编辑
     * User: Yao
     * Date: 2020/8/12
     * Time: 15:35
     */
    public function editAction() {
        $return = [
            'state' => 0,
            'message' => ''
        ];
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $data = $params['detail'];
                $vetInfo = $params['ve'];
                unset($params['detail']);
                $body = json_decode($data, true);
                $vetInfoArray = json_decode($vetInfo,true);
                $inv = new Process_InvDelivery();
                if (empty($params['idb_id'])) {
                    throw  new Exception('系统异常');
                }
                if(empty($data)){
                    throw new Exception('请添加核放单关联单证表体信息');
                }
                if (empty($vetInfoArray)) {
                    throw new Exception('请添加车辆信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                if (empty($headerError)) {
                    $bodyError = $inv->validateDecl($body);
                    $vetError = $inv->validateVe($vetInfo);
                }
                $error = array_merge($bodyError, $headerError,$vetError);
                if (!empty($error)) {
                    throw new Exception(implode('<br/>', $error));
                }
                $code = $inv->doEdit($params, $body,$vetInfoArray);
                $db->commit();
                $return['state'] = 1;
                $return['message'] = "编辑成功：企业内部单号【" . $code . "】";
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
    }

    /**
     * Note:反填备案序号
     * User: Yao
     * Date: 2020/9/2
     * Time: 16:59
     */
    public function refillRecodeAction() {
        $return = [
            'state' => 0,
            'message' => ''
        ];
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $data = $params['detail'];
                unset($params['detail']);
                $body = json_decode($data, true);
                $inv = new Process_Inv();
                if (empty($params['il_id'])) {
                    throw  new Exception('系统异常');
                }
                if (empty($body)) {
                    throw new Exception('请添加表体信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                if (empty($headerError)) {
                    if ($params['impexp_markcd'] == 'I') {
                        $bodyError = $inv->validateInBodyInfo($body, $params['bwl_no']);
                    } else {
                        throw new Exception('出区核注清单不支持此操作');
                    }
                }
                $error = array_merge($bodyError['error'], $headerError);
                if (!empty($error)) {
                    throw new Exception(implode('<br/>', $error));
                }
                $code = $inv->reFillRecodeNo($params, $body);
                $db->commit();
                $return['state'] = 1;
                $return['message'] = "反填备案号成功：企业内部单号【" . $code . "】";
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
    }

    /**
     * Note:导入数据模板
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:54
     */
    public function importAction() {
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        try {
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/inv-delivery/';
            $uploadInfo = $upload->uploadXls($savePath, 'delivery_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $deliverProcess = new Process_InvDelivery();
            $inv = new Process_InvDeliveryUpload();
            $inv->setFilePath($filePath);
            $headInfo = $inv->getHeadInfo();
            $bodyInfo = $inv->getDeclInfo();
            $vetInfo = $inv->getVet();
            $error = $deliverProcess->validateHeadInfo($headInfo);
            if (!empty($bodyInfo)) {
                $bodyError = $deliverProcess->validateDecl($bodyInfo);
                if (!empty($bodyError)) {
                    $error = array_merge($error, $bodyError);
                }
            }
            if (!empty($vetInfo)) {
                $vetError = $deliverProcess->validateVe($vetInfo);
                if (!empty($vetError)) {
                    $error = array_merge($error, $vetError);
                }
            }
            if (!empty($error)) {
                $return['error'] = $error;
            }else{
                $return['state'] = 1;
                $return['data']= [
                    'head'=>$headInfo,
                    'body'=>$bodyInfo,
                    'vet' =>$vetInfo,
                ];
            }
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));


    }

    /**
     * Note:详情查看
     * User: Yao
     * Date: 2019/12/27
     * Time: 14:48
     */
    public function viewAction() {
        $id = $this->_request->getParam('id', '');
        if (empty($id)) {
            $this->redirect("/default/error/error");
        }
        $invList = Service_InvtDeliveryBase::getByField($id);
        if (empty($invList)) {
            $this->redirect("/default/error/error");
        }
        $log = Service_InvtDeliveryLog::getByCondition([
            'ieh_id' => $invList['ieh_id']
        ], '*', '', '', "idl_id desc");
        $this->view->invList = $invList;
        $this->view->sysStatus = Service_InvtDeliveryBase::getStatus();
        $this->view->zbStatus = Service_InvtDeliveryBase::getZbStatus();
        $this->view->bussType = Service_InvtDeliveryBase::getBussType();
        $this->view->ioFlag = Service_InvtDeliveryBase::getIoFlag();
        $this->view->target = Service_InvtDeliveryBase::getTarget();
        $this->view->custom = Service_InvtDeliveryBase::getCustomCode();
        $this->view->log = $log;
        echo Ec::renderTpl($this->tplDirectory . 'view.tpl', 'layout');
    }

    /**
     * Note:表体的信息
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:43
     */
    public function getDetailAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $id = $this->_request->getPost('inv_id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            $invList = Service_InvtDeliveryDecl::getByCondition([
                'idb_id' => $id
            ], '*');
            $ve = Service_InvtDeliveryVe::getByCondition([
                'idb_id' => $id
            ], '*');
            $return['state'] = 1;
            $return['data']['decl'] = $invList;
            $return['data']['ve'] = $ve;
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:表头信息
     * User: Yao
     * Date: 2020/8/10
     * Time: 18:20
     */
    public function getHeadInfoAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $id = $this->_request->getPost('inv_id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            $invList = Service_InvtDeliveryBase::getByField($id);
            if (empty($invList)) {
                throw new Exception('数据为空');
            }
            $return['state'] = 1;
            $return['data'] = $invList;
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }


    public function concelAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $invtId = $this->_request->getParam('inv_id');
            if (empty($invtId)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $invList = Service_InvtList::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            $inv = new Process_Inv();
            $result = $inv->concel($invList);
            if ($result !== true) {
                throw new Exception('取消失败');
            }
            $return['state'] = 1;
            $message = "操作成功";
            if ($invList['status'] == 2 && $invList['ImpexpMarkcd'] == 'E') {
                $message .= ":请到综保系统取消该核注清单";
            }
            $return['message'] = $message;
            $db->commit();
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:
     * User: Yao
     * Date: 2020/8/21
     * Time: 17:15
     */
    public function makeXmlAction() {
        $id = $this->_request->getParam('id');
        $deliveryBase = Service_InvtDeliveryBase::getByField($id);
        if (empty($deliveryBase)) {
            $this->_redirect('/default/error/error');
        }
        $xml = new Xml();
        $base = new Base();
        $uperHead = array_change_key_case($deliveryBase, CASE_UPPER);
        $base->setFromArray($uperHead);
        $xml->setBase($base);
        $declList = Service_InvtDeliveryDecl::getByCondition([
            'idb_id' => $deliveryBase['idb_id']
        ]);
        if (!empty($declList)) {
            foreach ($declList as $decl) {
                $baseDecl = new  Decl();
                $baseDecl->setFromArray(array_change_key_case($decl, CASE_UPPER));
                $xml->addDecl($baseDecl);
            }
        }
        $evList = Service_InvtDeliveryVe::getByCondition([
            'idb_id' => $deliveryBase['idb_id']
        ]);
        if (!empty($evList)) {
            foreach ($evList as $list) {
                $baseEv = new Ve();
                $baseEv->setFromArray(array_change_key_case($list, CASE_UPPER));
                $xml->addVe($baseEv);
            }
        }
        $xmlString = $xml->toXml();
        header("Content-Type:text/xml;charsert=utf-8");
        echo $xmlString;
    }

    /**
     * Note:发送报文到综保系统
     * User: Yao
     * Date: 2020/8/24
     * Time: 17:04
     */
    public function sendAction() {
        $return = [
            'state' => 0,
            'message' => '',
        ];
        try {
            $id = $this->_request->getParam('id');
            $deliveryBase = Service_InvtDeliveryBase::getByField($id);
            if (empty($deliveryBase)) {
                throw new Exception('核放单信息不存在');
            }
            $xml = new Xml();
            $base = new Base();
            $uperHead = array_change_key_case($deliveryBase, CASE_UPPER);
            $base->setFromArray($uperHead);
            $xml->setBase($base);
            $declList = Service_InvtDeliveryDecl::getByCondition([
                'idb_id' => $deliveryBase['idb_id']
            ]);
            if (!empty($declList)) {
                foreach ($declList as $decl) {
                    $baseDecl = new  Decl();
                    $baseDecl->setFromArray(array_change_key_case($decl, CASE_UPPER));
                    $xml->addDecl($baseDecl);
                }
            }
            $evList = Service_InvtDeliveryVe::getByCondition([
                'idb_id' => $deliveryBase['idb_id']
            ]);
            if (!empty($evList)) {
                foreach ($evList as $list) {
                    $baseEv = new Ve();
                    $baseEv->setFromArray(array_change_key_case($list, CASE_UPPER));
                    $xml->addVe($baseEv);
                }
            }
            $xmlString = $xml->toXml();
            $send = new Send();
            $result = $send->send($xmlString);
            if ($result['state'] != 1) {
                throw new Exception($result['message']);
            }
            $return['state'] = $result['state'];
            $return['message'] = $result['message'];
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    public function exportAction(){
        set_time_limit(3600);
        require_once "PHPExcel.php";
        require_once "PHPExcel/IOFactory.php";
        $path = APPLICATION_PATH.'/../data/xls/inv_ent_delivery.xls';
        $excel = PHPExcel_IOFactory::load($path);
        $headSheet = $excel->getSheet(0);
        $bodySheet = $excel->getSheet(1);
        $carSheet = $excel->getSheet(2);
        $id = $this->_request->getParam('id');
        $invent = Service_InvtDeliveryBase::getByField($id);
        if($invent){
            $invtBody = Service_InvtDeliveryDecl::getByCondition([
                'idb_id'=>$invent['idb_id']
            ]);
            $ve = Service_InvtDeliveryVe::getByCondition([
                'idb_id'=>$invent['idb_id']
            ]);
            $headSheet->setCellValue('A2',$invent['buss_type']);//业务类型
            $headSheet->setCellValue('B2',$invent['io_flag']);//进出标志
            $headSheet->setCellValue('C2',$invent['target']);//货物流向
            $headSheet->setCellValue('D2',$invent['customs_code']);//主管关区代码
            $headSheet->setCellValue('E2',$invent['trade_code']);//区内企业代码
            $headSheet->setCellValue('F2',$invent['trade_name']);//区内企业名称
            $headSheet->setCellValue('G2',$invent['location_code']);//监管场所代码
            $headSheet->setCellValue('H2',$invent['app_er']);//申请人姓名
            $headSheet->setCellValue('I2',$invent['re_type']);//退运类型
            $headSheet->setCellValue('J2',$invent['re_reason']);//退运原因
            $headSheet->setCellValue('K2',$invent['rel_del_no']);//关联原核放单编号
            $headSheet->setCellValue('L2',$invent['remark']);//备注
            if(empty($invtBody)){
                $bodySheet->fromArray([array_fill('0','12','')],'','A2');
            }else{
                $index = 2;
                foreach ($invtBody as $body){
                    $bodySheet->setCellValue('A'.$index,$body['form_type']);//单证类型
                    $bodySheet->setCellValue('B'.$index,$body['key_no']);//关联单证号
                    $bodySheet->setCellValue('C'.$index,$body['ref_entry_id']);//报关申请单关联的报关单编号
                    $bodySheet->setCellValue('D'.$index,$body['reg_g_no']);//报关申请单商品和报关单商品的对应关系
                    $index++;
                }
            }
            if(empty($ve)){
                $carSheet->fromArray([array_fill('0','8','')],'','A2');
            }else{
                $index = 2;
                foreach ($ve as $body){
                    $carSheet->setCellValue('A'.$index,$body['ve_order']);//车次号
                    $carSheet->setCellValue('B'.$index,$body['ic_no']);//IC卡号
                    $carSheet->setCellValue('C'.$index,$body['ve_no']);//承运车辆备案号
                    $carSheet->setCellValue('D'.$index,$body['ve_name']);//承运车辆车牌号*	托架类型
                    $carSheet->setCellValue('E'.$index,$body['bracket_type']);//托架类型
                    $carSheet->setCellValue('F'.$index,$body['container_type']);//集装箱类型
                    $carSheet->setCellValue('G'.$index,$body['gross_weight']);//货物毛重
                    $carSheet->setCellValue('H'.$index,$body['pack_no']);//件数
                    $index++;
                }
            }
        }else{
            $headSheet->fromArray([array_fill('0','12','')],1,'A2');
            $bodySheet->fromArray([array_fill('0','4','')],1,'A2');
            $carSheet->fromArray([array_fill('0','8','')],1,'A2');
        }
        $filename = date("Y-m-d").mt_rand(100,999).'非金二核核放单.xls';
        $filename = mb_convert_encoding($filename,'gbk');
        $writer = PHPExcel_IOFactory::createWriter($excel,'Excel5');
        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');
        $writer->save('php://output');
    }
}