<?php
/**
 * +------------------------------------------------------------
 * | 财务 finance/controller/Api.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\finance\controller;

use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;
use app\finance\controller\Behavior;
use app\finance\controller\Alipay;
use app\finance\controller\Wechat;
use think\facade\Env;
use think\Db;

class Api extends Module
{

    /**
     * 积分
     */
    public function credit($attr = [], $return = 1)
    {
        $attr['type'] = 0;
        return $this->handle_data($attr, $return);
    }

    /**
     * 资金
     */
    public function money($attr = [], $return = 1)
    {
        $attr['type'] = 1;
        return $this->handle_data($attr, $return);
    }

    /**
     * 交易记录
     */
    function log($order_id = '', $memo = '')
    {
        if ($order_id) {
            $data = [
                'order_id' => $order_id,
                'memo' => $memo ?: ('订单【' . $order_id . '】支付成功'),
                'create_time' => time()
            ];
            model('app\finance\model\Log')->create($data);
        }
    }

    /*
     * 操作积分和余额
     */
    function handle_data($attr = [], $return = 1)
    {
        if (empty($attr['order'])) {
            $attr = $this->order($attr, 0);
        }
        $validate = $this->validate($attr, ['order' => 'require'], ['order.require' => '订单号不能为空']);
        if ($validate === true) {
            $order = model('app\finance\model\Order')->where('id', '=', $attr['order'])->find();
            if (!empty($order) && $order['status'] != 1) {
                //判断操作的是余额或积分
                $field = $order['type'] == 0 ? 'credit' : 'money';
                if (!empty($order['user_id'])) {
                    if (in_array($order['payment'], [2, 3]) && $order['balance'] == 0) {
                        $result = ['code' => 1, 'msg' => '操作成功'];
                    } else {
                        if ($order['balance'] == 0) {
                            $num = model('app\user\model\User')->where('id', $order['user_id'])->value($field);
                            if ($num >= $order['money']) {
                                model('app\user\model\User')->where('id', $order['user_id'])->setDec($field, $order['money']);
                                $result = ['code' => 1, 'msg' => '操作成功'];
                            } else {
                                $result = ['code' => 62002, 'msg' => (($field == 'credit' ? '积分' : '余额') . '不足')];
                            }
                        } else {
                            model('app\user\model\User')->where('id', $order['user_id'])->setInc($field, $order['money']);
                            $result = ['code' => 1, 'msg' => '操作成功'];
                        }
                    }
                } else {
                    if (in_array($order['payment'], [2, 3])) {
                        $result = ['code' => 1, 'msg' => '操作成功'];
                    } else {
                        $result = ['code' => 62002, 'msg' => (($field == 'credit' ? '积分' : '余额') . '不足')];
                    }
                }
            } else {
                $result = ['code' => 0, 'msg' => '订单不存在或已支付完成'];
            }
        } else {
            $result = ['code' => 62001, 'msg' => $validate];
        }
        if ($result['code'] == 1) {
            $attr['status'] = 1;
            $attr['memo'] = empty($order['memo']) ? '更改' . ($order['type'] == 0 ? '积分' : '余额') : $order['memo'];
            model('app\finance\model\Order')->where('id', $attr['order'])->update([
                'status' => $attr['status'],
                'trade_no' => empty($attr['trade_no']) ? '' : $attr['trade_no'],
                'update_time' => time()
            ]);
            action('message/api/send', [['content' => $attr['memo'], 'user_id' => $order['user_id']]]);
            $this->log($attr['order']);
            if (!empty($order['behavior'])) {
                $behavior = $order['behavior'];
                $behavior_obj = new Behavior();
                if (method_exists($behavior_obj, $behavior)) {
                    $method = $behavior;
                    $behavior_obj->$method(model('app\finance\model\Order')->find($attr['order'])->toArray());
                }
            }
        }
        return $return ? json($result) : $result;
    }

    /**
     * 读取记录
     * @param $attr
     * @return array|null|\PDOStatement|string|\think\Model
     */
    function read($attr = [])
    {
        return json($this->query($attr));
    }

    /**
     * 验证支付结果
     * @param array $attr
     * @return array
     */
    function check_pay_result($attr = [])
    {
        $validate = validate('Check');
        if ($validate->check($attr)) {
            $order = model('app\finance\model\Order')->where('id', $attr['out_trade_no'])->find();
            if (!empty($order)) {
                if ($order['payment'] == 2) {
                    $order['money'] = $order['money'] * 100;
                }
                if ($attr['money'] == $order['money']) {
                    if ($order['status'] == 0) {
                        //处理用户余额
                        $data = [
                            'order' => $attr['out_trade_no'],
                            'trade_no' => $attr['trade_no']
                        ];
                        $res = $this->money($data, 0);
                        if ($res['code'] == 1) {
                            $result = ['code' => 1, 'msg' => '支付成功'];
                        } else {
                            $result = ['code' => 0, 'msg' => $res['msg']];
                        }
                    } else {
                        $result = ['code' => 1, 'msg' => '支付成功'];
                    }
                } else {
                    $result = ['code' => 62003, 'msg' => '支付金额异常'];
                }
            } else {
                $result = ['code' => 62004, 'msg' => '订单不存在'];
            }
        } else {
            $result = ['code' => 0, 'msg' => $validate->getError()];
        }
        return $result;
    }

    /**
     * 积分余额相互兑换
     */
    function convert($attr = [], $return = 1)
    {
        $validate = validate('Convert');
        if ($validate->check($attr)) {
            $less = $attr['type'] == 1 ? 'money' : 'credit';
            $more = $attr['type'] == 1 ? 'credit' : 'money';
            $memo = $attr['type'] == 1 ? '余额兑换积分' : '积分兑换余额';
            $less_payment = $attr['type'] == 1 ? 0 : 1;
            $more_payment = $attr['type'] == 1 ? 1 : 0;
            if (!empty($this->finance_setting[$less . '_' . $more . '_' . session('user.group_id')])) {
                $less_num = $attr['num'] / $this->finance_setting[$less . '_' . $more . '_' . session('user.group_id')];
                $more_num = $attr['num'];
                if (is_int($less_num)) {
                    Db::startTrans();
                    //账户减少数量
                    $attr = [
                        'payment' => $less_payment,
                        'balance' => 0,
                        'money' => intval($less_num),
                        'user_id' => session('user.id'),
                        'memo' => $memo
                    ];
                    $less_result = $this->$less($attr, 0);
                    if ($less_result['code'] == 1) {
                        $attr['balance'] = 1;
                        $attr['money'] = $more_num;
                        $attr['payment'] = $more_payment;
                        $more_result = $this->$more($attr, 0);
                        if ($more_result['code'] == 1) {
                            $result = ['code' => 1, 'msg' => '兑换成功'];
                        } else {
                            $result = ['code' => 62005, 'msg' => $more_result['msg']];
                        }
                    } else {
                        $result = ['code' => 0, 'msg' => $less_result['msg']];
                    }
                    if ($result['code'] == 1) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                } else {
                    $result = ['code' => 62006, 'msg' => ('兑换数量必须是' . ($less == 'money' ? '余额' : '积分') . '的整数倍')];
                }
            } else {
                $result = ['code' => 62007, 'msg' => '请联系管理员设置积分兑换比率'];
            }
        } else {
            $result = ['code' => 62008, 'msg' => $validate->getError()];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 充值
     */
    public function recharge($attr = [], $return = 1)
    {
        $validate = validate('Recharge');
        if ($validate->check($attr)) {
            if (!empty(session('user.id'))) {
                $attr['balance'] = 1;
                $attr['type'] = 1;
                $attr['memo'] = '用户充值';
                $result = $this->order($attr, 0);
                if ($result['code'] == 1) {
                    $pay_result = $this->pay([
                        'method' => $attr['method'],
                        'order' => $result['order'],
                        'openid' => isset($attr['openid']) ? $attr['openid'] : ''
                    ], 0);
                    if ($pay_result['code'] == 1) {
                        $pay_result['order'] = $result['order'];
                        $result = $pay_result;
                    } else {
                        $result = ['code' => 0, 'msg' => $pay_result['msg']];
                    }
                } else {
                    $result = ['code' => 62009, 'msg' => '订单创建失败'];
                }
            } else {
                $result = ['code' => 1000, 'msg' => '请登录'];
            }
        } else {
            $result = ['code' => 0, 'msg' => $validate->getError()];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 支付接口
     */
    public function pay($attr = [], $return = 1)
    {
        $validate = $this->validate($attr, [
            'order' => 'require',
        ], [
            'order.require' => '订单号不能为空',
        ]);
        if ($validate === true) {
            $order = model('app\finance\model\Order')->where('id', '=', $attr['order'])->find();
            if (!empty($order) && $order['status'] != 1) {
                if (in_array($order['payment'], [2, 3])) {
                    if (!empty($attr['method'])) {
                        try {
                            $payment = ($order['payment'] == 2) ? new Wechat() : new Alipay();
                            $method = $attr['method'];
                            $order = array_merge($attr, $order->toArray());
                            if (isset($attr['extend'])) $order['extend'] = array_replace((array)$order['extend'], (array)$attr['extend']);
                            $result = $payment->_init_data($order)->$method();
                        } catch (\Exception $e) {
                            $result = ['code' => 62011, 'msg' => $e->getMessage()];
                        }
                    } else {
                        $result = ['code' => 62012, 'msg' => '支付方式不能为空'];
                    }
                } else if (in_array($order['payment'], [0, 1, 4])) {
                    $result = $this->handle_data($attr, 0);
                } else {
                    $result = ['code' => 62013, 'msg' => '订单支付方式错误'];
                }
            } else {
                $result = ['code' => 62014, 'msg' => '订单不存在或已支付完成'];
            }
        } else {
            $result = ['code' => 62010, 'msg' => $validate];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 删除日志
     */
    function delete($attr = [], $return = 1)
    {
        $where = [];
        if (!empty($attr['id'])) {
            $where [] = ['id', 'in', (array)$attr['id']];
        }
        $where[] = ['user_id', '=', intval(session('user.id'))];
        if (empty($attr['id'])) {
            $result = ['code' => 62015, 'msg' => '请选择要删除的数据'];
        } else {
            model('app\finance\model\Order')->where($where)->delete();
            $result = ['code' => 1, 'msg' => '删除成功'];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 创建订单
     */
    function order($attr = [], $return = 1)
    {
        $validate = $this->validate($attr, [
            'payment' => 'require|in:0,1,2,3,4',
            'money' => 'require|float|egt:0',
            'balance' => 'require|in:0,1',
            'type' => 'require|in:0,1'
        ], [
            'payment.require' => '支付方式不能为空',
            'money.require' => '支付金额不能为空',
            'money.float' => '金额必须是数字',
            'payment.in' => '支付方式请在余额、积分、支付宝、微信、系统支付中选择',
            'balance.require' => '请填写收支类型',
            'balance.in' => '收支类型只能为0、1',
            'type.require' => '请选择操作对象积分、余额',
            'type.in' => '操作对象只能是0、1',
            'money.gt' => '金额必须大于0'
        ]);
        if ($validate === true) {
            $order = [
                'id' => create_str(),
                'balance' => $attr['balance'],
                'user_id' => !empty($attr['user_id']) ? $attr['user_id'] : intval(session('user.id')),
                'money' => $attr['money'],
                'memo' => empty($attr['memo']) ? '' : $attr['memo'],
                'status' => 0,
                'payment' => $attr['payment'],
                'type' => $attr['type'],
                'behavior' => empty($attr['behavior']) ? '' : $attr['behavior'],
                'extend' => empty($attr['extend']) ? '' : json_encode($attr['extend'])
            ];
            if (model('app\finance\model\Order')->create($order)) {
                $result = ['code' => 1, 'msg' => '订单创建成功', 'data' => $order, 'order' => $order['id']];
            } else {
                $result = ['code' => 62017, 'msg' => '订单创建失败'];
            }
        } else {
            $result = ['code' => 62016, 'msg' => $validate];
        }
        return $return ? json($result) : $result;
    }

    /**
     * 待商定
     * 返回配置项
     */
    function finance_setting()
    {
        return json(['code' => 1, 'msg' => '加载成功', 'data' => [
            'finance_setting' => $this->finance_setting,
            'finance_payment' => $this->finance_payment
        ]]);
    }

    /**
     * 生成二维码
     * @param $text
     * @return $this
     */
    function qrcode($text = '')
    {
        $text = urldecode($text);
        include(Env::get('extend_path') . 'Qrcode.php');
        $qrcode = new \QRcode();
        return response($qrcode->png($text, false, QR_ECLEVEL_L, $size = 8, $margin = 2, false))->header(['Content-type' => 'image/png']);
    }

}
