<?php
/**
 * @package merchant
 * @Author: Qinii
 * @Date: 2020/5/8
 */

namespace app\common\repositories\movie;

use app\common\dao\movie\order\MovieOrderDao;
use app\common\model\movie\order\MovieOrder;
use app\common\repositories\BaseRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\traits\HuiPay;
use crmeb\services\ApiResponseService;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * Class MovieRepository
 * @package app\common\repositories\movie
 * @author xaboy
 * @mixin MovieOrderDao
 */
class MovieRepository extends BaseRepository
{
    use HuiPay;

    protected $dao;

    const premium_ratio = 0.2;//溢价比例
    const yanglaojin_ratio = 0.3;

    const pv_ratio = 0.7;
    const tenMinute = 600;

    /**
     * ProductRepository constructor.
     * @param MovieOrderDao $dao
     */
    public function __construct(MovieOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param $page
     * @param $limit
     * @param $initial
     * @param $city_name
     * @return false|int|mixed
     */
    public function getMovieCity($page = 1, $limit = 10, $initial = '', $city_name = '')
    {
        return DouHuoMallFilmApiRequest::getMovieCity($page, $limit, $initial = '', $city_name);
    }

    /**
     * @param $city_sign
     * @return false|int|mixed
     */
    public function getMovieArea($city_sign = '')
    {
        return DouHuoMallFilmApiRequest::getMovieArea($city_sign);
    }

    /**
     * @param $page
     * @param $limit
     * @param $city_sign
     * @param $area_sign
     * @return false|int|mixed
     */
    public function getCinema($page = 1, $limit = 10, $city_sign = '', $area_sign = '')
    {
        return DouHuoMallFilmApiRequest::getCinema($page, $limit, $city_sign, $area_sign);
    }

    /**
     * @param $page
     * @param $limit
     * @param $cinema_sign
     * @param $film_sign
     * @return false|int|mixed
     */
    public function getFilm($page = 1, $limit = 10, $cinema_sign = '', $film_sign = '')
    {
        return DouHuoMallFilmApiRequest::getFilm($page, $limit, $cinema_sign, $film_sign);
    }

    /**
     * @param $film_sign
     * @param $cinema_sign
     * @return mixed|string
     */
    public function getCinemaSched($film_sign = '', $cinema_sign = '')
    {
        $movie_commission_rate_config = Db::name('system_config_value')->where('config_key', 'movie_commission_rate_config')->find();
        $movie_commission_rate_config = !empty($movie_commission_rate_config) ? json_decode($movie_commission_rate_config['value'], true) : [];

        $result = DouHuoMallFilmApiRequest::getCinemaSched($film_sign, $cinema_sign);
        $cinemaSchedList = (isset($result['code']) && ($result['code'] == ApiResponseService::DEFAULT_SUCCESS_CODE))
            ? $result['data']['list'] : [];
        foreach ($cinemaSchedList as $dateDay => &$fileSchedValue) {
            foreach ($fileSchedValue as $key => $value) {
                $pcYanglaojinGongxian = static::getPvYanglaojinScore($value['cost_price'], $movie_commission_rate_config);

                $fileSchedValue[$key]['price'] = $pcYanglaojinGongxian['cost_price']; // 销售价
                $fileSchedValue[$key]['yanglaojin'] = $pcYanglaojinGongxian['yanglaojin'];
                $fileSchedValue[$key]['pv'] = $pcYanglaojinGongxian['pv'];
                $fileSchedValue[$key]['score'] = $pcYanglaojinGongxian['score'];
                $fileSchedValue[$key]['gongxian'] = $pcYanglaojinGongxian['gongxian'];

//                unset($fileSchedValue[$key]['channel_price']);
            }
        }

        return $cinemaSchedList;
    }

    /**
     * @param $page
     * @param $limit
     * @param $film_sign
     * @param $longitude
     * @param $latitude
     * @param $city_sign
     * @return mixed|string
     */
    public function getFilmSched($page = 1, $limit = 10, $film_sign = '', $longitude = '', $latitude = '', $city_sign = '')
    {
        return DouHuoMallFilmApiRequest::getFilmSched($page, $limit, $film_sign, $longitude, $latitude, $city_sign);
    }

    /**
     * @param $relation_id
     * @param $sched_sign
     * @return mixed|string
     */
    public function getSchedSeat($relation_id = '', $sched_sign = '')
    {
        $result = DouHuoMallFilmApiRequest::getSchedSeat($relation_id, $sched_sign);

        $sched_seatList = [];
        // 根据场次id、场次编号获取锁座订单
        $seatOrder = $this->dao->search(['relation_id' => $relation_id, 'sched_sign' => $sched_sign, 'status' => [0, 1]])->field('relation_id,sched_sign,sched_seat')->select()->toArray();
        if (!empty($seatOrder)) {
            $tmpsched_seat = array_column($seatOrder, 'sched_seat');
            foreach ($tmpsched_seat as $ssKey => $ssValue) {
                $ssValue = json_decode($ssValue, true);
                foreach ($ssValue as $k => $v) {
                    $sched_seatList[$v['seat_sign']] = $v['seat_sign'];
                }
            }
        }

        $movie_commission_rate_config = Db::name('system_config_value')->where('config_key', 'movie_commission_rate_config')->find();
        $movie_commission_rate_config = !empty($movie_commission_rate_config) ? json_decode($movie_commission_rate_config['value'], true) : [];

        $seat = [];
        $schedSeatList = (isset($result['code']) && ($result['code'] == ApiResponseService::DEFAULT_SUCCESS_CODE)) ? $result['data'] : [];
        foreach ($schedSeatList as $key => $value) {
            $tmpprice = [];
            foreach ($value['price'] as $pKey => $pValue) {
                $tmpprice[$pKey] = ['channel_type' => $pKey, 'price' => $pValue];
            }

            $channel_price = [];
            if (isset($tmpprice['P2'])) {
                $channel_price = $tmpprice['P2'];
            } elseif (isset($tmpprice['P1'])) {
                $channel_price = $tmpprice['P1'];
            } elseif (isset($tmpprice['P0'])) {
                $channel_price = $tmpprice['P0'];
            }
            unset($schedSeatList[$key]['price']);

            $pcYanglaojinGongxian = self::getPvYanglaojinScore($channel_price['price'], $movie_commission_rate_config);
            $schedSeatList[$key]['channel_sn'] = base64_encode(json_encode($channel_price, JSON_FORCE_OBJECT));
            $schedSeatList[$key]['price'] = $pcYanglaojinGongxian['cost_price'];
            $schedSeatList[$key]['yanglaojin'] = $pcYanglaojinGongxian['yanglaojin'];
            $schedSeatList[$key]['pv'] = $pcYanglaojinGongxian['pv'];
            $schedSeatList[$key]['score'] = $pcYanglaojinGongxian['score'];
            $schedSeatList[$key]['gongxian'] = $pcYanglaojinGongxian['gongxian'];
            $schedSeatList[$key]['relation_id'] = $relation_id; // 场次ID
            $schedSeatList[$key]['sched_sign'] = $sched_sign; // 场次编码
            if ($value['status'] == 1) {
                $schedSeatList[$key]['status'] = isset($sched_seatList[$value['seatSign']]) ? 0 : 1;
            }

            $seat[$value['rowNo']][] = $schedSeatList[$key];
        }
        if ($seat) ksort($seat);

        return array_values($seat);
    }

    /**
     * 锁座订单
     *
     * @param $userinfo
     * @param $params
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function submitOrder($userinfo, $params)
    {
        /** @var StoreOrderRepository $storeOrder */
        $storeOrder = app()->make(StoreOrderRepository::class);
        $order_sn = substr($storeOrder->getNewOrderId(), 0, 20);

        $channel_sn = json_decode(base64_decode($params['channel_sn']), true);
        if (empty($channel_sn) || !isset($channel_sn['channel_type']) || empty($channel_sn['channel_type']) || !isset($channel_sn['price'])
            || empty($channel_sn['price']) || json_last_error()) {
            throw new ValidateException('请选择观影场次');
        }

        $sched_seat = json_decode($params['sched_seat'], true);
        if (json_last_error()) throw new ValidateException('锁座下单失败');

        $order_price = bcmul((string)$channel_sn['price'], (string)count($sched_seat), 2);
        Db::name('log')->insert(['data' => '---电影票支付订单数据---' . json_encode([
                $params['phone'] ?? $userinfo->phone, $channel_sn['channel_type'], $params['sched_sign'], array_column($sched_seat, 'seat_sign'), $order_sn, $order_price
            ])]);
        $submitOrder = DouHuoMallFilmApiRequest::submitOrder($params['phone'] ?? $userinfo->phone, $channel_sn['channel_type'], $params['sched_sign'], array_column($sched_seat, 'seat_sign'), $order_sn, $order_price);
        if (!empty($submitOrder) && isset($submitOrder['code']) && ($submitOrder['code'] == ApiResponseService::DEFAULT_SUCCESS_CODE) && isset($submitOrder['data']['plat_order'])) {
            /** @var CinemaRepository $cinemaRepository */
            $cinemaRepository = app()->make(CinemaRepository::class);
            $cinema = $cinemaRepository->getCinemaInfo($params['cinema_sign']);

            /** @var FilmRepository $filmRepository */
            $filmRepository = app()->make(FilmRepository::class);
            $filminfo = $filmRepository->getFilmInfo($params['film_sign']);

            // 电影分佣比例配置
            $movie_commission_rate_config = Db::name('system_config_value')->where('config_key', 'movie_commission_rate_config')->find();
            $movie_commission_rate_config = !empty($movie_commission_rate_config) ? json_decode($movie_commission_rate_config['value'], true) : [];
            $premium_ratio = isset($movie_commission_rate_config['premium_rate']) ? $movie_commission_rate_config['premium_rate'] : self::premium_ratio;

            $_order = [
                'uid' => $userinfo->uid,
                'mobile' => $params['phone'] ?? $userinfo->phone,
                'phone' => $params['phone'] ?? $userinfo->phone,
                'order_sn' => $order_sn,
                'plat_order' => $submitOrder['data']['plat_order'],
                'price' => $order_price,
                'number' => count($sched_seat),
                'order_price' => bcadd((string)$order_price, bcmul((string)$order_price, (string)$premium_ratio, 2), 2),
                'channel_type' => $channel_sn['channel_type'],
                'city_sign' => $cinema['city_sign'],
                'city_name' => $cinema['city_name'],
                'area_code' => $cinema['area_sign'],
                'area_name' => $cinema['area_name'],
                'cinema_sign' => $cinema['cinema_sign'],
                'cinema_name' => $cinema['cinema_name'],
                'address' => $cinema['address'],
                'longitude' => $cinema['longitude'],
                'latitude' => $cinema['latitude'],
                'hall_sign' => $params['hall_sign'],
                'hall_name' => $params['hall_name'],
                'relation_id' => $params['relation_id'],
                'sched_sign' => $params['sched_sign'],
                'film_sign' => $filminfo['film_sign'],
                'film_name' => $filminfo['film_name'],
                'show_date' => $params['show_date'],
                'show_time' => $params['show_time'],
                'sched_seat' => $params['sched_seat'], // 场次座位
                'create_time' => time()
            ];
            $order_id = Db::transaction(function () use ($userinfo, $_order) {
                $orderModel = $this->dao->create($_order);
                if ($orderModel) return $orderModel['order_id'];
                throw new ValidateException('锁座下单失败');
            });
            return compact('order_id', 'order_sn');
        } else {
            throw new ValidateException($submitOrder['msg']);
        }
    }

    /**
     * @param $userinfo
     * @param $order_sn
     * @param $pay_type
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function confirmOrder($userinfo, $order_id, $pay_type, $code)
    {
        $orderinfo = $this->dao->search(['order_id' => $order_id])->find();
        if (empty($orderinfo)) throw new ValidateException('订单不存在');
        if ($orderinfo['paid'] == 0 && $orderinfo['status'] == 2) throw new ValidateException('订单已超时');
        if ($orderinfo['paid'] == 0 && $orderinfo['status'] == 3) throw new ValidateException('订单已取消');
        if ($orderinfo['paid'] == 1) throw new ValidateException('订单已支付');

        $res = $this->movie_pay(strtolower($pay_type), $code, '', $orderinfo, $orderinfo['film_name'], env('APP_URL') . "/api/hf_notify/movie", 'delay');
        Db::name('log')->insert(['data' => '汇付电影票订单支付--- 返回参数' . json_encode($res)]);
        if (isset($res['id'])) {
            $type = 0;
            if ($pay_type == 'wx') $type = 2;
            if (strtolower($pay_type) == 'ali') $type = 1;

            $orderinfo->pay_type = $type;
            $orderinfo->update_time = time();
            $orderinfo->save();

            return $res;
        }
        throw new ValidateException('支付失败');
    }

    /**
     * 支付
     *
     * @param $payType
     * @param $openid
     * @param $_order
     * @param $title
     * @param $notify_url
     * @param $pay_mode
     * @param $appid
     * @return array|mixed
     */
    private function pay($payType, $openid, $_order, $title, $notify_url, $pay_mode = null, $appid = '')
    {
        switch ($payType) {
            case 'wx':
                $pay_wx = systemConfig('pay_wx');
                if ($pay_wx == 2) {
                    $appid = env('WECHAT_MP.APPID');
                    $new_secret = env('WECHAT_MP.SECRET');

                    $app_id = 'app_0827b960-b932-45ec-b800-4e850091b419';
                    $key = 'api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';
                } elseif ($pay_wx == 3) {
                    $appid = env('WECHAT_TDYL.APPID');
                    $new_secret = env('WECHAT_TDYL.SECRET');

                    $app_id = 'app_383a75dd-c03d-44ab-8f58-92c60fe9b9d0';
                    $key = 'api_live_b0a687ec-5450-4ada-a0e4-65bac0f46871';
                }

                $type = '2';
                $params = [
                    'order_no' => $_order['order_sn'],
                    'app_id' => $app_id,
                    'pay_channel' => 'wx_lite',
                    'pay_amt' => (string)$_order['order_price'],
                    'goods_title' => strlen($title) > 64 ? mb_substr($title, 0, 64, 'utf-8') : $title,// 解决因为太长不能支付问题
                    'goods_desc' => strlen($title) > 42 ? mb_substr($title, 0, 127, 'utf-8') : $title,// 解决因为太长不能支付问题
                    'device_info' => [
                        'device_ip' => app('request')->ip()
                    ],
                    'expend' => json_encode(['open_id' => $openid, 'wx_app_id' => $appid]),
//                    'fee_mode' => 'I',
                    'notify_url' => $notify_url,
                    'pay_mode' => $pay_mode
                ];
                break;
            case 'ALI':
            case 'ali':
                $type = '1';
                // 天地博爱科技通道
                $app_id = 'app_44108546-d27a-48ee-88c1-84b45b75114f';
                $key = 'api_live_b23537ed-64b8-45d6-832e-fb228aa9e0a9';

                $params = [
                    'order_no' => $_order['order_sn'],
                    'app_id' => $app_id,
                    'pay_channel' => 'alipay_qr',
                    'pay_amt' => (string)$_order['order_price'],
                    'goods_title' => strlen($title) > 64 ? mb_substr($title, 0, 64, 'utf-8') : $title,// 解决因为太长不能支付问题
                    'goods_desc' => strlen($title) > 42 ? mb_substr($title, 0, 127, 'utf-8') : $title,// 解决因为太长不能支付问题
                    'device_info' => [
                        'device_ip' => app('request')->ip()
                    ],
//                    'fee_mode' => 'I',
                    'notify_url' => $notify_url
                ];
                break;
            default:
                throw new ValidateException('请选择支付方式');
                break;
        }

        return $this->Payment_create_traits_a($params, $type, $key);
    }

    /**
     * 电影票支付
     *
     * @param $payType
     * @param $code
     * @param $wechat_user_id
     * @param $orderinfo
     * @param $title
     * @param $notify_url
     * @param $pay_mode
     * @param $appid
     * @return array|mixed|void
     */
    private function movie_pay($payType, $code, $wechat_user_id, $orderinfo, $title, $notify_url, $pay_mode = null, $appid = '')
    {
        if ($payType == 'wx') {
            if (!$code || $code == '' || $code == 'undefined') {
                throw new ValidateException('授权失败，code为空');
            }
            if ($appid == '') {
                $pay_wx = systemConfig('pay_wx');
                if ($pay_wx == 2) {
                    $appid = env('WECHAT_MP.APPID');
                    $new_secret = env('WECHAT_MP.SECRET');

                    $app_id = 'app_0827b960-b932-45ec-b800-4e850091b419';
                    $key = 'api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';
                } elseif ($pay_wx == 3) {
                    $appid = env('WECHAT_TDYL.APPID');
                    $new_secret = env('WECHAT_TDYL.SECRET');

                    Db::name('log')->insert(['data' => 'appid---' . $appid]);
                    Db::name('log')->insert(['data' => 'new_secret---' . $new_secret]);
                    $app_id = 'app_383a75dd-c03d-44ab-8f58-92c60fe9b9d0';
                    $key = 'api_live_b0a687ec-5450-4ada-a0e4-65bac0f46871';
                }
            } else {
                $app_id = 'app_0827b960-b932-45ec-b800-4e850091b419';
                $key = 'api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';
                $new_secret = "c8cbe24fa3b83f77a88b79554b3aeab4";
            }

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $new_secret . "&js_code=" . $code . "&grant_type=authorization_code";
            $get = curlGet($url);
            Db::name('log')->insert(['data' => 'open_id---' . json_encode($get)]);
            if (!isset($get['openid']) || empty($get['openid'])) {
                throw new ValidateException('授权失败');
            }
            $member_id = 0;
            $type = '2';
            $pay_channel = 'wx_lite';

            $expend = ['open_id' => $get['openid'], 'wx_app_id' => $appid];
            if (false) {
//                if ($orderinfo['order_type'] = "movie") {
                $cfb = sprintf("%01.2f", round(bcmul($orderinfo['order_price'], '0.094', 5), 2));//9.4%的分账
                $cfb_member = "jsdk_member_1680162243019";
                //  平台
                $cxb = sprintf("%01.2f", round(bcsub($orderinfo['order_price'], $cfb, 5), 2));//剩下的归平台
                $div_members = [
//                    [
//                        'member_id' => $member_id,
//                        'amount' => $cxb,
//                        'fee_flag' => 'Y'
//                    ],
//                    [
//                        'member_id' => $cfb_member,
//                        'amount' => $cfb,
//                        'fee_flag' => 'N'
//                    ]
                ];
            } else {
                $div_members = [
                    [
                        'member_id' => $member_id,
                        'amount' => $orderinfo['order_price'],
                        'fee_flag' => 'Y'
                    ]
                ];
            }

            $params = [
                'order_no' => $orderinfo['order_sn'],
                'app_id' => $app_id,
                'pay_channel' => $pay_channel,
                'pay_amt' => (string)$orderinfo['order_price'],
                'goods_title' => strlen($title) > 64 ? mb_substr($title, 0, 64, 'utf-8') : $title,// 解决因为太长不能支付问题
                'goods_desc' => strlen($title) > 42 ? mb_substr($title, 0, 127, 'utf-8') : $title,// 解决因为太长不能支付问题
                'device_info' => [
                    'device_ip' => app('request')->ip()
                ],
                'expend' => json_encode($expend),
                'div_members' => json_encode($div_members),
                'fee_mode' => 'I',
                'notify_url' => $notify_url
            ];
            if ($pay_mode == 'delay') {
                $params['pay_mode'] = 'delay';
                unset($params['div_members']);
                unset($params['fee_mode']);
            }
            return $this->Payment_create_traits_b($params, $type, $key);
        } elseif ($payType == 'ali') {
            $member_id = 0;
            $type = '1';
            $pay_channel = 'alipay_qr';
            // 天地博爱科技通道
            $app_id = 'app_44108546-d27a-48ee-88c1-84b45b75114f';
            $key = 'api_live_b23537ed-64b8-45d6-832e-fb228aa9e0a9';
            // 天地博爱通道
//            $app_id='app_0827b960-b932-45ec-b800-4e850091b419';
//            $key='api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';

            $div_members = [
                [
                    'member_id' => $member_id,
                    'amount' => $orderinfo['order_price'],
                    'fee_flag' => 'Y'
                ]
            ];

            $params = [
                'order_no' => $orderinfo['order_sn'],
                'app_id' => $app_id,
                'pay_channel' => $pay_channel,
                'pay_amt' => (string)$orderinfo['order_price'],
                'goods_title' => strlen($title) > 64 ? mb_substr($title, 0, 64, 'utf-8') : $title,// 解决因为太长不能支付问题
                'goods_desc' => strlen($title) > 42 ? mb_substr($title, 0, 127, 'utf-8') : $title,// 解决因为太长不能支付问题
                'device_info' => [
                    'device_ip' => app('request')->ip()
                ],
                'div_members' => json_encode($div_members),
                'fee_mode' => 'I',
                'notify_url' => $notify_url
            ];
            if ($pay_mode == 'delay') {
                $params['pay_mode'] = 'delay';
                unset($params['div_members']);
                unset($params['fee_mode']);
            }
            return $this->Payment_create_traits_a($params, $type, $key);
        }
    }

    /**
     * @param $userinfo
     * @param $order_sn
     * @return mixed|string
     */
    public function getOrderInfo($userinfo, $order_sn)
    {
        $orderinfo = $this->dao->search(['order_sn' => $order_sn, 'uid' => $userinfo['uid']])->find();
        if (empty($orderinfo)) throw new ValidateException('订单不存在');

        $time = time();
        $result = DouHuoMallFilmApiRequest::getOrderInfo($order_sn);
        if (!empty($result) && ($result['code'] == ApiResponseService::DEFAULT_SUCCESS_CODE)) {
            $plat_orderinfo = $result['data'];
            $plat_orderinfo['oid'] = $orderinfo['order_id'];
            $plat_orderinfo['type'] = ($orderinfo['pay_type'] == 1) ? 'wx' : ($orderinfo['pay_type'] == 2 ? 'ali' : 'wx');
            $plat_orderinfo['order_price'] = $orderinfo['order_price'];
            $plat_orderinfo['order_sn'] = $order_sn;
            $plat_orderinfo['create_time'] = strtotime($orderinfo['create_time']);// 下单时间戳
            $plat_orderinfo['phone'] = $orderinfo['mobile'];
            $plat_orderinfo['sched_seat'] = json_decode($orderinfo['sched_seat'], true);
            $plat_orderinfo['cinema'] = [
                'cinema_sign' => $orderinfo['cinema_sign'],
                'cinema_name' => $orderinfo['cinema_name'],
                'address' => $orderinfo['address'],
                'longitude' => $orderinfo['longitude'],
                'latitude' => $orderinfo['latitude'],
                'hall_sign' => $orderinfo['hall_sign'],
                'hall_name' => $orderinfo['hall_name'],
                'tel' => Db::name('movie_cinema')->where('cinema_sign', $orderinfo['cinema_sign'])->value('tel')
            ];
            $film = Db::name('movie_film')->where('film_sign', $orderinfo['film_sign'])->find();
            $plat_orderinfo['film'] = [
                'film_sign' => $orderinfo['film_sign'],
                'film_name' => $orderinfo['film_name'],
                'language' => $film['language'],
                'cover_img' => $film['cover_img'],
                'version' => $film['version'],
            ];
            $plat_orderinfo['sched_time'] = date('Y-m-d H:i', strtotime($result['data']['sched_time']));
            $plat_orderinfo['schedend_time'] = date('m-d H:i', strtotime($result['data']['sched_time']) + $film['duration'] * 60);

            // 订单状态 0：待支付；1：已出票；3：已取消
            $statuspayinfo = $this->getOrderStatus($plat_orderinfo['create_time'], $plat_orderinfo['status']);
            $plat_orderinfo['status'] = $statuspayinfo['status'];
            $plat_orderinfo['state'] = $statuspayinfo['state'];
            $plat_orderinfo['time_remaining'] = $statuspayinfo['time_remaining'];// 支付倒计时

            unset($plat_orderinfo['plat_order']);
            unset($plat_orderinfo['third_order']);
            return $plat_orderinfo;
        }
        throw new ValidateException('订单不存在');
    }

    /**
     * 获取订单状态
     *
     * @param $create_time
     * @param $plat_status
     * @return array
     */
    private function getOrderStatus($create_time, $plat_status = 0)
    {
        $time_remaining = 0;

        $time = time();
        // 订单状态 0：待支付；1：已出票；3：已取消
        $create_time = $create_time + self::tenMinute;
        if (($plat_status == 0) || ($plat_status == 1)) {
            if ($create_time < $time) {
                $status = 3;
                $state = '支付超时，已取消';
            } else {
                $status = 0;
                $state = '待付款';
                $time_remaining = $time - $create_time;
            }
        } elseif ($plat_status == 5) {
            $status = 3;
            $state = '支付超时，已取消';
        } elseif ($plat_status == 6) {
            $status = 1;
            $state = '已出票';
        } else {
            $status = 3;
            $state = '支付超时，已取消';
        }

        return compact('status', 'state', 'time_remaining');
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLocalMovieCity()
    {
        $city_name = [];

        $city = Db::name('movie_city')->field('city_sign,city_name,initial')->where('is_show', 1)->order('id asc')->select();
        foreach ($city as $key => $value) {
            $city_name[$value['initial']][] = ['city_sign' => $value['city_sign'], 'city_name' => $value['city_name']];
        }

        $initial = !empty($city) ? array_values(array_column($city->toArray(), 'initial', 'initial')) : [];

        return compact('city_name', 'initial');
    }

    /**
     * 获取pv、养老金、售价、积分
     *
     * @param $cost_price
     * @return array
     */
    public static function getPvYanglaojinScore($cost_price, $movie_commission_rate_config)
    {
        $premium_ratio = isset($movie_commission_rate_config['premium_rate']) ? $movie_commission_rate_config['premium_rate'] : self::premium_ratio;
        $pv_ratio = isset($movie_commission_rate_config['pv_rate']) ? $movie_commission_rate_config['pv_rate'] : self::pv_ratio;
        $yanglaojin_ratio = isset($movie_commission_rate_config['consumer_yanglaojin_rate']) ? $movie_commission_rate_config['consumer_yanglaojin_rate'] : self::yanglaojin_ratio;

        $premium = round($cost_price * $premium_ratio, 2);
        $cost_price = bcadd((string)$cost_price, (string)$premium, 2);
        $pv = $gongxian = $score = bcmul((string)$premium, $pv_ratio, 2);
        $yanglaojin = bcmul((string)$premium, $yanglaojin_ratio, 2);

        return compact('premium', 'cost_price', 'pv', 'yanglaojin', 'gongxian', 'score');
    }

    /**
     * 计算佣金分佣奖励
     *
     * @param $pay_type
     * @param $order_sn
     * @param $post_data
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateMovieOrderAndcalculationCommissionDividendAward($pay_type, $order_sn, $post_data)
    {
        $orderinfo = $this->dao->search(['order_sn' => $order_sn])->find();
        if ($orderinfo) throw new ValidateException('订单不存在');
        Db::startTrans();
        $orderinfo->paid = 1;
        $orderinfo->pay_time = time();
        $orderinfo->pay_type = $pay_type;
        $orderinfo->status = 1;
        $orderinfo->channel_trade_no = $post_data['id'];
        $orderinfo->pay_open_id = $post_data['expend']['open_id'];
        $orderinfo->update_time = time();
        // 支付方式 1支付宝 2微信
        if ($pay_type == 1) {
            $orderinfo->alipay_no = $post_data['out_trans_id'];
        }
        if ($pay_type == 2) {
            $orderinfo->weixin_no = $post_data['out_trans_id'];
        }
        $res = $orderinfo->save();
        if ($res) {
            $confirmOrder = DouHuoMallFilmApiRequest::confirmOrder($orderinfo['order_sn'], $orderinfo['price']);
            if (!empty($confirmOrder) && isset($confirmOrder['code']) && ($confirmOrder['code'] == ApiResponseService::DEFAULT_SUCCESS_CODE)) {
                // 计算佣金、分红奖励
                $this->calculationCommissionDividendAward($orderinfo);
                // 提交事务
                Db::commit();
            } else {
                Db::name('log')->insert(['data' => '电影票订单支付回调向【微唯宝】--- 告知电影订单已支付失败，订单编号：' . $order_sn]);
                // 回滚事务
                Db::rollback();
                throw new ValidateException('向微维宝确认订单失败');
            }
        } else {
            Db::name('log')->insert(['data' => '汇付电影票订单支付回调--- 更新电影订单表失败，订单编号：' . $order_sn]);
            // 回滚事务
            Db::rollback();
            throw new ValidateException('更新订单失败');
        }
    }

    /**
     * 计算佣金、分红奖励
     * @param $orderinfo
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function calculationCommissionDividendAward($orderinfo)
    {
        /** @var StoreOrderRepository $storeOrderRepository */
        $storeOrderRepository = app()->make(StoreOrderRepository::class);

        // 电影分佣比例配置
        $movie_commission_rate_config = Db::name('system_config_value')->where('config_key', 'movie_commission_rate_config')->find();
        $movie_commission_rate_config = !empty($movie_commission_rate_config) ? json_decode($movie_commission_rate_config['value'], true) : [];
        // 让利金额
        $concession_pri = bcmul((string)$orderinfo['price'], $movie_commission_rate_config['premium_rate'], 2);
        // 养老金
        $ylj_pri = bcmul($concession_pri, $movie_commission_rate_config['consumer_yanglaojin_rate'], 2);
        // 业绩PV
        $pv = bcmul($concession_pri, $movie_commission_rate_config['pv_rate'], 2);

        //-------------------消费者收益---------------------
        // PV值
        $storeOrderRepository->con_log_pv($orderinfo['uid'], $pv, $orderinfo['order_id'], 13, "购买电影票赠送PV值");
        // 养老金
        $this->distributionAnnuityEarnings($orderinfo['uid'], $ylj_pri, $orderinfo['order_id'], 5, $orderinfo['order_sn'], '购买电影票获得养老金' . $ylj_pri, 0, 0);
        // 消费者 - 红包 - 老用户发红包奖励
        $user = Db::name("user")->where('uid', $orderinfo["uid"])->find();
        if ($user['is_old'] == 1) {
            $storeOrderRepository->giveHongBao($orderinfo["uid"], $pv, $orderinfo['order_id'], '购买电影票赠送红包', -1,13);
        }
        // 积分
        $storeOrderRepository->score_log($orderinfo['uid'], $pv, $orderinfo['order_id'], 13, "购买电影票赠送积分");
        // 贡献值
        $storeOrderRepository->con_log($orderinfo['uid'], $pv, $orderinfo['order_id'], 13, "购买电影票赠送贡献值");
        //-------------------消费者收益---------------------

        // 推广者
        if ($user['spread_uid'] != 0) {
            //查询{下单用户}的上级
            $spread_data = Db::name('user')->where('uid', $user['spread_uid'])->find();
            $rate = $storeOrderRepository->getUserGroupRate($spread_data['user_group']);

            //养老金
            $spread_yanglaojin = bcmul($pv, $movie_commission_rate_config['spread_yanglaojin_rate'], 2);
            $this->distributionAnnuityEarnings(
                $spread_data['uid'], $spread_yanglaojin, $orderinfo['order_id'], 5, $orderinfo['order_sn'], '电影票-推广者获得养老金' . $spread_yanglaojin, 0, 0
            );

            // 直推佣金
            $yj_amount_90 = round(bcmul($pv, $rate, 2) * $movie_commission_rate_config['commission_directthrust_rate'], 2);
            $this->distributionAnnuityEarnings(
                $spread_data['uid'], $yj_amount_90, $orderinfo['order_id'], 3, $orderinfo['order_sn'], '电影票-推广者获得直推佣金' . $yj_amount_90,
                0, 0
            );

            // 复购金-推广者的佣金抽10%到个人复购金
            $fgj_amount_10 = round(bcmul($pv, $rate, 2) * $movie_commission_rate_config['repurchase_directthrust_rate'], 2);
            $storeOrderRepository->fugou_user_log($spread_data['uid'], $fgj_amount_10, $orderinfo['order_id'], 1, -1, 13);

            // 积分
            $score = bcmul($pv, $rate, 2);
            $storeOrderRepository->score_log($spread_data['uid'], $score, $orderinfo['order_id'], 13, "电影票-推广者获得赠送积分");

            // 业务员及以上身份
            if ($spread_data['user_group'] > 1) {
                // 贡献值
                $storeOrderRepository->con_log($spread_data['uid'], $pv, $orderinfo['order_id'], 13, "电影票-推广者获得赠送贡献值");
            }

            // 普通用户推广人
            if ($spread_data['user_group'] == 1) {
                // 贡献值
                $gongxianValue = bcmul($pv, $movie_commission_rate_config['contributionvalue_spread_user_rate'], 2);
                $storeOrderRepository->con_log($spread_data['uid'], $gongxianValue, $orderinfo['order_id'], 13, "电影票-推广者用户身份获得赠送贡献值");
            }
        }

        // 锁客收益
        if ($user['mer_id'] != 0) {
            $merchant_uid = Db::name('merchant')->where('mer_id', $user['mer_id'])->value('uid');
            $merchant_user = Db::name('user')->where('uid', $merchant_uid)->find();
            if (!empty($merchant_user)) {
                // 锁客佣金
                $yj_amount_90 = round(bcmul($pv, $movie_commission_rate_config['commission_lockpassenger_merid_rate'], 2) * $movie_commission_rate_config['commission_lockpassenger_rate'], 2);
                $this->distributionAnnuityEarnings(
                    $merchant_uid, $yj_amount_90, $orderinfo['order_id'], 3, $orderinfo['order_sn'], '电影票-商户锁定用户获得佣金' . $yj_amount_90,
                    $user['mer_id'], 0
                );

                // 锁客复购金
                $fgj_amount_10 = round(bcmul($pv, $movie_commission_rate_config['repurchase_lockpassenger_merid_rate'], 2) * $movie_commission_rate_config['repurchase_lockpassenger_rate'], 2);
                $storeOrderRepository->fugou_user_log($merchant_uid, $fgj_amount_10, $orderinfo['order_id'], 1, -1, 13);
            }
        }
    }

    /**
     * 直推奖、养老金
     *
     * @param $uid
     * @param $num
     * @param $order_id
     * @param $comm_order_type
     * @param $order_sn
     * @param $mark
     * @param $merid
     * @param $ds
     * @return void
     */
    private function distributionAnnuityEarnings($uid, $num, $order_id, $comm_order_type, $order_sn, $mark, $merid, $ds = 0)
    {
        $name = '';

        if ($comm_order_type == 3) {
            $name = '直推奖';

        } else if ($comm_order_type == 5) {
            $name = '养老金';
        }

        $bill = [
            'uid' => $uid,
            'link_id' => $order_id,//关联订单id
            'pm' => 1,//0：支出，1：获得
            'title' => $name,//账单标题
            'category' => 'now_money',//明细种类
            'type' => 'commission',//明细类型
            'number' => $num,//明细数字
            'balance' => 0,//剩余
            'mark' => $mark,//备注
            'create_time' => date('Y-m-d H:i:s'),//添加时间
            'status' => $ds,//0待确定，1有效，-1无效
            'commission_type' => $comm_order_type,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
            //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
            //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
            'order_sn' => $order_sn,//订单号
            'tripartite' => 0,//
            'type_shop' => 13,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
            'mer_id' => $merid,//商户id
            'source' => 0,//1线下 0线上
            'order_type' => 1,//1自营  2 第三方  订单类型
            'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
            'gzc' => 0,//养老金是否已进入公证处log表0：未进入。1：已进入
            'take_time' => '',//结算时间
            'district_id' => '',//
            'street_id' => '',//
            'month' => '',//月份
        ];

        Db::name('user_bill')->insert($bill);
    }

    /**
     * 订单列表
     *
     * @param $userinfo
     * @param $page
     * @param $limit
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderList($userinfo, $page, $limit, $type = -1)
    {
        $where['uid'] = $userinfo['uid'];
        switch ($type) {
            case 0:
                $where['status'] = [0];
                break;
            case 1:
            case 4:
                $where['status'] = [1, 4];
                break;
            case 2:
            case 3:
                $where['status'] = [2, 3];
                break;
            default:
                break;
        }
        $film = [];

        $field = 'order_sn,order_price,city_name,area_name,cinema_name,address,hall_name,film_sign,film_name,show_date,show_time,sched_seat,number,status,create_time';
        $movie_order = $this->dao->search($where)
            ->when($page && $limit, function ($query) use ($page, $limit) {
                $query->page($page, $limit);
            })->order('order_id desc')->field([$field])->select()->toArray();
        foreach ($movie_order as $key => $value) {
            if (!isset($film[$value['film_sign']])) $film[$value['film_sign']] = Db::name('movie_film')->where('film_sign', $value['film_sign'])->value('cover_img');
            $movie_order[$key]['sched_seat'] = json_decode($value['sched_seat'], true);
            $movie_order[$key]['cover_img'] = $film[$value['film_sign']];
            $movie_order[$key]['time_remaining'] = 0;

            // 订单状态 0：待支付；1：已出票；3：已取消
            $statuspayinfo = $this->getOrderStatus(strtotime($value['create_time']), $value['status']);
            $movie_order[$key]['status'] = $statuspayinfo['status'];
            $movie_order[$key]['state'] = $statuspayinfo['state'];
            $movie_order[$key]['time_remaining'] = $statuspayinfo['time_remaining'];// 支付倒计时
        }

        $count = $this->dao->search($where)->count();

        return compact('movie_order', 'count');
    }

    /**
     * 所有未支付订单列表
     *
     * @param $status
     * @param $paid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderListAll($status = [], $paid = 0)
    {
        $where = ['status' => $status, 'paid' => $paid];

        $field = 'order_id,order_price,city_name,area_name,cinema_name,address,hall_name,film_sign,film_name,show_date,show_time,sched_seat,number,status,create_time';
        //        foreach ($movie_order as $key => $value) {
//            $movie_order[$key]['sched_seat'] = json_decode($value['sched_seat'], true);
//            $movie_order[$key]['cover_img'] = Db::name('movie_film')->where('film_sign', $value['film_sign'])->value('cover_img');
//        }

        return $this->dao->search($where)->order('create_time asc')->field([$field])->select()->toArray();
    }
}
