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

namespace fx\service\user;

use common\models\FxCommissionApply;
use common\models\FxCommissionInfo;
use common\models\FxUserAmountLog;
use common\models\FxUserAmountOrder;
use common\models\LogOrder;
use common\models\OrderContacts;
use common\models\OrderInfo;
use common\models\OrderMain;
use common\models\ProdCategory;
use common\util\curl\CsCurl;
use common\util\FxAmount;
use common\util\PayService;
use common\util\Util;
use common\models\FxUser;
use common\models\FxUserAccount;
use fx\util\FxUtil;
use yii\base\Exception;

class FxUserService
{
    /**
     * Function Description:我的佣金
     * Function Name: myCommission
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function myCommission()
    {
        $fx_user_account = new FxUserAccount();
        //获取用户信息及佣金明细
        $result = $fx_user_account->getMyCommission();
        if ($result !== false) {
            $siteConfig = Util::getSiteConfig();
            $result['apply_rule'] = '' . "1.提现金额将在申请成功后1-2个工作日内到账<br/>2.提现金额必须是{$siteConfig["apply_commission_min"]}的整倍数方可申请";
            $toUrl = $siteConfig['host_name'] . '/web/fx/apply_for.html';
            $result['BindWxUrl'] = $toUrl;
            if ($result['wx_openid'] == 0) {
                $result['BindWxUrl'] = $siteConfig['zzcx_host'] . '/zzcx/user/login/bind-fx-user?fx_uid=' . FxUtil::$uid . '&redirect=' . urlencode($toUrl);
            }

            return Util::returnArrSu('', $result);
        } else {
            return Util::returnArrEr('用户错误');
        }
    }

    /**
     * Function Description:分销订单列表
     * Function Name: FxOrderList
     * @param $params array
     * @return array
     *
     * @author 娄梦宁
     */
    public function FxOrderList($params)
    {
        $order_main = new OrderMain();
        $userInfo = FxUtil::getUserInfo();
        $result1 = [];
        $change_price_power = $userInfo['data']['change_price_power'];//修改价格权限
        $change_price_1 = substr($change_price_power, 0, 1);//巴士自由行改价权限
        $change_price_2 = substr($change_price_power, 1, 1);//酒店订单改价权限
        $result = $order_main->FxOrderList(FxUtil::$uid, $params);
        foreach ($result as $key => $val) {
            $result[$key]['order_total_money'] = floatval($val['order_total_money']);
            $result[$key]['commission_total_money'] = floatval($val['commission_total_money']);
            if ($val['order_status'] == 2) {
                $result[$key]['refund_flag'] = 1;
            } else {
                $result[$key]['refund_flag'] = 0;
            }
            //是否可以修改价格
            $result[$key]['change_price'] = 0;
            if ($val['category_id'] == 4 && $change_price_1 == '1' && $val['order_status'] == 1) {
                $result[$key]['change_price'] = 1;
            }
            if ($val['category_id'] == 3 && $change_price_2 == '1' && $val['order_status'] == 1) {
                $result[$key]['change_price'] = 1;
            }
            //设置产品
            $arr = [];
            if ($val['category_id'] == 3) {//如果是酒店
                $total_day = count(json_decode($val['total_details'], true));
                $proValArr['prod_name'] = '酒店';
                $proValArr['prod_cnt'] = $val['prod_cnt'] . '人 ' . $total_day . '晚';
                $arr[] = $proValArr;
            } else {
                $prodArr = explode('||', $val['prod_str']);
                foreach ($prodArr as $proVal) {
                    if (empty($prod['0']) || empty($prod['1'])) {
                        continue;
                    }
                    $prod = explode(',,', $proVal);
                    $proValArr['prod_name'] = $prod['0'];
                    $proValArr['prod_cnt'] = $prod['1'];
                    $arr[] = $proValArr;
                }
            }
            $result[$key]['prod_arr'] = $arr;
        }
        $result1['order_list'] = $result;//订单列表
        $result1['current_page'] = $params['current_page'];
        $result1['page_size'] = $params['page_size'];
        if ($result !== false) {
            return Util::returnArrSu('', $result1);
        } else {
            return Util::returnArrEr('获取信息失败');
        }
    }

    /**
     * Des:获取订单详细
     * Name: getOrderInfo
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public function getOrderInfo($order_id)
    {
        /***----参数及权限校验***/
        if (Util::checkPattern('intVal', $order_id) == false) {
            return Util::returnArrEr('参数错误 ！');
        }
        $orderMain = new OrderMain();
        $getOrderInfo = $orderMain->getOrderInfo($order_id);
        if (empty($getOrderInfo['order_id'])) {
            return Util::returnArrEr('无效订单');
        }
        if ($getOrderInfo['fx_uid'] != FxUtil::$uid) {
            return Util::returnArrEr('您无法查看他人的订单！');
        }

        /***设置订单信息***/
        $orderInfo['order_id'] = $getOrderInfo['order_id'];//订单名称
        $orderInfo['order_name'] = $getOrderInfo['order_name'];//订单名称
        $orderInfo['original_price'] = $getOrderInfo['original_price'];//原价
        $orderInfo['total_money'] = $getOrderInfo['total_money'];//实际价格
        $orderInfo['order_status'] = $getOrderInfo['order_status'];//订单状态
        //订单折扣价
        if ($getOrderInfo['original_price'] == $getOrderInfo['total_money']) {
            $orderInfo['discount_money'] = 0;
            $orderInfo['discount_type'] = 0;
        } elseif ($getOrderInfo['original_price'] > $getOrderInfo['total_money']) {
            $orderInfo['discount_money'] = $getOrderInfo['original_price'] - $getOrderInfo['total_money'];
            $orderInfo['discount_type'] = 1;
        } else {
            $orderInfo['discount_type'] = 2;
            $orderInfo['discount_money'] = $getOrderInfo['total_money'] - $getOrderInfo['original_price'];
        }
        $orderInfo['discount_money'] = floatval($orderInfo['discount_money']);
        $orderInfo['total_money'] = floatval($orderInfo['total_money']);
        $orderInfo['original_price'] = floatval($orderInfo['original_price']);
        /***获取佣金***/
        $fxCommissionTab = new FxCommissionInfo();
        $getCommission = $fxCommissionTab->getInfoByOrderId($order_id);
        if (empty($getCommission['total_money'])) {
            $orderInfo['commission'] = 0;
        } else {
            $orderInfo['commission'] = $getCommission['total_money'];
        }
        $orderInfo['commission'] = floatval($orderInfo['commission']);

        /***-----获取订单产品**/
        $orderInfoTab = new OrderInfo();
        $prodArr = $orderInfoTab->geProdArr($order_id);
        //获取保险单
        $orderContent = new OrderContacts();
        $getInsuranceCnt = $orderContent->getInsuranceCnt($order_id);
        if (!empty($getInsuranceCnt)) {
            $arr = [
                'prod_id' => '1',
                'prod_name' => '乘意险',
                'prod_num' => $getInsuranceCnt
            ];
            $prodArr[] = $arr;
        }

        /***------获取联系人信息****/
        $getConnect = $orderContent->getRowByOrderId($order_id);

        /**------获取订单日志列表*/
        $orderLog = new LogOrder();
        $getOrderLog = $orderLog->getOrderLog($order_id);

        /***-----设置返回值****/
        $return = [];
        $return['order_info'] = $orderInfo;
        $return['prod_arr'] = $prodArr;
        $return['content'] = $getConnect;
        $return['order_log'] = $getOrderLog;
        return Util::returnArrSu('', $return);
    }

    /**
     * Des:变更订单价格
     * Name: changeOrderMoney
     * @param $params
     * @return array
     * @author 倪宗锋
     */
    public function changeOrderMoney($params)
    {
        //1.校验参数
        if (empty($params['order_id']) || empty($params['money'])) {
            return Util::returnArrEr('参数异常，请稍后再试!');
        }
        if (!Util::checkPattern('intVal', $params['order_id']) || !Util::checkPattern('money', $params['money'])) {
            return Util::returnArrEr('参数异常，请稍后再试!');
        }
        //2.校验是否可以变更价格
        $userInfo = FxUtil::getUserInfo();
        $change_price_power = $userInfo['data']['change_price_power'];//修改价格权限
        $change_price_1 = substr($change_price_power, 0, 1);//巴士自由行改价权限
        $change_price_2 = substr($change_price_power, 1, 1);//酒店订单改价权
        $orderMain = new OrderMain();
        $orderInfo = $orderMain->getOrderInfo($params['order_id']);//获取订单信息
        if (empty($orderInfo['order_id'])) {
            return Util::returnArrEr('订单不存在！');
        }
        if ($change_price_1 != 1 && $orderInfo['category_id'] == 4) {
            return Util::returnArrEr('您没有巴士自由行订单的改价权限！');//用户权限
        }
        if ($change_price_2 != 1 && $orderInfo['category_id'] == 3) {
            return Util::returnArrEr('您没有酒店订单的改价权限！');//用户权限
        }
        if ($orderInfo['fx_uid'] != FxUtil::$uid) {//订单归属是否当前用户
            return Util::returnArrEr('您没有操作他人订单的权限！');
        }
        if (!in_array($orderInfo['category_id'], [3, 4])) {//是否巴士自由行订单或者酒店订单
            return Util::returnArrEr('目前只支持巴士自由行、酒店订单改价！');
        }
        if ($orderInfo['order_status'] != 1) {//是否是未支付订单
            return Util::returnArrEr('未支付订单才可以修改价格');
        }
        if ($params['money'] == $orderInfo['total_money']) {
            return Util::returnArrSu();
        }
        if ($orderInfo['category_id'] == 4) {//自由行订单需要校验低价
            //3.校验价格是否低于底价
            $oderInfoTab = new OrderInfo();
            $prodCate = new ProdCategory();
            $getProdInfo = $prodCate->getProdCateInfo($orderInfo['prod_cate_id']);//主产品详情
            $date['sign'] = $getProdInfo['sign'];
            $date['prod_arr'] = $oderInfoTab->geProdArr($params['order_id']);//获取票种产品数据
            $date['start_date'] = $orderInfo['start_date'];
            $getPrice = CsCurl::getFreeWalkPrice($date);
            if ($getPrice['flag'] == false) {
                return Util::returnArrEr('获取结算底价失败！');
            }
            $insuranceMoney = $orderInfo['original_price'] - $getPrice['data']['total_money'];//保险单的价格 = 订单原价-自由产品零售价
            if ($params['money'] < ($getPrice['data']['total_cost'] + $insuranceMoney)) {//如果价格 低于 （自由行产品价格+保险单的价格）则设置失败
                return Util::returnArrEr('不满足可改价格区间，请重新输入。');
            }
        } elseif ($orderInfo['category_id'] == 3) {//酒店需要校验底价
            $getPrice = CsCurl::getHotelLowPrice($orderInfo['order_id']);
            if ($getPrice['flag'] == false) {
                return Util::returnArrEr('获取结算底价失败！');
            }
            if ($params['money'] < $getPrice['data']['total_cost']) {//如果价格 低于底价则设置失败
                return Util::returnArrEr('不满足可改价格区间，请重新输入。');
            }
        }
        //4.修改价格
        $value = ['total_money' => $params['money']];
        $changeMoney = $orderMain->upOrder($value, [$params['order_id']]);
        if ($changeMoney) {
            Util::addOrderLog(FxUtil::$uid, 2, $params['order_id'], '改价时间', 2);
            return Util::returnArrSu();
        } else {
            return Util::returnArrEr('修改价格失败！');
        }
    }

    /**
     * Function Description:提现列表
     * Function Name: ApplyCommissionDetail
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function ApplyCommissionDetail()
    {
        $fx_commission_apply = new FxCommissionApply();
        $commission_apply_list = $fx_commission_apply->getCommissionApplyList();
        if ($commission_apply_list !== false) {
            $commission_apply_list = ['apply_list' => $commission_apply_list];
            return Util::returnArrSu('', $commission_apply_list);
        } else {
            return Util::returnArrEr('获取信息失败');
        }
    }

    /**
     * Function Description:申请提现
     * Function Name: CashCommission
     * @param $apply_commission
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function CashCommission($apply_commission)
    {
        $time = time();
        session_start();
        if (($time - $_SESSION['expire_time'] < 3)) {
            return Util::returnArrEr('请勿重复点击！');
        } else {
            $_SESSION['expire_time'] = $time;
            session_write_close();
        }
        $sitConfig = Util::getSiteConfig();
        $applyCommissionMin = $sitConfig["apply_commission_min"];//最低提现金额
        $fx_user_account = new FxUserAccount();
        $fx_commission_apply = new FxCommissionApply();
        if (((int)$apply_commission) % $applyCommissionMin != 0) {
            return Util::returnArrEr("提现金额仅限{$applyCommissionMin}的倍数");
        }
        //检查账户可提现金额
        $msg = '申请失败-10000';
        $check_commission = $fx_user_account->getMyCommission();
        if ($check_commission['accountStatus'] == '2') {
            return Util::returnArrEr('您的账户已冻结，无法提现！');
        }
        if ($check_commission['available_commission'] >= $apply_commission) {
            $msg = '申请失败-10001';
            //1.插入提现记录表
            $insertApplyCommission = $fx_commission_apply->InsertApplyCommission($apply_commission);
            if ($insertApplyCommission) {
                $msg = '申请失败-10002';
                //2.更新用户账户状态
                $available_commission = $check_commission['available_commission'] - $apply_commission;
                $new_apply_commission = $check_commission['apply_commission'] + $apply_commission;
                $uptUserAccount = $fx_user_account->ApplyCommission($available_commission, $new_apply_commission);
                if ($uptUserAccount) {
                    return Util::returnArrSu();
                }
            }
        }
        return Util::returnArrEr($msg);
    }

    /**
     * Function Description:账户充值
     * Function Name: CashCommission
     * @param $params array
     *
     * @return array
     *
     * @author 倪宗锋
     */
    public function recharge($params)
    {
        if (Util::checkPattern('money', $params['amount']) == false) {
            return Util::returnArrEr('金额格式错误！');
        }
        $siteConfig = Util::getSiteConfig();
        if ($params['amount'] < $siteConfig['recharge_amount']) {
            return Util::returnArrEr("不能低于{$siteConfig['recharge_amount']}元");
        }
        $fx_user = new FxUser();
        $userInfo = $fx_user->getUserInfoByUid($params['fx_uid']);
        /****添加充值记录*****/
        $fxUserAmountOrder = new FxUserAmountOrder();
        $add = $fxUserAmountOrder->addAmountOrder($params['fx_uid'], $params['amount'], $params['payType']);
        if ($add['flag'] == false) {
            return Util::returnArrEr('充值失败！[10001]');
        }
        $params = [
            'name' => '分销账户充值！',
            'order_id' => $add['data']['recharge_order'],
            'total_fee' => $params['amount'],
            'openid' => $userInfo['openid'],
            'notify_url' => '/fx/wechat/amountNotify/'
        ];
        $result = PayService::pay($params);
        if (!$result) {
            return Util::returnArrEr('充值失败[10002]');
        }
        return Util::returnArrSu('', $result);
    }

    /**
     * 订单充值
     * @param $params
     * @return array
     */
    public function payRecharge($params)
    {
        $orderId = $params['out_trade_no'];//订单ID
        $total_money = empty($params['total_fee']) ? $params['buyer_pay_amount'] : $params['total_fee'] / 100;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $fxUserAmountOrder = new FxUserAmountOrder();
            $getInfo = $fxUserAmountOrder->getAmountOrderInfo($orderId);
            if ($getInfo['amount'] != $total_money) {
                return Util::returnArrEr('充值失败！[10001]');
            }
            if ($getInfo['status'] == 2) {
                return Util::returnArrEr('充值失败！[10002]');
            }
            //1、添加用户余额
            $recharge = FxAmount::recharge($getInfo['fx_uid'], $total_money);
            if ($recharge['flag'] == false) {
                return $recharge;
            }
            //2、修改充值单状态
            $updateFlag = $fxUserAmountOrder->updateStatus($orderId, 2);
            if ($updateFlag == false) {
                $transaction->rollBack();//回滚
                return Util::returnArrEr('充值失败！[10003]');
            }
            $transaction->commit();
            return Util::returnArrSu();
        } catch (Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr('system error!');
        } catch (\yii\db\Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr('system error!');
        }
    }

    /**
     * 获取账户余额变更记录
     * @param $params
     * @return array
     */
    public function getAmountLog($params)
    {
        $fxUserAmountLog = new FxUserAmountLog();
        $getList = $fxUserAmountLog->getList($params);
        $return['list'] = $getList;
        return Util::returnArrSu('', $return);
    }

    /**
     * 获取充值记录
     * @param $params
     * @return array
     */
    public function getRechargeList($params)
    {
        $fxUserAmountOrder = new FxUserAmountOrder();
        $getList = $fxUserAmountOrder->getList($params);
        $return['list'] = $getList;
        return Util::returnArrSu('', $return);
    }

}