<?php
namespace backend\modules\admin\controllers;

use backend\models\forms\RemitForm;
use Yii;
use yii\helpers\Url;
use common\helpers\UserAgentHelper;
use backend\models\RemitApi;
use common\helpers\ExcelHelper;

class RemitController extends BaseController
{
    /**
     * 打款若干天后才可以更新状态为成功或失败
     * @var int
     */
    public $daysAfterPayTime = 1;

    public $crumbs = [
        'all' => '全部列表',
        'first_trial' => '待打款明细',
        're_trial' => '打款中明细',
        'passed' => '打款成功明细',
        'fail' => '打款不成功明细',
    ];
    
    /**
     * 列表页
     */
    public function actionIndex()
    {
        $status = Yii::$app->request->get('status', 'all');
        $crumb = isset($this->crumbs[$status]) ? $this->crumbs[$status] : '';
        return $this->render('index', [
            'daysAfterPayTime' => $this->daysAfterPayTime,
            'status' => $status,
            'crumb' => $crumb,
        ]);
    }

    /**
     * AJAX获取数据
     */
    public function actionAjax()
    {
        $get = Yii::$app->request->get();
        
        $status = isset($get['status']) && in_array($get['status'], array_keys($this->crumbs)) ? $get['status'] : 'all';
        $batch_no = isset($get['batch_no']) ? $get['batch_no'] : '';
        $sTime = isset($get['sTime']) ? $get['sTime'] : ''; // 创建时间
        $eTime = isset($get['eTime']) ? $get['eTime'] : '';
        $sTime2 = isset($get['sTime2']) ? $get['sTime2'] : ''; // 操作时间
        $eTime2 = isset($get['eTime2']) ? $get['eTime2'] : '';
        
        $orderInt = isset($get['order'][0]['column']) ? (int) $get['order'][0]['column'] : 1;
        $order = isset($get['columns'][$orderInt]['data']) ? $get['columns'][$orderInt]['data'] : '';
        $orderBy = isset($get['order'][0]['dir']) ? $get['order'][0]['dir'] : 'desc';
        $search = isset($get['search']['value']) ? trim($get['search']['value']) : '';

        $start = isset($get['start']) ? (int) $get['start'] : 0;
        $length = isset($get['length']) ? (int) $get['length'] : 20;
        $draw = isset($get['draw']) ? $get['draw'] : 1;
        
        $params = [
            'status' => $status,
            'batch_no' => $batch_no,
            'sTime' => $sTime,
            'eTime' => $eTime,
            'sTime2' => $sTime2,
            'eTime2' => $eTime2,
            'order' => $order,
            'orderBy' => $orderBy,
            'search' => $search,
            'start' => $start,
            'length' => $length,
            'draw' => $draw,
        ];

        if ($params['length'] > 5000) {
            if (Yii::$app->getRequest()->getIsAjax()) {
                Yii::$app->getResponse()->redirect(Url::current(), UserAgentHelper::isIE() ? 200 : 302);
            } else {
                $this->exportXls($params);
            }
            Yii::$app->end();
        }

        $api = new RemitApi();
        $result = $api->getRemitList($params);
        return json_encode($result['data']);
    }

    /**
     * 打款
     */
    public function actionOutRemit()
    {
        if (Yii::$app->request->isPost) {
            // 放到后台跑
            ignore_user_abort(true);
            set_time_limit(0);
            $batch_no = Yii::$app->request->post('batch_no');
            $password = Yii::$app->request->post('password');
            
            $api = new RemitApi();
            $detailList = $api->financeRemitDetail(['batch_no' => $batch_no])['data']['dataList'];
            $remitNoArr = array_column($detailList, 'remit_no');

            $successCount = 0;
            $message = '';
            $model = new RemitForm();
            $model->password = $password;
            foreach ($remitNoArr as $k => $v) {
                $model->remitNo = $v;
                $result = $model->outRemit();
                if ($result) {
                    $successCount++;
                } else {
                    $message .= $v . "\n";
                    $message .= array_values($model->getFirstErrors())[0];
                    $message .= "\n";
                }
            }
            
            $code = $successCount ? 1 : 0;
            $message = $successCount ?  '更新' . $successCount . '笔打款单' : $message;
            
            return json_encode(['code' => $code, 'data' => [], 'message' => $message]);
        }

        $batch_no = Yii::$app->request->get('batch_no');
        return $this->renderPartial('out_remit', [
            'batch_no' => $batch_no,
        ]);
    }

    /**
     * 打款成功
     */
    public function actionSuccess()
    {
        if (Yii::$app->request->isPost) {
            $batch_no = Yii::$app->request->post('batch_no');
            $api = new RemitApi();
            $result = $api->updatePayStatus(['batch_no' => $batch_no, 'daysAfterPayTime' => $this->daysAfterPayTime, 'status' => 'success']);
            return json_encode($result);
        }

        $batch_no = Yii::$app->request->get('batch_no');
        return $this->renderPartial('success', [
            'daysAfterPayTime' => $this->daysAfterPayTime,
            'batch_no' => $batch_no,
        ]);
    }

    /**
     * 打款失败
     */
    public function actionFail()
    {
        if (Yii::$app->request->isPost) {
            $batch_no = Yii::$app->request->post('batch_no');
            $reason = trim(Yii::$app->request->post('reason'));
            $api = new RemitApi();
            $result = $api->updatePayStatus(['batch_no' => $batch_no, 'reason' => $reason, 'daysAfterPayTime' => $this->daysAfterPayTime, 'status' => 'fail']);
            return json_encode($result);
        }

        $batch_no = Yii::$app->request->get('batch_no');
        return $this->renderPartial('fail', [
            'daysAfterPayTime' => $this->daysAfterPayTime,
            'batch_no' => $batch_no,
        ]);
    }

    /**
     * 查看操作日志
     */
    public function actionViewlog()
    {
        $batch_no = Yii::$app->request->get('batch_no');
        $api = new RemitApi();
        $result = $api->getBatchRemitLog(['batch_no' => $batch_no]);
        return $this->renderPartial('viewlog', ['logList' => $result['data']]);
    }
    
    /**
     * @param array $params
     */
    protected function exportXls($params)
    {
        ExcelHelper::init();
        $attachmentName = "打款列表_" . date('Y-m-d') . '.xlsx';
        $header = ['打款批次号', '打款笔数', '打款总额(CNY)', '创建时间', '打款状态', '操作时间', '打款信息', '操作人员'];
        $source = [];
        
        $api = new RemitApi();
        $params['length'] = 5000;
        while (true) {
            $result = $api->getRemitList($params);
            if ($result['code'] == 1 && !empty($result['data']['data'])) {
                foreach ((array)$result['data']['data'] as $key => $row) {
                    $arr = [];
                    $arr[] = $row['batch_no'];
                    $arr[] = $row['pay_count'];
                    $arr[] = $row['amount_sum'];
                    $arr[] = $row['create_time'];
                    $arr[] = $row['pay_status'];
                    $arr[] = $row['pay_time'];
                    $arr[] = $row['ret_msg'];
                    $arr[] = $row['admin_name'];
                    $source[] = $arr;
                }
            } else {
                break;
            }
            $params['start'] += $params['length'];
            if ($params['start'] >= $result['data']['recordsTotal']) {
                break;
            }
        }
        ExcelHelper::output($source, $header, $attachmentName);
    }

}


