<?php

/**
 * Class Clearance_InvManifestController
 * User: Yao
 * Date: 2021/1/6
 * Note:入区QG单列表
 */
class Clearance_QgController extends Ec_Controller_Action
{
    protected $tplDirectory = '';

    public function preDispatch() {
        $this->tplDirectory = "clearance/views/qg/";
    }

    /**
     * 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_InvtQg();
        $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(
                'iq_id',
                'iq_code',
                'iq_type',
                'iq_count',
                'iq_status',
                'add_time',
                'update_time'
            );
            $service = new Service_InvtQg();
            $showFields = $service->getFieldsAlias($showFields);
            $count = Service_InvtQg::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count > 0) {
                $rows = Service_InvtQg::getByCondition($condition, $showFields, $pageSize, $page, 'iq_id desc');
                $return['state'] = $count ? 1 : 0;
                $return['data'] = $rows;
            }
            $return['status'] = Service_InvtQg::getStatus();
            $return['type'] = Service_InvtQg::getType();
            $return['size'] = $pageSize;
            $return['page'] = $page;
            die(Zend_Json::encode($return));
        }
        $this->view->type = Service_InvtQg::getType();
        $this->view->transMethod = Service_InvtList::getTrspMethod();
        $this->view->country = Service_Country::getByCondition([
            'trade_country_not_empty'=>true,
        ]);
        $this->view->supvModecd = Service_InvtList::getsupvModecd();
        $this->view->portcd = Service_InvtList::getImexpPortcd();
        $this->view->invtType = Service_InvtList::getInvtType();
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }

    /**
     * Note:创建QG单
     * User: Yao
     * Date: 2021/1/6
     * Time: 17:25
     */
    public function createAction() {
        if ($this->_request->isPost()) {
            $return = [
                'state' => 0,
                'message' => 'fail',
                'success' => [],
                'error' => [],
            ];
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $invOrderProcess = new Process_InvQg();
                $validateError = $invOrderProcess->validateHead($params);
                if(!empty($validateError)){
                    $return['error']=$validateError;
                    throw new Exception('参数验证错误：');
                }
                $codeList = $params['receiving_code'];
                $iqType = $params['E2'];
                $codeArray = preg_split('/\n|,/', $codeList);
                $codeArray = array_map(function ($v) {
                    return preg_replace('/\r/', '', $v);
                }, $codeArray);
                $codeArray = array_filter($codeArray);
                $number = Common_GetNumber::getCode('invQj', '', 'QG');
                $now = date("Y-m-d H:i:s");
                $invQg = [
                    'iq_code' => $number,
                    'iq_status' => 0,
                    'etps_id'=>$params['etps_info'],
                    'iq_type' => $iqType,
                    'trsp_modecd'=>$params['trsp_modecd'],
                    'supv_modecd'=>$params['supv_modecd'],
                    'impexp_portcd'=>$params['impexp_portcd'],
                    'stship_trsarv_natcd'=>$params['stship_trsarv_natcd'],
                    'gen_dec_flag'=>$params['gen_dec_flag'],
                    'add_time' => date("Y-m-d H:i:s"),
                ];
                $iqId = Service_InvtQg::add($invQg);
                $orderTotal = 0;
                $errorMsg = [];
                foreach ($codeArray as $receivingCode) {
                    $errror = $invOrderProcess->validate([
                        'receiving_code' => $receivingCode
                    ]);
                    if (!empty($errror)) {
                        $errorMsg[] = implode(',', $errror);
                    } else {
                        $orderTotal++;
                        $invtQgReceiving = [
                            'iq_id' => $iqId,
                            'receiving_code' => $receivingCode,
                            'add_time' => $now
                        ];
                        Service_InvtQgReceiving::add($invtQgReceiving);
                    }
                }
                if (!empty($errorMsg)) {
                    throw new Exception(implode(",", $errorMsg));
                }
                $updateInvManifest = [
                    'iq_count' => $orderTotal
                ];
                Service_InvtQg::update($updateInvManifest, $iqId);
                $log = [
                    'iq_id' => $iqId,
                    'operater_id' => $this->_userAuth->userId,
                    'add_time' => date("Y-m-d"),
                    'note' => "创建QG单",
                ];
                Service_InvtQgLog::add($log);
                $return['message'] = "创建成功：QG单号：" . $number;
                $return['fail'] = array_diff($codeArray, $return['success']);
                $return['state'] = 1;
                $db->commit();
            } catch (Exception $e) {
                $return['message'] = $e->getMessage();
                $db->rollBack();
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . 'create.tpl', 'layout');
    }

    /**
     * Note:生成核注清单信息
     * User: Yao
     * Date: 2020/11/14
     * Time: 11:05
     */
    public function makeInvAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'inv_code' => [],
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $imCode = $this->_request->getParam('iq_code');
            if (empty($imCode)) {
                throw new Exception('汇单号为空');
            }
            $invtQg = Service_InvtQg::getByField($imCode);
            if (empty($invtQg)) {
                throw new Exception('信息不存在');
            }
            if ($invtQg['iq_status'] != 0) {
                throw new Exception('改QG单不是草稿状态，无法操作');
            }
            $invOrderProcess = new Process_InvQg();
            $invOrderProcess->makeInvByIm($invtQg);
            Service_InvtQg::update([
                'iq_status' => 1,
                'update_time' => date("Y-m-d H:i:s")
            ], $invtQg['iq_id']);
            $log = [
                'iq_id' => $invtQg['iq_id'],
                'operater_id' => $this->_userAuth->userId,
                'add_time' => date("Y-m-d H:i:s"),
                'note' => "生成核注清单" . implode(',', $invOrderProcess->getInvCode()),
                'status_from' => $invtQg['iq_status'],
                'status_to' => 1,
            ];
            Service_InvtQgLog::add($log);
            $db->commit();
            $return['inv_code'] = $invOrderProcess->getInvCode();
            $return['state'] = 1;
            $return['message'] = '核注清单生成成功';
        } catch (Exception $e) {
            echo $e;
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:查看页面
     * User: Yao
     * Date: 2020/11/18
     * Time: 17:52
     */
    public function viewAction() {
        $id = $this->_request->getParam('id');
        if (empty($id)) {
            $this->_redirect('/default/error/error');
        }
        $invtQg = Service_InvtQg::getByField($id);
        if (empty($invtQg)) {
            $this->_redirect('/default/error/error');
        }
        $invtQgReceiving = Service_InvtQgReceiving::getByCondition([
            'iq_id' => $invtQg['iq_id']
        ]);
        $invtQgInvt = Service_InvtQgInvt::getByCondition([
            'iq_id' => $invtQg['iq_id']
        ], '*', '0', '0', '', 'etps_inner_invt_no');
        if (!empty($invtQgInvt)) {
            $invStatus = Service_InvtList::getStatus();
            foreach ($invtQgInvt as $key => $inv) {
                $invInfo = Service_InvtList::getByField($inv['etps_inner_invt_no'], 'EtpsInnerInvtNo');
                $invtQgInvt[$key]['status'] = $invInfo['status'];
                $invtQgInvt[$key]['status_desc'] = $invStatus[$invInfo['status']];
                $invtQgInvt[$key]['il_id'] = $invInfo['il_id'];
            }
        }
        $log = Service_InvtQgLog::getJoinLeftByCondition([
            'iq_id' => $invtQg['iq_id']
        ],'*','','','iql_id desc');
        $this->view->invtQg = $invtQg;
        $this->view->invtQgInvt = $invtQgInvt;
        $this->view->invtQgReceiving = $invtQgReceiving;
        $this->view->status = Service_InvtQg::getStatus();
        $this->view->type = Service_InvtQg::getType();
        $this->view->qgLog = $log;
        echo Ec::renderTpl($this->tplDirectory . 'view.tpl', 'layout');
    }

    /**
     * Note:入库单信息
     * User: Yao
     * Date: 2020/11/16
     * Time: 17:14
     */
    public function receivingListAction() {
        $return = [
            'Rows' => [],
            'total' => 0
        ];
        try {
            if ($this->_request->isPost()) {
                $id = $this->_request->getParam('iq_id');
                if (empty($id)) {
                    throw new Exception('参数错误');
                }
                $page = $this->_request->getParam('page', 1);
                $pageSize = $this->_request->getParam('pagesize', 20);
                $receivingCode = $this->_request->getParam('receiving_code', '');
                $pageSize = (int)$pageSize;
                $pageSize = $pageSize > 2000 ? 2000 : $pageSize;
                $condition = [
                    'iq_id' => $id,
                    'receiving_code' => trim($receivingCode),
                ];
                $invtMainiFestInfo = Service_InvtQgReceiving::getByCondition($condition, '*', $pageSize, $page);
                $count = Service_InvtQgReceiving::getByCondition($condition, 'count(*)');
                $return['Rows'] = $invtMainiFestInfo;
                $return['Total'] = $count;
            }
        } catch (Exception $e) {

        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:删除入库单
     * User: Yao
     * Date: 2020/11/17
     * Time: 11:56
     */
    public function deleteReceivingAction() {
        $return = [
            'state' => 0,
            'message' => 'fail'
        ];
        try {
            if (!$this->_request->isPost()) {
                throw new Exception('非法提交');
            }
            $iqId = $this->_request->getParam('iq_id', '');
            if (empty($iqId)) {
                throw new Exception('参数错误');
            }
            $iqrIdList = $this->_request->getParam('iqr_id');
            $qgInfo = Service_InvtQg::getByField($iqId);
            if (empty($qgInfo)) {
                throw new Exception('QG单信息不存在');
            }
            $idListArray = explode(',', $iqrIdList);
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                //还没有生成核注清单，只删除对应关系就可以了
                if ($qgInfo['iq_status'] == 0) {
                    $receivingCodeList = [];
                    $deleteNumber = 0;
                    foreach ($idListArray as $id) {
                        $qgReceiving = Service_InvtQgReceiving::getByField($id);
                        Service_InvtQgReceiving::delete($id);
                        $deleteNumber++;
                        $receivingCodeList[] = $qgReceiving['receiving_code'];
                    }
                    $updateManifest = [
                        'iq_count' => $qgInfo['iq_count'] - $deleteNumber,
                        'update_time' => date("Y-m-d H:i:s")
                    ];
                    Service_InvtQg::update($updateManifest, $qgInfo['iq_id']);
                    $log = [
                        'iq_id' => $qgInfo['iq_id'],
                        'operater_id' => $this->_userAuth->userId,
                        'add_time' => date("Y-m-d H:i:s"),
                        'note' => '删除入库单' . implode(',', $receivingCodeList),
                        'status_from' => $qgInfo['iq_status'],
                        'status_to' => $qgInfo['iq_status'],
                    ];
                    Service_InvtQgLog::add($log);
                } else {
                    /**
                     * 已生成核注清单，要删除核注清单信息
                     * 先统计出来入库单详细和对应的核注清单数据
                     * */
                    $qgReceivingDetail = [];
                    $allReceivingCode = [];
                    foreach ($idListArray as $id) {
                        $qgReceiving = Service_InvtQgReceiving::getByField($id);
                        if (empty($qgReceiving)) {
                            throw new Exception('提交参数错误');
                        }
                        Service_InvtQgReceiving::delete($id);
                        $allReceivingCode[] = $qgReceiving['receiving_code'];
                        $qgInvtList = Service_InvtQgInvt::getByCondition([
                            'receiving_code' => $qgReceiving['receiving_code']
                        ], '*', '', '', '');
                        foreach ($qgInvtList as $qgInv) {
                            $qgReceivingDetail[$qgInv['etps_inner_invt_no']][] = [
                                'receiving_code' => $qgInv['receiving_code'],
                                'rd_id' => $qgInv['rd_id'],
                                'ilb_id' => $qgInv['ilb_id']
                            ];
                        }
                    }
                    foreach ($qgReceivingDetail as $invNo => $qgr) {
                        $summaryQg = [];
                        $receivingCodeList = [];
                        foreach ($qgr as $qg) {
                            $receivingDetailInfo = Service_ReceivingDetail::getByField($qg['rd_id']);
                            if (!isset($summaryQg[$qg['ilb_id']])) {
                                $summaryQg[$qg['ilb_id']] = $receivingDetailInfo['rd_receiving_qty'];
                            } else {
                                $summaryQg[$qg['ilb_id']] += $receivingDetailInfo['rd_receiving_qty'];
                            }
                            $receivingCodeList[] = $qg['receiving_code'];
                        }
                        $invtInfo = Service_InvtList::getByField($invNo, 'EtpsInnerInvtNo');
                        $invtListBody = Service_InvtListBody::getByCondition([
                            'il_id' => $invtInfo['il_id']
                        ]);
                        $invtListBodyCopy = $invtListBody;
                        $updateBody = [];
                        $deleteBody = [];
                        foreach ($invtListBody as $key => $body) {
                            if ($summaryQg[$body['ilb_id']]) {
                                if ($summaryQg[$body['ilb_id']] == $body['DclQty']) {
                                    $deleteBody[] = $body['ilb_id'];
                                    unset($invtListBodyCopy[$key]);
                                } else {
                                    $updateBody[$body['ilb_id']] = $body['DclQty'] - $summaryQg[$body['ilb_id']];
                                }
                            }
                        }

                        //核注清单表体全部删除了，就直接放回删除状态
                        if (empty($invtListBodyCopy)) {
                            Service_InvtList::update([
                                'status' => 0
                            ], $invtInfo['il_id']);
                            $invLog = [
                                'il_id' => $invtInfo['il_id'],
                                'note' => '删除入库单' . implode(',', array_unique($receivingCodeList)),
                                'add_time' => date("Y-m-d H:i:s"),
                                'status_from' => $invtInfo['status'],
                                'status_to' => $invtInfo['status'],
                                'edite_info' => json_encode([]),
                            ];
                            Service_InvtListLog::add($invLog);
                        } else {
                            //部分删除，只删除表体信息
                            $updateContent = [];
                            if ($deleteBody) {
                                foreach ($deleteBody as $ilbId) {
                                    $listBodyInfo = Service_InvtListBody::getByField($ilbId);
                                    $updateContent['delete'][] = $listBodyInfo;
                                    Service_InvtListBody::delete($ilbId);
                                }
                            }
                            if ($updateBody) {
                                foreach ($updateBody as $ilbId => $updateQty) {
                                    $listBodyInfo = Service_InvtListBody::getByField($ilbId);
                                    $updateContent['update'][] = [
                                        'ilb_id' => $ilbId,
                                        'before_dcl_qty' => $listBodyInfo['DclQty'],
                                        'after_dcl_qty' => $updateQty
                                    ];
                                    Service_InvtListBody::update([
                                        'DclQty' => $updateQty
                                    ], $ilbId);
                                }
                            }

                            $invLog = [
                                'il_id' => $invtInfo['il_id'],
                                'note' => '删除入库单' . implode(',', array_unique($receivingCodeList)),
                                'add_time' => date("Y-m-d H:i:s"),
                                'status_from' => $invtInfo['status'],
                                'status_to' => $invtInfo['status'],
                                'edite_info' => json_encode($updateContent),
                            ];
                            Service_InvtListLog::add($invLog);
                        }
                    }
                    $updateManifest = [
                        'iq_count' => $qgInfo['iq_count'] - count($allReceivingCode),
                        'update_time' => date("Y-m-d H:i:s")
                    ];
                    Service_InvtQg::update($updateManifest, $qgInfo['iq_id']);
                    $log = [
                        'iq_id' => $qgInfo['iq_id'],
                        'operater_id' => $this->_userAuth->userId,
                        'add_time' => date("Y-m-d H:i:s"),
                        'note' => '删除入库单' . implode(',', $allReceivingCode),
                        'status_from' => $qgInfo['iq_status'],
                        'status_to' => $qgInfo['iq_status'],
                    ];
                    Service_InvtQgLog::add($log);
                }

                $db->commit();
                $return['state'] = 1;
                $return['message'] = implode(",", $allReceivingCode) . '删除成功';
            } catch (Exception $e) {
                echo $e;
                $return['message'] = $e->getMessage();
                $db->rollBack();
            }
        }catch (Exception $e){
            echo $e;
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:增加入库单
     * User: Yao
     * Date: 2021/1/12
     * Time: 11:18
     */
    public function addReceivingAction() {
        $return = [
            'state' => 0,
            'message' => 'fail'
        ];
        try {
            if (!$this->_request->isPost()) {
                throw new Exception('非法提交');
            }
            $receivingCodeList = $this->_request->getParam('add_receiving', '');
            if (empty($receivingCodeList)) {
                throw new Exception('参数错误');
            }
            $iqId = $this->_request->getParam('im_id');
            $iqInfo = Service_InvtQg::getByField($iqId);
            if (empty($iqInfo)) {
                throw new Exception('QG单信息不存在');
            }
            $receivingCodeArray = explode(',', $receivingCodeList);
            $receivingCodeArray = array_filter(array_unique($receivingCodeArray));
            $db = Common_Common::getAdapter();
            $qgProcess = new Process_InvQg();
            $addNumber = 0;
            $db->beginTransaction();
            try {
                $errorOrder = [];
                foreach ($receivingCodeArray as $receivingCode) {
                    $addNumber++;
                    $errorInfo = $qgProcess->validate(['receiving_code' => $receivingCode]);
                    if (!empty($errorInfo)) {
                        $errorOrder[] = $receivingCode . implode(',', $errorInfo);
                    }
                }
                if (!empty($errorOrder)) {
                    throw new Exception(implode(',', $errorOrder) . '已经生成核注清单，不能重复添加');
                }
                foreach ($receivingCodeArray as $receivingCode) {
                    $qgProcess->addReceiving($receivingCode, $iqInfo['iq_code']);
                }
                $updateManifest = [
                    'iq_count' => $iqInfo['iq_count'] + $addNumber,
                    'update_time' => date("Y-m-d H:i:s")
                ];
                Service_InvtQg::update($updateManifest, $iqInfo['iq_id']);
                $log = [
                    'iq_id' => $iqInfo['iq_id'],
                    'operater_id' => $this->_userAuth->userId,
                    'add_time' => date("Y-m-d H:i:s"),
                    'note' => '添加入库单' . implode(',', $receivingCodeArray),
                    'status_from' => $iqInfo['iq_status'],
                    'status_to' => $iqInfo['iq_status'],
                ];
                Service_InvtQgLog::add($log);
                $db->commit();
                $return['message'] = '添加成功';
                $return['state'] = 1;
            } catch (Exception $e) {
                $return['message'] = $e->getMessage();
                $db->rollBack();
            }
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }


}