<?php
/**
 * +------------------------------------------------------------
 * | 财务 finance/controller/Admin.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;

class Admin extends Module
{

    /**
     * 数据概览
     */
    public function overview()
    {
        $where = [
            ['type', '=', 1],
            ['status', '=', 1],
            ['payment', 'neq', 4]
        ];
        $count['recharge'] = number_format(model('app\finance\model\Order')->where($where)->where('balance', '=', 1)->sum('money'), 2);
        $count['cost'] = number_format(model('app\finance\model\Order')->where($where)->where('balance', '=', 0)->sum('money'), 2);
        $count['user'] = count(model('app\finance\model\Order')->field('user_id')->where('type', '=', 1)->where('balance', '=', 0)->where('status', '=', 1)->group('user_id')->select());
        //图表
        $recharge = array_column(db('order')->where('balance', 1)->where('status', 1)->where('type', 1)->where("`create_time`>UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 30 DAY))")->group("day")->field("count(*) as count,FROM_UNIXTIME(create_time, '%m-%d') as day")->select(), null, 'day');
        $cost = array_column(db('order')->where('balance', 0)->where('type', 1)->where("`create_time`>UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 30 DAY))")->group("day")->field("count(*) as count,FROM_UNIXTIME(create_time, '%m-%d') as day")->select(), null, 'day');
        for ($i = 30; $i >= 1; $i--) {
            $day = date("m-d", strtotime("-" . $i . " day"));
            $data[] = [
                'day' => $day,
                '充值' => empty($recharge[$day]['count']) ? 0 : $recharge[$day]['count'],
                '消费' => empty($cost[$day]['count']) ? 0 : $cost[$day]['count']
            ];
        }
        $data = [
            'count' => $count,
            'chart' => [
                'fields' => ['充值', '消费'],
                'data' => $data
            ]
        ];
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 财务流水
     */
    public function payment($attr = [], $return = 1)
    {
        $attr = input('param.');
        $attr['page'] = max(1, input('param.page', 0));
        $attr['with'] = 'user';
        $attr['limit'] = isset($attr['limit']) ? $attr['limit'] : 20;
        $attr['type'] = 1;
        $attr['field'] = 'o.id,o.user_id,o.balance,o.money,o.memo,o.status,o.payment,o.type,o.trade_no,l.order_id,l.create_time';
        $attr['join'] = [
            'table' => '__ORDER_LOG__ l',
            'where' => 'l.order_id=o.id'
        ];
        $rs = $this->query($attr);
        return $return ? json(['code' => 1, 'data' => $rs]) : $rs;
    }

    function configs()
    {
        $data = [
            'option' => config('app.option'),
            'payment' => config('app.option')['payment'],
            'status' => config('app.option')['status']
        ];
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 手动入账
     */
    public function add()
    {
        $data = input('post.');
        if (!empty($data['name']) && empty($data['user_id'])) $data['user_id'] = db('user')->where('name', '=', $data['name'])->value('id');
        $result = $this->validate($data, [
            'user_id' => 'require|number|gt:0',
            'balance' => 'require',
            'money' => 'require'
        ], [
            'user_id.require' => '请选择要操作的用户',
            'balance.require' => '操作类型不能为空',
            'money.require' => '金额不能为空',
            'user_id.number' => '未找到用户信息',
            'user_id.gt' => '未找到用户信息'
        ]);
        if ($result !== true) return json(['code' => 0, 'msg' => $result]);
        $user = action('user/api/query', [['id' => $data['user_id']]]);
        if (empty($user)) return json(['code' => 65001, 'msg' => '用户不存在']);
        //系统支付
        $data['payment'] = 4;
        //操作余额
        $data['type'] = 1;
        $result = action('finance/api/money', [$data, 0]);
        if ($result['code'] == 1) {
            $event = '手动入账';
            $memo = ($data['balance'] == 0 ? '减少' : '增加') . '【' . $user['name'] . '】余额¥' . $data['money'];
            action('user/Api/log', [$event, $memo]);
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            return json(['code' => 65002, 'msg' => $result['msg']]);
        }
    }

    /**
     * 交易记录
     */
    public function exchange($attr = [], $return = 1)
    {
        $attr['page'] = max(1, input('param.page', 0));
        $attr['with'] = 'user';
        $attr['limit'] = isset($attr['limit']) ? $attr['limit'] : 20;
        $attr['field'] = 'o.id,o.user_id,o.balance,o.money,o.memo,o.status,o.payment,o.type,o.trade_no,l.order_id,l.create_time';
        $attr['join'] = [
            'table' => '__ORDER_LOG__ l',
            'where' => 'l.order_id=o.id'
        ];
        $rs = $this->query($attr);
        return $return ? json(['code' => 1, 'data' => $rs]) : $rs;
    }

    function delete($id = [], $days = '')
    {
        if (empty($id) && empty($days)) return json(['code' => 65003, 'msg' => '请选择要删除的数据']);
        $where = [];
        if (!empty($id)) {
            $where [] = ['order_id', 'in', (array)$id];
        }
        if (!empty($days)) {
            $where [] = ['create_time', '<', $days * 86400];
        }
        model('app\finance\model\Log')->where($where)->delete();
        if (!empty($attr['days'])) {
            action('user/Api/log', ['清除记录', date('Y-m-d', time() - $days * 86400) . '之前的财务记录']);
        }
        if (!empty($attr['id'])) {
            action('user/Api/log', ['清除记录', '订单号:' . join(',', (array)$id)]);
        }
        return json(['code' => 1, 'msg' => '删除成功']);
    }

    /**
     * 导出excel
     */
    function export()
    {
        $attr = input('param.');
        $attr['with'] = 'user';
        unset($attr['page']);
        $attr['field'] = 'o.id,o.user_id,o.balance,o.money,o.memo,o.status,o.payment,o.type,o.trade_no,l.order_id,l.create_time';
        $attr['join'] = [
            'table' => '__ORDER_LOG__ l',
            'where' => 'l.order_id=o.id'
        ];
        $result = $this->query($attr);
        if (empty($result)) {
            return json(['code' => 65004, 'msg' => '查询记录为空']);
        }
        $option = config('app.option');
        $file_name = date('YmdHis') . '财务明细';
        foreach ($result as $k => $v) {
            $data[$k] = [
                'id' => ' ' . $v['id'],
                'name' => ' ' . $v['user']['name'],
                'type_name' => ' ' . $v['type_name'],
                'balance' => ' ' . $v['balance_name'],
                'amount' => ' ' . $v['money'],
                'status' => ' ' . $option['status'][$v['status']],
                'memo' => ' ' . $v['memo'],
                'payment' => ' ' . $option['payment'][$v['payment']],
                'create_time' => ' ' . $v['create_time'],
            ];
        }
        action('user/Api/log', [
            'event' => '导出明细为Excel',
            'memo' => '查询条件：' . http_build_query(input('param.')),
        ]);
        $this->save_excel($file_name, ['系统订单编号', '用户名', '类型', '收支', '金额', '支付状态', '备注', '支付方式', '支付时间'], $data);
    }

}
