<?php
/**
 * +------------------------------------------------------------
 * | CIM
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-04-19 17:40:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-07-14 18:02:58
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\finance\controller;

use think\Db;
use app\common\controller\Init;

class Index extends Init
{
    private static $user_money = 0;

    private static $user_credit = 0;

    private static $data;

    private static $key = ['top' => '置顶', 'refresh' => '刷新', 'redpack' => '信息红包', 'add' => '付费发布', 'buy' => '购买信息', 'money' => '付款'];

    private static $money_credit = 0;

    private static $payment = '';

    private static $appid;

    private static $behavior = [];

    private static $order;

    private static $method;

    private static $cart = [];

    private static $cart_id = 0;

    private static $result = [
        'final_user_money' => 0,
        'final_user_credit' => 0,
        'final_money' => 0,
        'data' => []
    ];

    public function initialize()
    {
        parent::initialize();
        if (self::$user['id']) {
            $user = model('app\user\model\User')->get(self::$user['id']);
            if (!empty($user)) {
                self::$user_money = $user['money'];
                self::$user_credit = $user['credit'];
            }
        }
        $finance_setting = load_setting('finance');
        if (!empty($finance_setting['money_credit_' . self::$user['group_id']])) self::$money_credit = $finance_setting['money_credit_' . self::$user['group_id']];
        self::$data = input('param.');
        if (is_string(self::$data)) self::$data = json_decode(self::$data, 1);
        $this->_init_data();
    }

    /**
     * 处理数据
     */
    private function _init_data()
    {
        if (isset(self::$data['payment'])) {
            self::$payment = self::$data['payment'];
            unset(self::$data['payment']);
        }
        if (isset(self::$data['attr'])) {
            unset(self::$data['attr']);
        }
        if (isset(self::$data['order'])) {
            self::$order = self::$data['order'];
            unset(self::$data['order']);
        }
        if (isset(self::$data['method'])) {
            self::$method = self::$data['method'];
            unset(self::$data['method']);
        }
        if (isset(self::$data['cart_id'])) {
            self::$cart_id = self::$data['cart_id'];
            unset(self::$data['cart_id']);
        }
        if (empty(self::$data)) {
            if (self::$user['id']) {
                $cart = model('app\finance\model\Cart')->where('user_id', '=', self::$user['id'])->select()->toArray();
                if (!empty($cart)) {
                    foreach ($cart as $k => $v) {
                        $v['extend']['cart_id'] = $v['id'];
                        self::$data[$v['key']] = $v['extend'];
                    }
                } else {
                    return;
                }
            }
        }
        $data = (count(self::$data) == count(self::$data, 1)) ? [self::$data] : self::$data;
        foreach ($data as $k => $v) {
            if (empty(array_intersect([$k], array_keys(self::$key)))) {
                if (empty($v) || empty($v = $this->rule($v))) continue;
                list($k, $v) = $v;
            }
            //根据行为计算价格
            $result = $this->check($k, $v);
            if (!empty($result)) {
                if ($result['code']) {
                    if ($result['credit'] > self::$user_credit && empty(self::$money_credit)) {
                        $result['code'] = 61027;
                        $result['msg'] = '积分不足，请充值...';
                        self::$result['data'][] = $result;
                        continue;
                    }
                    $result['money_credit'] = self::$money_credit;
                    $result['user_money'] = self::$user_money;
                    $result['user_credit'] = self::$user_credit;
                    $result['final_user_money'] = $result['money'];
                    $result['final_user_credit'] = $result['credit'];
                    $result['final_money'] = 0;
                    if ($result['credit'] > $result['user_credit']) {
                        $result['final_user_credit'] = $result['user_credit'];
                        $over_credit = $result['credit'] - $result['user_credit'];
                        $result['money'] = (float)$result['money'] + round($over_credit / $result['money_credit']);
                        $result['final_user_money'] = $result['money'];
                        $result['credit'] = $result['user_credit'];
                    }
                    if ($result['money'] > $result['user_money']) {
                        $result['final_user_money'] = $result['user_money'];
                        $result['final_money'] += ($result['money'] - $result['user_money']);
                        $result['money'] = $result['user_money'];
                    }
                    self::$user_credit = self::$user_credit - $result['final_user_credit'];
                    self::$user_money = self::$user_money - $result['final_user_money'];
                    //购物车数据
                    self::$cart[] = [
                        'name' => $result['title'],
                        'key' => $k,
                        'extend' => $v,
                        'user_id' => self::$user['id'],
                        'data_id' => isset($v['data_id']) ? $v['data_id'] : ($v['id'] ?? 0)
                    ];
                }
                self::$result['data'][] = $result;
            }
        }
        self::$result['count'] = count(self::$result['data']);
        foreach (self::$result['data'] as $k => $v) {
            if (isset($v['final_user_credit'])) self::$result['final_user_credit'] += $v['final_user_credit'];
            if (isset($v['final_user_money'])) self::$result['final_user_money'] += $v['final_user_money'];
            if (isset($v['final_money'])) self::$result['final_money'] += $v['final_money'];
        }
    }

    /**
     * 接收商品规则
     */
    private function rule($data)
    {
        $rule = [
            //发布信息规则
            'add' => [
                'column_id',
                'data_id'
            ],
            //购买信息规则
            'buy' => [
                'data_id'
            ],
            //只付款
            'money' => [
                'money'
            ],
            //查看信息
            'view' => [
                'cid',
                'id'
            ],
            //置顶
            'top' => [
                'data_id',
                'days'
            ],
            //刷新
            'refresh' => [
                'data_id'
            ],
            //红包
            'redpack' => [
                'data_id',
                'num',
                'type',
                'money'
            ]
        ];
        foreach ($rule as $k => $v) {
            if (empty(array_diff($v, array_keys($data))) && empty(array_diff(array_keys($data), $v))) {
                return [$k, $data];
            }
        }
    }

    //创建订单
    public function create_order()
    {
        if (empty(self::$result['data'])) {
            return json(['code' => 61020, 'msg' => '未找到有效的数据信息']);
        }
        if (self::$result['final_money'] == 0 && self::$result['final_user_credit'] == 0 && self::$result['final_user_money'] == 0) return json(['code' => 61024, 'msg' => '结算金额为0，请仔细检查后重试...']);
        if (self::$result['final_money'] && (empty(self::$payment) || !in_array(self::$payment, ['2', '3']))) return json(['code' => 61025, 'msg' => '支付方式只能选择支付宝或微信']);
        $order = [
            'payment' => self::$payment ?: (self::$result['final_user_money'] ? 1 : 0),
            'money' => self::$result['final_money'] ?: (self::$result['final_user_money'] ?: self::$result['final_user_credit']),
            'balance' => 0,
            'type' => (self::$result['final_money'] || self::$result['final_user_money']) ? 1 : 0,
            'behavior' => 'goods',
            'extend' => '',
            'appid' => self::$appid
        ];
        Db::startTrans();
        try {
            $order = action('finance/api/order', [$order, 0]);
            if ($order['code'] == 0) return json(['code' => 61026, 'msg' => $order['msg']]);
            $goods = [];
            $time = time();
            foreach (self::$result['data'] as $k => $v) {
                if ($v['code']) {
                    $goods[] = [
                        'order_id' => $order['order'],
                        'title' => $v['title'],
                        'user_credit' => $v['final_user_credit'],
                        'user_money' => $v['final_user_money'],
                        'money' => $v['final_money'],
                        'extend' => self::$behavior[$k]['data'],
                        'behavior' => self::$behavior[$k]['key'],
                        'create_time' => $time
                    ];
                }
            }
            if (!empty($goods)) {
                model('app\finance\model\Goods')->saveAll($goods);
            }
            Db::commit();
            return json(['code' => 1, 'msg' => '订单创建成功', 'order' => $order['order']]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 61026, 'msg' => $e->getMessage()]);
        }
    }

    /**
     *
     * 数据验证器
     * key：行为
     * data：数据
     */
    private function check($key, $data)
    {
        $validate = validate('app\finance\validate\\' . ucfirst($key));
        if ($validate->check($data) !== true) {
            $result['code'] = 61021;
            $result['msg'] = $validate->getError();
            $result['title'] = self::$key[$key];
            if (isset($data['data_id'])) {
                $title = db('data')->where('id', '=', $data['data_id'])->value('name');
                $result['title'] .= '【' . $title . '】';
            }
        } else {
            self::$behavior[] = [
                'key' => $key,
                'data' => $data
            ];
            $result = $this->$key($data);
        }
        return $result;
    }

    /**
     * 置顶
     * @param $data
     */
    private function top($data)
    {
        $info = db('data')->where('id', '=', $data['data_id'])->find();
        $column = load_column($info['column_id']);
        if (empty($info)) return ['code' => 61022, 'msg' => '所需信息不存在或已删除'];
        if (empty($column)) return ['code' => 61023, 'msg' => '栏目不存在'];
        return [
            'code' => 1,
            'money' => (empty($column['setting']['group'][self::$user['group_id']]['top_money']) ? 0 : $column['setting']['group'][self::$user['group_id']]['top_money']) * $data['days'],
            'credit' => (empty($column['setting']['group'][self::$user['group_id']]['top_credit']) ? 0 : $column['setting']['group'][self::$user['group_id']]['top_credit']) * $data['days'],
            'title' => self::$key['top'] . '【' . $info['name'] . '】'
        ];
    }

    /**
     * 刷新
     * @param $data\
     */
    private function refresh($data)
    {
        $info = db('data')->where('id', '=', $data['data_id'])->find();
        $column = load_column($info['column_id']);
        if (empty($info)) return ['code' => 61022, 'msg' => '所需信息不存在或已删除'];
        if (empty($column)) return ['code' => 61023, 'msg' => '栏目不存在'];
        return [
            'code' => 1,
            'money' => empty($column['setting']['group'][self::$user['group_id']]['refresh_money']) ? 0 : $column['setting']['group'][self::$user['group_id']]['refresh_money'],
            'credit' => empty($column['setting']['group'][self::$user['group_id']]['refresh_credit']) ? 0 : $column['setting']['group'][self::$user['group_id']]['refresh_credit'],
            'title' => self::$key['refresh'] . '【' . $info['name'] . '】'
        ];
    }

    /**
     * 信息红包
     * @param $data
     */
    private function redpack($data)
    {
        $info = db('data')->where('id', '=', $data['data_id'])->find();
        if (empty($info)) return ['code' => 61022, 'msg' => '所需信息不存在或已删除'];
        return [
            'code' => 1,
            'money' => $data['money'],
            'credit' => 0,
            'title' => self::$key['redpack'] . '【' . $info['name'] . '】'
        ];
    }

    /**
     * 发布信息
     * @param $data
     */
    private function add($data)
    {
        $column = load_column($data['column_id'], 0, '');
        if (empty($column)) return ['code' => 61023, 'msg' => '栏目不存在'];
        $money = empty($column['setting']['group'][self::$user['group_id']]['add_money']) ? 0 : $column['setting']['group'][self::$user['group_id']]['add_money'];
        $credit = empty($column['setting']['group'][self::$user['group_id']]['add_credit']) ? 0 : $column['setting']['group'][self::$user['group_id']]['add_credit'];
        self::$behavior[] = [
            'key' => 'add',
            'data' => $data
        ];
        return [
            'code' => 1,
            'money' => $money > 0 ? 0 : abs($money),
            'credit' => $credit > 0 ? 0 : abs($credit),
            'title' => '发布信息【' . db('data')->where('id', '=', $data['data_id'])->value('name') . '】'
        ];
    }

    /**
     * 购买信息
     * @param $data
     */
    private function buy($data)
    {
        $info = model('app\index\model\Data')->get($data['data_id']);
        if (empty($info)) return ['code' => 61022, 'msg' => '所需信息不存在或已删除'];
        self::$behavior[] = [
            'key' => 'buy',
            'data' => $data
        ];
        if (isset($info['fields']['jiage'])) {
            if (!is_numeric($info['fields']['jiage'])) return ['code' => 61030, 'msg' => '当前信息未设置价格'];
            if ($info['fields']['jiage'] < 0.01) return ['code' => 61031, 'msg' => '当前信息设置价格小于0.01'];
            return [
                'code' => 1,
                'money' => $info['fields']['jiage'],
                'credit' => 0,
                'title' => '购买信息【' . $info['name'] . '】'
            ];
        } else {
            return ['code' => 61028, 'msg' => '当前信息未设置价格'];
        }
    }

    /**
     * 查看信息行为
     * @param $data
     */
    private function view($data)
    {
        $column = load_column($data['cid']);
        if (empty($column)) return ['code' => 61029, 'msg' => '栏目不存在'];
        if (empty($column['setting']['group'][self::$user['group_id']]['view_money'])) return ['code' => 61030, 'msg' => '栏目未设置查看信息价格'];
        $info = model('app\index\model\Data')->get($data['data_id']);
        if (empty($info)) return ['code' => 61022, 'msg' => '所需信息不存在或已删除'];
        self::$behavior[] = [
            'key' => 'view',
            'data' => $data
        ];
        return [
            'code' => 1,
            'money' => $column['setting']['group'][self::$user['group_id']]['view_money'],
            'credit' => 0,
            'title' => '查看信息【' . $info['name'] . '】'
        ];
    }

    /**
     * 支付行为
     * @param $data
     * @return array
     */
    private function money($data)
    {
        self::$behavior[] = [
            'key' => 'money',
            'data' => $data
        ];
        return [
            'code' => 1,
            'money' => $data['money'],
            'credit' => 0,
            'title' => '付费'
        ];
    }

    /**
     * 购物车
     */
    public function cart()
    {
        if (!self::$user['id']) return json(['code' => 1000, 'msg' => '请登录']);
        if (self::$cart_id) {
            db('cart')->where('id', 'in', (array)self::$cart_id)->delete();
            return json(['code' => 1, 'msg' => '清除成功']);
        } else {
            if (!empty(self::$cart)) {
                $cart = model('app\finance\model\Cart')->field('*,concat(`key`,`data_id`) temp')->where('user_id', '=', self::$user['id'])->select()->toArray();
                if (!empty($cart)) {
                    $cart = array_column($cart, null, 'temp');
                    foreach (self::$cart as $k => $v) {
                        if (isset($cart[$v['key'] . $v['data_id']])) {
                            self::$cart[$k]['id'] = $cart[$v['key'] . $v['data_id']]['id'];
                        }
                    }
                }
                model('app\finance\model\Cart')->allowField(true)->saveAll(self::$cart);
            }
            return json(['code' => 1, 'msg' => '添加成功']);
        }
    }

    /**
     * 返回处理后的结果数据
     * @param int $json
     * @return array|\think\response\Json
     */
    public function get($json = 1)
    {
        $result = [
            'code' => 1,
            'msg' => '加载成功',
            'data' => self::$result,
        ];
        return $json ? json($result) : $result;
    }

    /**
     * 收银台页面
     */
    public function cashier()
    {
        //返回处理结果
        $this->assign('goods', self::$result);
        //返回原始数据
        $this->assign('data', self::$data);
        return view('../finance/cashier');
    }

    /**
     * @param $name
     * @return \think\Response
     */
    public function pay()
    {
        return action('finance/api/pay', [[
            'order' => self::$order,
            'method' => self::$method
        ]]);
    }

    public function _empty($name)
    {
        return $this->_404();
    }
}