<?php 
namespace backend\controllers;

use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\BatchRemitLog;
use backend\models\RemitLog;
use backend\models\RemitOrder;
use common\helpers\Utils;
use common\pay\RemitForm;
use Yii;
use yii\helpers\ArrayHelper;

class RemitController extends BaseController
{
    /**
     * 获取财务打款审核列表
     * @return \yii\web\Response
     */
    public function actionGetFinanceRemitList()
    {
        $data = Yii::$app->getRequest()->get();
        $data['status'] = isset($data['status']) ? trim($data['status']) : '';
        $data['batch_no'] = isset($data['batch_no']) ? trim($data['batch_no']) : '';
        $data['inStartTime'] = isset($data['inStartTime']) ? trim($data['inStartTime']) : '';
        $data['inEndTime'] = isset($data['inEndTime']) ? trim($data['inEndTime']) : '';
        $data['page'] = isset($data['page']) ? max(intval($data['page']), 1) : 1;
        $data['pageSize'] = isset($data['pageSize']) ? intval($data['pageSize']) : 20;
        $data['orderBy'] = isset($data['orderBy']) ? trim($data['orderBy']) : 'create_time desc';
        $data['search'] = isset($data['search']) ? trim($data['search']) : '';

        $data = ValidatorHelper::validateData($data, [
            ['status', 'string'],
            ['inStartTime', 'integer'],
            ['inEndTime', 'integer'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        
        $query = RemitOrder::find()
            ->select('batch_no,amount,audit_status,audit_name,audit_reason,
            reaudit_name,reaudit_reason,audit_time,reaudit_time,create_time')
            ->addSelect(['count(*) as batch_count,sum(amount) as cny_amount']);
            // ->orderBy($data['orderBy']);
        $where = [];
        if ($data['status'] == 'all') {
            // 全部列表
        } else if ($data['status'] == 'first_trial') {
            // 初审列表明细
            $where = [
                'OR',
                ['audit_status' => 0],
                ['audit_status' => 4],
            ];
        } else if ($data['status'] == 're_trial') {
            // 复审列表明细
            $where = [
                'AND',
                ['audit_status' => 1],
            ];
            $data['orderBy'] = 'audit_time desc';
        } else {
            // 审核不通过明细
            $where = [
                'AND',
                ['audit_status' => 3],
            ];
        }
        $query->orderBy($data['orderBy']);
        $query->where($where);
        $query->andFilterWhere(['>=', 'create_time', $data['inStartTime']]);
        $query->andFilterWhere(['<', 'create_time', $data['inEndTime']]);
        $query->andFilterWhere([
            'or',
            ['like', 'batch_no', $data['search']]
        ]);
        
        if (!empty($data['batch_no'])) {
            $query->andFilterWhere(['batch_no' => $data['batch_no']]);
        }

        $queryClone = clone $query;

        $query->groupBy('batch_no');
        
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        
        if ($result) {
            // 统计
            $sum = $queryClone->select(['COUNT(*) AS pay_count', 'SUM(amount) AS amount_sum'])->asArray()->limit(1)->one();
            $lastRow = [
                'batch_no' => '',
                'batch_count' => $sum['pay_count'],
                'cny_amount' => !empty($sum['amount_sum']) ? $sum['amount_sum'] : 0,
                'create_time' => '',
                'audit_status' => null,
                'audit_time' => '',
                'audit_reason' => '',
                'audit_name' => '',
                'reaudit_time' => '',
                'reaudit_reason' => '',
                'reaudit_name' => '',
            ];
            array_push($result['dataList'], $lastRow);

            // 有小数就显示小数，没有就只显示整数部分
            if ($result['dataList']) {
                foreach ($result['dataList'] as $k => $v) {
                    $result['dataList'][$k]['cny_amount'] = Utils::formatFloatOrInt($v['cny_amount']);
                }
            }
        }
        
        return $this->outJson(1, $result);
    }

    /**
     * 批次详细信息
     * @return \yii\web\Response
     */
    public function actionFinanceRemitDetail()
    {
        $data = Yii::$app->getRequest()->get();
        $data['batch_no'] = isset($data['batch_no']) ? trim($data['batch_no']) : '';
        $data['remit_no'] = isset($data['remit_no']) ? trim($data['remit_no']) : '';
        $data['page'] = isset($data['page']) ? max(intval($data['page']), 1) : 1;
        $data['pageSize'] = isset($data['pageSize']) ? intval($data['pageSize']) : 20;
        $data['orderBy'] = isset($data['orderBy']) ? trim($data['orderBy']) : 'remit_no asc';
        $data['search'] = isset($data['search']) ? trim($data['search']) : '';

        $query = RemitOrder::find()
            ->select('id,batch_no,remit_no,pay_type,biz_no,payee_name,
            amount,bank_name,bank_branch,bank_card_no,bank_province,bank_city,bank_code,memo,ret_msg')
            ->andWhere(['batch_no' => $data['batch_no']]);
        if (!empty($data['search'])) {
            $query->andFilterWhere(['like', 'remit_no', $data['search']]);
        }

        if (!empty($data['remit_no'])) {
            $query->andFilterWhere(['like', 'remit_no', $data['remit_no']]);
        }

        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        return $this->outJson(1, $result);
    }

    /**
     * 获取某条记录的备注
     */
    public function actionMemo()
    {
        $data = \Yii::$app->getRequest()->get();
        $data['id'] = isset($data['id']) ? $data['id'] : 0;
        $remit = RemitOrder::findOne(['id' => $data['id']]);
        return $this->outJson(1, $remit);
    }
    /**
     * 修改某条记录的备注
     */
    public function actionMemoUpdate()
    {
        $data = \Yii::$app->getRequest()->post();
        $data['id'] = isset($data['id']) ? $data['id'] : 0;
        $data['memo'] = isset($data['memo']) ? $data['memo'] : '';

        $info = RemitOrder::findOne(['id' => $data['id']]);

        if (!$info) {
            return $this->outJson(0, [], '该记录不存在');
        }

        $info->memo = $data['memo'];

        $rs = $info->save();

        if (!$rs) {
            return $this->outJson(0, [], '数据操作失败');
        }
        return $this->outJson(1, ['id' => $info['id']], '操作成功');
    }
    
    /**
     * 检测批次号是否存在
     * @return \yii\web\Response
     */
    public function actionCheckBatchNo()
    {
        $batchNo = trim(Yii::$app->getRequest()->get('batchNo'));
        if ($batchNo == '' || !is_numeric($batchNo)) {
            return $this->outJson(0, [], '参数非法');
        }

        if (RemitOrder::find()->where(['batch_no' => $batchNo])->exists()) {
            return $this->outJson(0, [], '批次号已存在');
        }

        return $this->outJson(1, $batchNo, "操作成功");
    }

    /**
     * 导入批次
     * @return \yii\web\Response
     * @throws \yii\db\Exception
     */
    public function actionImportRemitOrder()
    {
        $data = \Yii::$app->getRequest()->post();
        $data['list'] = json_decode($data['list'], true);
        if (!empty($data['list'])) {
            $rows = [];
            foreach ($data['list'] as $item) {
                $remitNo = RemitOrder::generateRemitNo();
                if ($remitNo) {
                    $rows[] = [
                        'remit_no' => $remitNo,
                        'batch_no' => $data['batch_no'],
                        'biz_type' => 1,
                        'biz_no' => $item[0],
                        'pay_type' => 5,
                        'payee_name' => $item[1],
                        'amount' => $item[2],
                        'bank_name' => $item[3],
                        'bank_branch' => $item[4],
                        'bank_card_no' => $item[5],
                        'bank_province' => $item[6],
                        'bank_city' => $item[7],
                        'bank_code' => $item[8],
                        'memo' => $item[9],
                        'create_time' => time(),
                    ];
                }
            }
            if ($rows) {
                $command = RemitOrder::getDb()->createCommand();
                $columns = array_combine(array_keys($rows[0]), array_keys($rows[0]));
                $sql = $command->batchInsert(RemitOrder::tableName(), $columns, $rows)->getSql();
                if ($command->setSql(str_ireplace("INSERT INTO", "INSERT IGNORE INTO", $sql))->execute()) {
                    // 记录日志
                    $logData = [];
                    $logData['memo'] = '导入批次';
                    isset($data['admin_id']) && $logData['admin_id'] = trim($data['admin_id']);
                    isset($data['admin_name']) && $logData['admin_name'] = trim($data['admin_name']);
                    isset($data['admin_ip']) && $logData['admin_ip'] = trim($data['admin_ip']);
                    BatchRemitLog::addLog($data, $logData);
                    return $this->outJson(1, [], '导入批次成功');
                } else {
                    return $this->outJson(0, [], '123');
                }
            } else {
                return $this->outJson(0, [], '234');
            }
        } else {
            return $this->outJson(0, [], '表中无数据');
        }
    }

    /**
     * 操作日志
     * @return \yii\web\Response
     */
    public function actionGetBatchRemitLog()
    {
        $data = Yii::$app->getRequest()->get();
        $data['batch_no'] = isset($data['batch_no']) ? $data['batch_no'] : '';

        $rs = BatchRemitLog::find()->where(['batch_no' => $data['batch_no']])->asArray()->all();
        return $this->outJson(1, $rs);
    }

    /**
     * 批次初审
     * @return \yii\web\Response
     */
    public function actionBatchAudit()
    {
        $data = Yii::$app->getRequest()->post();
        if (!isset($data['batch_no']) || trim($data['batch_no']) == '') {
            return $this->outJson(0, [], '打款批次号不能为空');
        }
        $batchNo = $data['batch_no'];
        if (!isset($data['audit_status']) || trim($data['audit_status']) == '') {
            return $this->outJson(0, [], '审核状态不能为空');
        }
        $model = RemitOrder::findByBatchNo($batchNo);
        if ($model == null) {
            return $this->outJson(0, [], '打款单不存在');
        }
        if ($model->doBatchAudit($data)) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], $model->getFirstError('audit_status'));
        }
    }

    /**
     * 批次复审
     * @return \yii\web\Response
     */
    public function actionBatchReAudit()
    {
        $data = Yii::$app->getRequest()->post();
        if (!isset($data['batch_no']) || trim($data['batch_no']) == '') {
            return $this->outJson(0, [], '打款批次号不能为空');
        }
        $batchNo = $data['batch_no'];
        if (!isset($data['audit_status']) || trim($data['audit_status']) == '') {
            return $this->outJson(0, [], '审核状态不能为空');
        }
        $model = RemitOrder::findByBatchNo($batchNo);
        if ($model == null) {
            return $this->outJson(0, [], '打款单不存在');
        }
        if ($model->doBatchReAudit($data)) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], $model->getFirstError('audit_status'));
        }
    }

    /**
     * 创建打款单
     * @return \yii\web\Response
     */
    public function actionCreate()
    {
        $data = Yii::$app->getRequest()->post();
        $unsetFields = ['audit_status', 'audit_admin_id', 'audit_name', 'audit_reason', 'audit_time',
            'reaudit_admin_id', 'reaudit_name', 'reaudit_reason', 'reaudit_time', 'pay_status', 'pay_time',
            'complete_time', 'out_no', 'out_no_crc32', 'ret_code', 'res_code', 'ret_msg', 'sign',
            'create_time', 'last_modified'];
        foreach ($unsetFields as $field) {
            unset($data[$field]);
        }
        if (!isset($data['biz_no']) || trim($data['biz_no']) == '') {
            return $this->outJson(0, [], '业务单号不能为空');
        }
        if (!isset($data['biz_type']) || trim($data['biz_type']) == '') {
            return $this->outJson(0, [], '业务类型不能为空');
        }
        if (RemitOrder::checkBizExist($data['biz_no'], $data['biz_type'])) {
            return $this->outJson(0, [], '业务号已存在，请勿重复添加');
        }
        $remitNo = RemitOrder::generateRemitNo();
        if ($remitNo == false) {
            return $this->outJson(0, [], '打款单号生成失败');
        }
        $data['remit_no'] = $remitNo;
        $data['create_time'] = time();
        $model = new RemitOrder();
        $model->setAttributes($data);
        if ($model->save()) {
            $logData = [];
            $logData['memo'] = "创建打款单";
            isset($data['admin_id']) && $logData['admin_id'] = trim($data['admin_id']);
            isset($data['admin_name']) && $logData['admin_name'] = trim($data['admin_name']);
            isset($data['admin_ip']) && $logData['admin_ip'] = trim($data['admin_ip']);
            RemitLog::addLog($model->getAttributes(), $logData);
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], $model->getFirstErrors());
        }
    }

    /**
     * 初审
     * @return \yii\web\Response
     */
    public function actionAudit()
    {
        $data = Yii::$app->getRequest()->post();
        if (!isset($data['remit_no']) || trim($data['remit_no']) == '') {
            return $this->outJson(0, [], '打款单号不能为空');
        }
        $remitNo = $data['remit_no'];
        if (!isset($data['audit_status']) || trim($data['audit_status']) == '') {
            return $this->outJson(0, [], '审核状态不能为空');
        }
        $model = RemitOrder::findByRemitNo($remitNo);
        if ($model == null) {
            return $this->outJson(0, [], '打款单不存在');
        }
        if ($model->doAudit($data)) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], $model->getFirstError('audit_status'));
        }
    }

    /**
     * 复审
     * @return \yii\web\Response
     */
    public function actionReaudit()
    {
        $data = Yii::$app->getRequest()->post();
        if (!isset($data['remit_no']) || trim($data['remit_no']) == '') {
            return $this->outJson(0, [], '打款单号不能为空');
        }
        $remitNo = $data['remit_no'];
        if (!isset($data['audit_status']) || trim($data['audit_status']) == '') {
            return $this->outJson(0, [], '审核状态不能为空');
        }
        $model = RemitOrder::findByRemitNo($remitNo);
        if ($model == null) {
            return $this->outJson(0, [], '打款单不存在');
        }
        if ($model->doReAudit($data)) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], $model->getFirstError('audit_status'));
        }
    }

    /**
     * 打款
     * @return \yii\web\Response
     */
    public function actionOutremit()
    {
        $model = new RemitForm();
        $model->setAttributes(Yii::$app->getRequest()->post());
        if ($model->outRemit()) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], $model->getFirstErrors());
        }
    }

    public function actionNotify()
    {
        $model = new RemitForm();
        $data = Yii::$app->getRequest()->post();
        if ($model->handleNotify($data)) {
            return $this->outJson(1, $model->getOutNotifyResult());
        } else {
            return $this->outJson(0, $model->getOutNotifyResult());
        }
    }
    
    /**
     * 打款列表数据
     */
    public function actionGetRemitList()
    {
        $model = new RemitOrder();
        $result = $model->getList(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data'], $result['message']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 更改打款状态
     */
    public function actionUpdatePayStatus()
    {
        $model = new RemitOrder();
        $result = $model->updatePayStatus(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data'], $result['message']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }
    
    /**
     * 日志
     */
    public function actionGetRemitLog()
    {
        $model = new RemitLog();
        $result = $model->getList(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data'], $result['message']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

}


