<?php


namespace app\controller\merchant\finance;

use app\common\repositories\finance\FinanceRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\controller\api\entropybarter\User;
use crmeb\basic\BaseController;
use crmeb\services\AliYunSmsService;
use think\facade\Cache;
use think\facade\Db;

class PlatformIncomeDetail extends BaseController
{
    public function lst()
    {
        try {
            [$page, $limit] = $this->getPage();
            $where = $this->request->params(['date']);
            $params = $this->request->params(['pm', 'subjection_team_uid', 'deal_type', 'search', 'keyword', 'select_type']);


            //商户ID
            $mer_id = $this->request->merId();
            $query = Db::name('enterprise_platform_income_detail')
                ->alias('income_detail')
                ->leftJoin('user u', 'u.uid=income_detail.uid')
                ->where('income_detail.mer_id', $mer_id)
                ->when(isset($params['pm']) && $params['pm'] != '', function ($query) use ($params) {
                    $query->where('pm', $params['pm']);
                })
                ->when(isset($params['deal_type']) && $params['deal_type'] > 0, function ($query) use ($params) {
                    $query->where('deal_type', $params['deal_type']);
                })
//                ->when(isset($params['select_type']) && !empty($params['select_type']), function ($query) use ($params, $mer_id) {
//                    if ($params['select_type'] == 'platform_income_detail') {
//                        $query->whereIn('deal_type', [1, 2, 3, 5]);
//                    } elseif ($params['select_type'] == 'platform_income_detail_yj') {
//                        $income_detail_ids = Db::name('enterprise_platform_income_detail')
//                            ->alias('income_detail')
//                            ->leftJoin('user u', 'u.uid=income_detail.uid')
//                            ->leftJoin('store_order o', 'o.order_id=income_detail.order_id')
//                            ->where('income_detail.mer_id', $mer_id)->where('income_detail.deal_type', 4)->where('pay_type!=5')->column('income_detail.id');
//                        $query->whereIn('income_detail.id', $income_detail_ids);
//                    }
//                })
                ->when(isset($params['search']) && $params['search'], function ($query) use ($params) {
                    $select_uid = Db::name('user')
                        ->where('nickname', 'like', "%{$params['search']}%")
                        ->whereOr('phone', 'like', "%{$params['search']}%")
                        ->column('uid');
                    $query->whereIn('income_detail.uid', $select_uid);
                })
                ->when(isset($params['keyword']) && $params['keyword'], function ($query) use ($params) {
                    $select_uid = Db::name('user')
                        ->where('nickname', 'like', "%{$params['keyword']}%")
                        ->whereOr('phone', 'like', "%{$params['keyword']}%")
                        ->column('uid');
                    if ($select_uid) {
                        $query->where(" (income_detail.uid in (" . join(',', $select_uid) . ") or income_detail.deal_order_sn like '%{$params['keyword']}%' or income_detail.order_sn like '%{$params['keyword']}%')");
                    } else {
                        $query->where(" (income_detail.deal_order_sn like '%{$params['keyword']}%' or income_detail.order_sn like '%{$params['keyword']}%')");
                    }
                })
                ->when(isset($params['subjection_team_uid']) && $params['subjection_team_uid'], function ($query) use ($params, $mer_id) {
                    unset($where);
                    $node_uid = $params['subjection_team_uid'];
                    $where['node_uid'] = $node_uid;
                    $where['mer_id'] = $mer_id;

                    $tema_id = $this->jisuantuandui($where, [$node_uid]);
                    if ($params['select_type'] != 'platform_income_detail')
                        $tema_id = array_diff($tema_id, [$node_uid]);
                    $query->whereIn('income_detail.uid', $tema_id);
                })
                // ->where('u.test_user', '<', '1')
                ->page($page, $limit)
                ->field('income_detail.*,u.nickname,u.phone')
                ->order('income_detail.deal_time', 'desc');
            $list = $this->date_where($query, $where['date'], 'income_detail.deal_time')->select();
            if (!$list) {
                return app('json')->success([]);
            }

            $count = $query->count('income_detail.id');

            $list->each(function ($item) use ($mer_id) {
                $enterprise_user = Db::name('enterprise_user')
                    ->where('uid', $item['uid'])
                    ->find();

                $item['subjection_team_phone'] = $item['pay_type'] = '';
                if ($enterprise_user) {
                    if ($enterprise_user['node_uid'] == 11714) {
                        $node_uid = $item['uid'];
                    } else {
                        $node_uid = $this->getParentNode($enterprise_user['node_uid']);
                    }

                    $item['subjection_team_phone'] = Db::name('user')
                        ->where('uid', $node_uid)
                        ->value('phone');
                }
                $item['pay_type'] = Db::name('store_order')
                    ->where('order_id', $item['order_id'])
                    ->value('pay_type');
                $item['extract_type'] = Db::name('user_extract')
                    ->where('extract_id', $item['user_extra_id'])
                    ->value('extract_type');
                return $item;
            });

            $query1 = clone $query;
            $query2 = clone $query;
            $query3 = clone $query;
            $query4 = clone $query;
            $query5 = clone $query;
            $query6 = clone $query;
            //总入账
            // 佣金提现
            $yongjin_out_all = $query5
                ->where('deal_type', 2)
                ->where('pm', 1)
                ->sum('income_detail.money');
            // 订单入账总额
            $order_in_money = $query6
                ->where('deal_type', 1)
                ->where('pm', 1)
                ->sum('income_detail.money');
            $order_in_vr = $query6
                ->where('deal_type', 1)
                ->where('pm', 1)
                ->sum('income_detail.vr');
            $order_in_fg = $query6
                ->where('deal_type', 1)
                ->where('pm', 1)
                ->sum('income_detail.fg');
            $platform_enter_all = $yongjin_out_all+$order_in_money+$order_in_vr+$order_in_fg;

            $return_data = compact( 'platform_enter_all', 'yongjin_out_all', 'list', 'count', 'order_in_money', 'order_in_vr', 'order_in_fg');
            return app('json')->success($return_data);
        } catch (\Exception $e) {
            Db::name('log')->insert(['data' => '获取平台收支明细错误：' . $e->getFile() . '：' . $e->getLine() . '【' . $e->getMessage() . '】']);
            return app('json')->fail('获取平台收支明细失败' . $e->getFile() . '：' . $e->getLine() . '【' . $e->getMessage());
        }
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     * @day 2020-06-11
     */
    public function detail($id)
    {
        $mer_id = $this->request->merId();
        $financeRepository = app()->make(FinanceRepository::class);
        $data = $financeRepository->income_detail($id,$mer_id);
        return app('json')->success($data);
    }

    /**
     * 列表中的时间条件
     */
    public function date_where($Db, $where, $prefix = '', $field = '-')
    {
        if (!isset($where)) return $Db;
        switch ($where) {
            case strlen($where) == 10 && strstr($where, $field) !== false:
                // 2024-03-08
                $Db->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($where)), date('Y-m-d H:i:s', strtotime($where . ' +1day -1second')));
            case strlen($where) == 7 && strstr($where, $field) !== false:
                // 2024-03
                $Db->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($where)), date('Y-m-d H:i:s', strtotime($where . ' +1month -1second')));
                break;
            case 'today':
                $Db->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('today')), date('Y-m-d H:i:s', strtotime('tomorrow -1second'))]);
                break;
            case 'week':
                $Db->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('this week 00:00:00')), date('Y-m-d H:i:s', strtotime('next week 00:00:00 -1second'))]);
                break;
            case 'month':
                $Db->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('first Day of this month 00:00:00')), date('Y-m-d H:i:s', strtotime('first Day of next month 00:00:00 -1second'))]);
                break;
            case 'year':
                $Db->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('this year 1/1')), date('Y-m-d H:i:s', strtotime('next year 1/1 -1second'))]);
                break;
            case 'yesterday':
                $Db->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('yesterday')), date('Y-m-d H:i:s', strtotime('today -1second'))]);
                break;
            case 'quarter':
                list($startTime, $endTime) = getMonth();
                $Db = $Db->where($prefix, '>', $startTime);
                $Db = $Db->where($prefix, '<', $endTime);
                break;
            case 'lately7':
                $Db = $Db->where($prefix, 'between', [date('Y-m-d', strtotime("-7 day")), date('Y-m-d H:i:s')]);
                break;
            case 'lately30':
                $Db = $Db->where($prefix, 'between', [date('Y-m-d', strtotime("-30 day")), date('Y-m-d H:i:s')]);
                break;
            default:
                if (strstr($where, $field) !== false) {
                    list($startTime, $endTime) = explode($field, $where);
                    if (strlen($startTime) == 4) {
                        $Db->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($startTime)), date('Y-m-d H:i:s', strtotime($startTime . ' +1day -1second')));
                    } else {
                        if ($startTime == $endTime) {
                            $Db = $Db->whereDay($prefix, $startTime);
                        } else {
                            $Db = $Db->where($prefix, '>', date('Y-m-d H:i:s', strtotime($startTime)));
                            $Db = $Db->where($prefix, '<', date('Y-m-d H:i:s', strtotime($endTime)));
                        }
                    }
                }
                break;
        }
        return $Db;
    }

}
