<?php
/**
 *
 * ============================================================================
 * * 版权所有 蜘蛛出行 * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm RefundOrder.php
 * Create By 2017/3/11 15:25 $
 */

namespace console\controllers;

use common\models\OrderContacts;
use common\models\PayRefush;
use common\util\PayService;
use common\util\Util;
use yii\console\Controller;
use yii\db\Exception;

class RefundOrderController extends Controller
{
    public $payFund = '';

    public function getRefund()
    {
        if ($this->payFund == '') {
            $this->payFund = new PayRefush();
        }
        return $this->payFund;
    }

    /**
     * Des:退款操作
     * Name: actionIndex
     * @author 倪宗锋
     */
    public function actionIndex()
    {
        $refundList = $this->getRefund()->getUnPayIds();
        foreach ($refundList as $val) {
            $id = $val['id'];
            $refund = $this->refund($id);
            $logUrl = ROOT_PATH . '/console/log/refund/error' . date("Y-m-d") . '.log';
            $msg = date("Y-m-d H:i:s") . ':';
            $msg .= $refund['msg'];
            file_put_contents($logUrl, $msg . PHP_EOL, FILE_APPEND);
        }
    }

    /**
     * Des:执行退款
     * Name: refund
     * @param $id
     * @return array
     * @throws Exception
     * @author 倪宗锋
     */
    public function refund($id)
    {
        //获取退款信息
        $refundInfo = $this->getRefund()->getInfoById($id);
        if ($refundInfo['status'] == 2) {
            return Util::returnArrSu($refundInfo['order_id'] . '退款成功！已经是退款状态！');
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //1.修改订单状态为退款成功
            $upFlag = $this->getRefund()->updateStatus($id, 2);
            if ($upFlag == false) {
                return Util::returnArrEr($refundInfo['order_id'] . '退款失败!修改订单状态失败！');
            }
            //2.获取订单联系人信息
            $orderContacts = new OrderContacts();
            $getOrderCon = $orderContacts->getRowByOrderId($refundInfo['order_id']);
            if (empty($getOrderCon['contacts_phone'])) {
                $this->getRefund()->updateStatus($id, 3);
                return Util::returnArrEr($refundInfo['order_id'] . '退款失败！获取订单联系人失败！');
            }
            //3.调用接口微信或支付宝 进行退款操作
            $params = [
                'order_id' => $refundInfo['pay_order_id'],
                'name' => '订单退款',
                'total_fee' => $refundInfo['amount_money'],
                'refund_fee' => $refundInfo['refush_money']
            ];
            $refundFlag = PayService::cancel($params, $refundInfo['pay_type']);//退款退钱
            if ($refundFlag['flag'] == false) {
                $transaction->rollBack();
                $this->getRefund()->updateStatus($id, 3);
                return Util::returnArrEr($refundInfo['order_id'] . '退款失败！退款接口返回失败！');
            }
            //4.发送短信通知

            $reMsg = '';
            $siteConfig = Util::getSiteConfig();
            $msg = "您申请的￥{$params['refund_fee']}退款已经通过审核，预计一个工作日内会退还到您的付款账户，请留意查收。如有问题，可拨打客服热线：" . $siteConfig['kefu_tel'];
            $sendMsg = Util::sendMessage($msg, $getOrderCon['contacts_phone']);
            if ($sendMsg['flag'] == false) {
                $reMsg = '发送短信通知失败！';
            }
            $transaction->commit();
            return Util::returnArrSu($refundInfo['order_id'] . '退款成功！' . $reMsg);
        } catch (Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr($refundInfo['order_id'] . '退款失败！程序异常！');
        }
    }
}