<?php

namespace Option\Lib;

use Dever;

class Cash
{
    private function getInfo($type, $cash)
    {
        if ($type > 3) {
            $cash_type = 2;
        } else {
            $cash_type = 1;
        }
        if ($type == 1 || $type == 4) {
            $table = 'jiaofu';
            $prefix = 'J';
        } elseif ($type == 2 || $type == 5) {
            $table = 'fafang';
            $prefix = 'F';
        } elseif ($type == 3 || $type == 6) {
            $table = 'duifu';
            $prefix = 'D';
            $cash = -1*$cash;
        }

        return array($table, $cash, $cash_type, $prefix);
    }

    public function resetParent($uid, $parent)
    {
        # 获取所有下级
        $child = $this->getChild($uid, false);
        if ($child) {
            foreach ($child as $k => $v) {
                if ($v['level'] > 1) {
                    $this->update(array('id' => $v['id']), array('uid' => $parent));
                }
            }
        }
        return $this->delete(array('to_uid' => $uid, 'level' => 1), array('uid' => $parent));
    }

    public function up($aid, $mid, $type, $cash, $desc, $alert = true)
    {
        if ($cash == 0) {
            return false;
        }
        $account = Dever::db('option/account')->find(array('id' => $aid, 'clear' => true));
        if ($account['status'] <= 2) {
            list($table, $cash, $cash_type, $prefix) = $this->getInfo($type, $cash);
            $where = array();
            $where['clear'] = true;
            $where['aid'] = $aid;
            $where['mid'] = $mid;
            $where['type'] = $cash_type;
            $info = false;
            if (!$info) {
                $data = $where;
                $data['order_num'] = $this->getOrderId($table, $prefix);
                $col = $table;

                $cash_info = Dever::db('option/cash')->find($where);
                if (!$cash_info) {
                    Dever::db('option/cash')->insert($where);
                    $cash_info = Dever::db('option/cash')->find($where);
                }
                if ($table == 'fafang') {
                    $data['yue'] = $cash_info[$col] + $cash;
                    $data['status'] = 1;
                    if ($cash_info['jiaofu'] < $cash) {
                        if ($alert) {
                            Dever::alert('交付期权价值不足发放');
                        } else {
                            return false;
                            $data['status'] = 2;
                        }
                    }
                } elseif ($table == 'duifu') {
                    $data['yue'] = $cash_info[$col] + $cash;
                    $data['status'] = 1;
                    if ($cash_info['fafang'] < $cash) {
                        if ($alert) {
                            Dever::alert('发放期权价值不足兑付');
                        } else {
                            return false;
                            $data['status'] = 2;
                        }
                    }
                } else {
                    $col = 'dai' . $table;
                    $data['status'] = 2;
                }
                
                $data['cash'] = $cash;
                $data['desc'] = $desc;
                $data['clear'] = true;
                $state = Dever::db('option/bill_' . $table)->insert($data);

                if ($state && $cash_info) {
                    # 更新余额
                    $update = array();
                    $update['where_id'] = $cash_info['id'];
                    $update['set_cash'] = $cash;
                    $update['clear'] = true;
                    $method = 'upCash_' . $col;
                    if ($table == 'fafang') {
                        $update['jiaofu'] = $cash;
                        if ($data['status'] == 2) {
                            $update['jiaofu'] = 0;
                        }
                    } elseif ($table == 'duifu') {
                        $update['fafang'] = $cash;
                        if ($data['status'] == 2) {
                            $update['fafang'] = 0;
                        }
                    } else {
                        $update['daijiaofu_date'] = time();
                    }
                    Dever::db('option/cash')->$method($update);
                }
            }
            return $state;
        }

        return false;
    }

    /**
     * 生成订单号
     *
     * @return mixed
     */
    public function getOrderId($table, $prefix)
    {
        $where['order_num'] = Dever::order($prefix);
        $state = Dever::db('option/bill_' . $table)->one($where);
        if (!$state) {
            return $where['order_num'];
        } else {
            return $this->getOrderId($table, $prefix);
        }
    }

    # 获取日志列表
    public function getList($aid, $table, $status, $name, $audit = false)
    {
        $where = array();
        $where['aid'] = $aid;
        if ($status > 0) {
            $where['status'] = $status;
        }
        if ($audit) {
            $where['audit'] = $audit;
        }
        $type = Dever::input('type');
        if ($type) {
            $where['type'] = $type;
        }
        $table = 'option/bill_' . $table;
        if ($status == 2) {
            $data = Dever::db($table)->select($where);
        } else {
            $data = Dever::db($table)->getData($where);
        }
        
        if ($data) {
            $audit = Dever::db($table)->config['config_audit'];
            foreach ($data as $k => $v) {
                $data[$k] = $this->getOne($v, $name, $audit);
            }
        }

        return $data;
    }

    # 获取日志详情
    public function getView($id, $aid, $table, $name)
    {
        if (!$id) {
            Dever::alert('参数错误');
        }
        $where = array();
        $where['id'] = $id;
        $where['aid'] = $aid;
        $table = 'option/bill_' . $table;
        $data = Dever::db($table)->find($where);
        if ($data) {
            $audit = Dever::db($table)->config['config_audit'];
            $data = $this->getOne($data, $name, $audit);
        }

        return $data;
    }

    # 获取详情
    private function getOne($data, $name, $audit)
    {
        if ($data['type'] == 1) {
            $data['type_name'] = '期权' . $name ;
        } else {
            $data['type_name'] = '原始期权' . $name;
        }
        
        $data['audit_name'] = $audit[$data['audit']];
        $data['cdate_string'] = date('Y-m-d H:i', $data['cdate']);
        return $data;
    }

    # 确认期权价值 废弃
    /*
    public function setValue_commit($info)
    {
        $cash = array();
        $state = Dever::db('option/bill_jiaofu')->update(array('status' => 1, 'where_id' => $info['id']));

        if ($state) {
            $account_cash = Dever::db('option/cash')->find(array('type' => $info['type'], 'aid' => $info['aid']));
            if ($account_cash) {
                $update['where_id'] = $account_cash['id'];
                $update['daijiaofu'] = $account_cash['daijiaofu'] - $info['cash'];
                $update['jiaofu'] = $account_cash['jiaofu'] + $info['cash'];
                if ($update['daijiaofu'] < 0) {
                    $update['daijiaofu'] = 0;
                }
                $update['clear'] = true;
                Dever::db('option/cash')->update($update);

                # 获取待发放数据 对之前发放的数据进行发放
                $fafang = Dever::db('option/bill_fafang')->find(array('status' => 2, 'type' => $info['type'], 'aid' => $info['aid']));
                if ($fafang) {
                    foreach ($fafang as $v) {
                        if ($info['cash'] >= $v['cash']) {
                            Dever::db('option/bill_fafang')->update(array('where_id' => $v['id'], 'status' => 1));
                            $info['cash'] -= $v['cash'];
                        }
                    }
                }
            }
        }
    }
    */

    # 确认期权价值
    public function setValue_commit($info)
    {
        $this->setValue_act($info);
    }

    # 确认期权价值
    public function setValue_act($info)
    {
        $account_cash = Dever::db('option/cash')->select(array('aid' => $info['aid']));
        if ($account_cash) {
            foreach ($account_cash as $k => $v) {
                $cash = Dever::db('option/bill_jiaofu')->getTotal(array('where_end' => $info['jiaofu_date'], 'where_type' => $v['type'], 'where_aid' => $v['aid'], 'where_mid' => $v['mid'], 'where_status' => 2));
                if ($cash && $cash['total'] > 0) {
                    $update = array();
                    $update['where_id'] = $v['id'];
                    $update['daijiaofu'] = $v['daijiaofu'] - $cash['total'];
                    $update['jiaofu'] = $v['jiaofu'] + $cash['total'];
                    if ($update['daijiaofu'] < 0) {
                        $update['daijiaofu'] = 0;
                    }
                    $update['clear'] = true;
                    Dever::db('option/cash')->update($update);

                    # 获取待发放数据 对之前发放的数据进行发放
                    $fafang = Dever::db('option/bill_fafang')->find(array('status' => 2, 'type' => $v['type'], 'aid' => $v['aid'], 'mid' => $v['mid']));
                    if ($fafang) {
                        foreach ($fafang as $v1) {
                            if ($cash['total'] >= $v1['cash']) {
                                Dever::db('option/bill_fafang')->update(array('where_id' => $v['id'], 'status' => 1));
                                $cash['total'] -= $v1['cash'];
                            }
                        }
                    }
                    Dever::db('option/bill_jiaofu')->upYes(array('where_end' => $info['jiaofu_date'], 'where_aid' => $v['aid'], 'where_mid' => $v['mid'], 'where_type' => $v['type'], 'where_status' => 2, 'set_agreement_id' => $info['id'], 'set_status' => 1, 'set_qdate' => time()));
                }
            }
        }
    }

    # 展示详情
    public function show()
    {
        $id = Dever::input('id');

        $config = Dever::db('bill/cash')->config['set'];

        $info = Dever::db('bill/cash')->one($id);

        $status = $config['status'][$info['status']];

        $type = $config['type'][$info['type']];

        $member = Dever::db('agent/member')->find($info['mid']);
        $role = Dever::db('setting/role')->one($member['role']);
        $level = Dever::db('setting/level')->one($member['level_id']);

        if ($member['shop_id']) {
            $shop = Dever::db('shop/info')->one($member['shop_id']);
        } else {
            $shop['id'] = -1;
            $shop['name'] = '无';
        }

        $cdate = date('Y-m-d H:i', $info['cdate']);
        if ($info['operdate']) {
            $opertime = date('Y-m-d H:i', $info['operdate']);
        } else {
            $opertime = '';
        }

        $result = array();

        $result['代理商信息'] = array
        (
            'type' => 'info',
            'content' => array
            (
                array
                (
                    array('代理商', $member['name'] . ' ' . $member['mobile']),
                    array('代理角色', $role['name'] . ($level ? '（'.$level['name'].'）' : '')),
                    array('所属店铺', $shop['name']),
                ),

                array
                (
                    array('资金余额', '¥' . $member['cash'] . '元'),
                    //array('直推业绩', '¥' . $member['sell'] . '元'),
                    array('团队业绩', '¥' . $member['group_sell'] . '元'),
                ),
            ),
        );

        $result['交易信息'] = array
        (
            'type' => 'info',
            'content' => array
            (
                array
                (
                    array('流水号', $info['order_num']),
                    array('交易时间', $cdate),
                    array('交易类型', $type),
                ),

                array
                (
                    array('交易金额', '¥' . $info['cash'] . '元'),
                    array('交易后账户余额', '¥' . $info['yue'] . '元'),
                    array('交易说明', $info['desc']),
                ),
            )
        );

        $result['审核信息'] = array
        (
            'type' => 'info',
            'content' => array
            (
                array
                (
                    array('审核时间', $opertime),
                    array('审核状态', $status),
                    array('备注', $info['audit_desc']),
                ),
            )
        );
        
        # 提现信息

        $button = array();
        if ($info['status'] == 1) {
            $button[] = array
            (
                'type' => 'edit',
                'link' => Dever::url('project/database/update?project=bill&table=cash&where_id='.$info['id'].'&col=audit,audit_desc&oper_save_jump=cash&oper_table=cash&oper_parent=cash', 'manage'),
                'name' => '审核',
            );
        }
        if ($info['type'] == 11) {
            $tixian = Dever::db('bill/tixian')->find($info['type_id']);
            if ($tixian) {

                if ($info['status'] == 2 && $tixian['status'] == 1) {
                    $button[] = array
                    (
                        'type' => 'edit',
                        'link' => Dever::url('project/database/update?project=bill&table=tixian&where_id='.$tixian['id'].'&col=audit,audit_desc,pic&oper_save_jump=tixian&oper_table=tixian&oper_parent=tixian', 'manage'),
                        'name' => '发放',
                    );
                }

                $bank = Dever::db('setting/bank')->find($tixian['bank']);
                $result['提现信息'] = array
                (
                    'type' => 'info',
                    'content' => array
                    (
                        array
                        (
                            array('银行名称', $bank['name']),
                            array('开户行', $tixian['bankname']),
                        ),

                        array
                        (
                            array('姓名', $tixian['name']),
                            array('卡号', $tixian['card']),
                        ),
                    )
                );

                if ($tixian['status'] == 2) {
                    if ($tixian['operdate']) {
                        $opertime = date('Y-m-d H:i', $tixian['operdate']);
                    } else {
                        $opertime = '';
                    }
                    $pic = '';
                    if ($tixian['pic']) {
                        $temp = explode(',', $tixian['pic']);
                        foreach ($temp as $k => $v) {
                            $pic .= '<a href="'.Dever::pic($v).'" target="_blank"><img src="'.Dever::pic($v).'" width="150" /></a>';
                        }
                    }
                    $result['发放信息'] = array
                    (
                        'type' => 'info',
                        'content' => array
                        (
                            array
                            (
                                array('发放时间', $opertime),
                                array('备注', $tixian['audit_desc']),
                            ),
                            array
                            (
                                array('凭证', $pic),
                            ),
                        )
                    );
                }
                
            }
        }

        $head = array
        (
            'name' => '基本信息',
            'btn' => $button,
        );
        $html = Dever::show($head, $result);

        return $html;
    }
}