<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-05-07
 *
 *
 */

namespace app\controller\admin\user;


use app\common\model\merchant\order\OrderMerchant;
use app\common\model\system\admin\Admin;
use app\common\model\system\auth\Role;
use app\common\model\user\UserCertification;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\user\UserExtractRepository;
use app\controller\api\merchant\sxy\Access;
use app\controller\api\user\Im;
use crmeb\basic\BaseController;
use app\common\repositories\store\coupon\StoreCouponUserRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\user\UserBillRepository;
use app\common\repositories\user\UserGroupRepository;
use app\common\repositories\user\UserLabelRepository;
use app\common\repositories\user\UserRepository;
use app\common\repositories\wechat\WechatNewsRepository;
use app\common\repositories\wechat\WechatUserRepository;
use app\validate\admin\UserNowMoneyValidate;
use app\validate\admin\UserValidate;
use crmeb\services\SpreadsheetExcelService;
use FormBuilder\Exception\FormBuilderException;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\Log;

/**
 * Class User
 * @package app\controller\admin\user
 * @author xaboy
 * @day 2020-05-07
 */
class User extends BaseController
{
    /**
     * @var UserRepository
     */
    protected $repository;

    /**
     * User constructor.
     * @param App $app
     * @param UserRepository $repository
     */
    public function __construct(App $app, UserRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-07
     */
    public function lst()
    {

        /*
         * 昵称，分组，标签，地址，性别，
         */
        $where = $this->request->params([
            'label_id',
            'user_type',
            'sex',
            'is_promoter',
            'country',
            'pay_count',
            'user_time_type',
            'user_time',
            'nickname',
            'province',
            'city',
            'group_id',
            'identity',
            'now_money',
            'account',
            'user_card',
            'user_rich_type',
            'stockholder',
            'subIdentify',
            'user_group',
            'is_show',
            'zero_line_uid'
        ]);

        [$page, $limit] = $this->getPage();

        return app('json')->success($this->repository->getList($where, $page, $limit));
    }


        /**
     * 协议
     * @return mixed
     */
    public function xieyi(){
        var_dump(111);die;
        return app('json')->success($this->repository->getXieYi());
    }

    /**
     * 批量设置星级
     * @return mixed
     * @throws DbException
     */
    public function start_level(){
        $ids = (array)$this->request->param('ids', []);
        $admin_start_level = $this->request->param('admin_start_level', '0');
        if (!count($ids))
            return app('json')->fail('数据不存在');

        foreach ($ids as $id){
            $rich=Db::name('user_rich')->where('uid',$id)->count();
            if($rich){
                Db::name('user_rich')->where('uid',$id)->update(['admin_start_level'=>$admin_start_level]);
            }else{
                $insert=['uid' => $id, 'admin_start_level' => $admin_start_level];
                Db::name('user_rich')->insert($insert);
            }
        }
        return app('json')->success('修改成功');
    }

    public function spreadList($uid)
    {
        $where = $this->request->params(['level', 'keyword', 'date','identity']);
        [$page, $limit] = $this->getPage();
        return app('json')->success($this->repository->getLevelList($uid, $where, $page, $limit));
    }

    public function spreadOrder($uid)
    {
        $where = $this->request->params(['level', 'keyword', 'date']);
        [$page, $limit] = $this->getPage();
        return app('json')->success($this->repository->subOrder($uid, $page, $limit, $where));
    }

    public function clearSpread($uid)
    {
        $this->repository->update($uid, ['spread_uid' => 0]);
        return app('json')->success('清除成功');
    }

    /**
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-09
     */
    public function updateForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->userForm($id)));
    }
    public function get_info($id)
    {
//                ini_set('display_errors','On');
//
//        error_reporting(E_ALL);
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $user=Db::name('user')->find($id);
        $certification = Db::name('user_certification')->where("uid", $id)->find();
        $user['real_name'] = $certification['user_name'] ?? '';
        $user['card_id'] = $certification['user_card'] ?? '';
        $user_rich=Db::name('user_rich')->where('uid',$id)->find();
        $user['admin_start_level'] =$user_rich?$user_rich['admin_start_level']:'0';
        $user['user_rich_type'] =$user_rich?$user_rich['type']:'0';
        $user['area_manage_pics'] =[];
        $user['area_manage_obtain'] ='0';
        if($user_rich){
            $user['area_manage_obtain'] =$user_rich['obtain'];
            if($user_rich['pics']){
                $user['area_manage_pics']=explode(',',$user_rich['pics']);
            }
        }

        $code_list_province=DB::name('user')->where('user_group',6)->where('manage_address!=""')->column('manage_address');
        $code_list_district=DB::name('user')->where('user_group',5)->where('manage_address!=""')->column('manage_address');
        // 省
        $code_list_province_arr=[];
        foreach ($code_list_province as $v){
            $v_explode=explode(',',$v);
            $code_list_province_arr[$v_explode[0]][]=$v_explode[0];
        }
        //区县
        $code_list_district_arr=[];
        foreach ($code_list_district as $v){
            $v_explode=explode(',',$v);
            $code_list_district_arr[$v_explode[1]][]=$v_explode[0];
        }
        if( $user['manage_address']){
            $code_list_explode=explode(',',$user['manage_address']);
        }

        $regions1 = Db::name('regions') -> field('id as value,name as label')->where('level',1) ->select();
        $regions2 = Db::name('regions') -> field('id as value,name as label,pid')->where('level',2) ->select();
        $regions3 = Db::name('regions') -> field('id as value,name as label,pid')->where('level',3) ->select();
        $regions3_data=[];
        foreach ($regions3 as $v){
            $v['disabled']=false;
            if(isset($code_list_district_arr[$v['pid']]) && in_array($v['value'],$code_list_district_arr[$v['pid']])){
                if(!isset($code_list_explode[2]) || $code_list_explode[2]!=$v['value']){
                    $v['disabled']=true;
                }
            }
            $regions3_data[$v['pid']][]=$v;
        }
        $regions2_data=[];
        foreach ($regions2 as $v){
            $v['children']=isset( $regions3_data[$v['value']])? $regions3_data[$v['value']]:[];
            $regions2_data[$v['pid']][]=$v;
        }
        $city_area=[];
        foreach ($regions1 as $v){
            $v['children']=isset( $regions2_data[$v['value']])? $regions2_data[$v['value']]:[];
            $city_area[]=$v;
        }

        $regions2_data2=[];
        foreach ($regions2 as $v){
            $v['disabled']=false;
            if(isset($code_list_province_arr[$v['pid']]) && in_array($v['value'],$code_list_province_arr[$v['pid']])){
                if(!isset($code_list_explode[0]) || $code_list_explode[0]!=$v['value']){
                    $v['disabled']=true;
                }
            }
            $regions2_data2[$v['pid']][]=$v;
        }
        $city_area_2=[];
        foreach ($regions1 as $v){
            $v['children']=isset( $regions2_data2[$v['value']])? $regions2_data2[$v['value']]:[];
            $city_area_2[]=$v;
        }
        $user['city_area_1']=$city_area;
        $user['city_area_2']=$city_area_2;

        //查询当前团队的用户列表
        $sql = "select getUserSpreadId($id) as uids";
        //\think\facade\Log::info("lplpDB".$sql);
        try{
            $spread_user_list = Db::query($sql);
        }catch (Exception $exception){
           return app('json')->success($exception);
        }


        $spread_user_list = array_diff(explode(",", trim($spread_user_list[0]['uids'],'$,')), [$id]);

        //查询创客手机号
        $marker_phone_list = [];
        $marker_user_list = Db::name("user")->whereIn("uid", $spread_user_list)->where('is_shop_partner', 1)->select()->toArray();
        foreach ($marker_user_list as $k=>$v){
            $marker_phone_list[] = $v['account'];
        }
        $user['marker_phone_list'] = $marker_phone_list;

        $old_user_lianc_data = Db::name("old_user_lianc")->select()->toArray();//将联创等级数据一起发送到前端
        $user['old_user_lianc_data'] = $old_user_lianc_data;


        return app('json')->success($user);
    }

    /**
     * @param $id
     * @param UserValidate $validate
     * @param UserLabelRepository $labelRepository
     * @param UserGroupRepository $groupRepository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020-05-09
     */
    public function update($id, UserValidate $validate, UserLabelRepository $labelRepository, UserGroupRepository $groupRepository)
    {
        $data = $this->request->params(['real_name', 'agent_rebate', "mer_rebate", "promoter_rebate", "cross_store", "jurisdiction", "other_jurisdictions", "xqxiaofei", 'phone', 'birthday', 'card_id', 'addres', 'mark', 'group_id', 'user_group', ['label_id', []], ['is_promoter', 0], ['maker_phone_list', []]]);
        $validate->check($data);
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
//        if ($data['group_id'] && !$groupRepository->exists($data['group_id']))
//            return app('json')->fail('分组不存在');
        $label_id = (array)$data['label_id'];
        $maker_phone_list = (array)$data['maker_phone_list'] ?? [];
        foreach ($label_id as $k => $value) {
            $label_id[$k] = (int)$value;
            if (!$labelRepository->exists((int)$value))
                return app('json')->fail('标签不存在');
        }
        //查询当前团队的用户列表，判断当前用户是否为团队成员
        $sql = "select getUserSpreadId($id) as uids";
        $spread_user_list = Db::query($sql);
        $spread_user_list = trim($spread_user_list[0]['uids'],'$,');

        $error_maker_phone = [
            'no_registry' => [],
            'no_team' => [],
        ];
        foreach ($maker_phone_list as $k => $maker_phone) {
            //检查手机号是否已注册
            $user = Db::name('user')->where('account', $maker_phone)->find();
            if (empty($user)) {
                $error_maker_phone['not_sign'][] = $maker_phone;
            }
            if (!in_array($user['uid'], explode(",", $spread_user_list))) {
                $error_maker_phone['no_team'][] = $maker_phone;
            }
        }
        if (count($error_maker_phone['no_registry']) > 0 || count($error_maker_phone['no_team']) > 0) {
            return app('json')->fail("创客手机号校验异常", [
                'error_maker_phone' => $error_maker_phone,
            ]);
        } else {
            foreach ($maker_phone_list as $k => $maker_phone) {
                Db::name('user')
                    ->where('account', $maker_phone)
                    ->update([
                        'is_shop_partner' => 1,
                    ]);
            }
        }
        unset($data['maker_phone_list']);
        $data['label_id'] = implode(',', $label_id);

        if(!$data['birthday']) unset($data['birthday']);


        $user_group=input('post.user_group','');
        if(in_array($user_group,[5,6])){

            $city_list=input('post.city',[]);
            $city_string = implode(",", $city_list);
            if(!$city_list){
                return app('json')->fail('请选择代理区域');
            }
            $code_list_count=Db::name('user')->where('manage_address', $city_string)->where('uid !='.$id)->count();
            if($code_list_count){
                return app('json')->fail('改区域已经分配给其他人了');
            }
            $data['manage_address']=$city_string;
            $data['up_agency_time']=date('Y-m-d H:i:s');
        }else{
            $data['up_agency_time']=null;
        }
        if ($user_group == 3) {
            $mer = Db::name('merchant')->where('uid', $id)->find();
            if ($mer)
                return app('json')->fail('已经是创客，不可调整成大V经理身份');
            $data['up_vip_time'] = date('Y-m-d H:i:s');
        } else {
            $data['up_vip_time'] = null;
        }
        if ($user_group == 4) {
            $new_user_group = Db::name('user')->where('uid', $id)->value('user_group');
            if ($new_user_group == 3)
                return app('json')->fail('已经是大V经理，不可调整成创客身份');
            $data['up_vip_time'] = date('Y-m-d H:i:s');
        } else {
            $data['up_vip_time'] = null;
        }

        $this->repository->update($id, $data);

        $originatorIdOld = request()->post('originator_id_old','');//接收originator_id_old数据,并更新到数据库里
        if ($originatorIdOld === '') {
            $originatorIdOld = null;
        }
        Db::name('user')->where('uid', $id)->update(['originator_id_old' => $originatorIdOld]);

        //更新身份证信息
        $cardData = [];
        if ($data['card_id']) {
            $cardData['user_card'] = $data['card_id'];
        }
        if ($data['real_name']) {
            $cardData['user_name'] = $data['real_name'];
        }

        if (!empty($cardData)) {
            Db::name('user_certification')->where("uid", $id)->update($cardData);
        }
//        $admin_start_level=input('post.admin_start_level',0);
//        if (!empty($admin_start_level)) {

//        }
        $pics=input('post.area_manage_pics',[]);
        $user_rich_ypdate['type']=input('post.user_rich_type',0);
        $user_rich_ypdate['obtain']=input('post.area_manage_obtain',0);
        $user_rich_ypdate['admin_start_level']=input('post.admin_start_level',0);
        if($pics){
            $user_rich_ypdate['pics']=implode(',',$pics);
        }
        $rich=Db::name('user_rich')->where('uid',$id)->count();
        if($rich){
            Db::name('user_rich')->where('uid',$id)->update($user_rich_ypdate);
        }else{
            $user_rich_ypdate['uid']=$id;
            Db::name('user_rich')->insert($user_rich_ypdate);
        }

        $user = Db::name('user')->where('uid', $id)->find();
        if (isset($user['originator_id_old']) && is_null($user['originator_id_old'])) {
            $user['originator_id_old'] = '';
        }
        return app('json')->success('编辑成功',$user);
    }

    public function maker_check_phone($id)
    {
        $params = $this->request->params(['phone']);
        $user = Db::name('user')->where('account', $params['phone'])->find();
        if (empty($user)) {
            return app('json')->fail('该用户未注册，请先邀请用户注册~');
        }
        //查询当前团队的用户列表，判断当前用户是否为团队成员
        $sql = "select getUserSpreadId($id) as uids";
        $spread_user_list = Db::query($sql);
        $spread_user_list = trim($spread_user_list[0]['uids'],'$,');
        if (!in_array($user['uid'], explode(",", $spread_user_list))) {
            return app('json')->fail('该用户不属于您团队，不可设置为合伙人~');
        }
        return app('json')->success();
    }

    /**
     * 设为合伙人
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setAreaManage()
    {
        $area_type = $this->request->param('area_type', 0);//类型  district town village
        $area_manage_address_ids = $this->request->param('area_manage_address_ids', 0);//
        $uid = $this->request->param('uid', 0);//用户id

//        $area_manage = Db::name('area_manage')->where('code_list', $area_manage_address_ids)->find();
//        if ($area_manage) {
//            return app('json')->fail('该地区已有代理！');
//        }
//        $area_manage = Db::name('area_manage')->where('uid', $uid)->find();
//        if ($area_manage) {
//            return app('json')->fail('该用户已经是代理了！');
//        }
        $area_manage_address_list = explode(',', $area_manage_address_ids);
        switch ($area_type) {
            case 'district':
                if (count($area_manage_address_list) != 3)
                    return app('json')->fail('请输入正确的高级合伙人代理地址！');
                break;
            case 'town':
                if (count($area_manage_address_list) != 4)
                    return app('json')->fail('请输入正确的中级合伙人代理地址！');
                break;
            case 'village':
                if (count($area_manage_address_list) != 3)
                    return app('json')->fail('请输入正确的初级合伙人代理地址！');
                break;
            default :
                return app('json')->fail('请输入正确的初级合伙人代理地址！');
        }
        $end_address = Db::name('regions_new')->where('id', end($area_manage_address_list))->find();
        if (empty($end_address))
            return app('json')->fail('该地址不存在！');

        // 查询当时是否已有未支付的合伙人商品订单
        $hehuo_store_group_order = DB::name('store_order')
            ->alias('store_order')
            ->leftJoin('store_order_product store_order_product', 'store_order.order_id=store_order_product.order_id')
            ->where('store_order.uid', $uid)
            ->where('store_order.paid', 0)
            ->where('store_order_product.type', 'in', [11, 12, 13])
            ->find();
        if($hehuo_store_group_order)
            return app('json')->fail('该用户当前有待支付的合伙人商品，不可下单！');


        $key = 'area_manage_order:' . $area_manage_address_ids;
        $redis = Cache::store('redis')->handler();
        if (!$redis->setnx($key, 1))
            return app('json')->fail('该地区已有用户锁定，请稍后再试！');

        // 区域设置成功 记录
        Db::name('area_manage')->insert([
            'uid'         => $uid,
            'type'        => $area_type,
            'order_sn'    => '',
            'code_list'   => $area_manage_address_ids,
            'create_time' => date('Y-m-d H:i:s')
        ]);
        Db::name('log')->insert(['data' => "后台修改{$uid}为{$area_type}区域成功，code_list:{$area_manage_address_ids}！"]);

        return app('json')->success('修改成功');
    }

    /**
     * 设为回填
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setHuiTian()
    {
        $uid = $this->request->param('uid', 0);//用户id

        $user_rich = Db::name('user_rich')->where('uid', $uid)->find();
        if ($user_rich) {
            if ($user_rich['is_huitian'] == 1)
                return app('json')->fail('该用户已经是回填！');
            if ($user_rich['type'] != 0)
                return app('json')->fail('只有普通用户可以设置为回填！');

            Db::name('user_rich')->where('uid', $uid)->update([
                'type'          => 4,
                'is_huitian'    => 1,
            ]);
        } else {
            Db::name('user_rich')->where('uid', $uid)->insert([
                'uid'           => $uid,
                'type'          => 4,
                'is_huitian'    => 1,
            ]);
        }
        Db::name('log')->insert(['data' => "后台修改{$uid}为回填成功！"]);

        return app('json')->success('修改成功');
    }

    /**
     * @param $id
     * @param UserLabelRepository $labelRepository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020-05-08
     */
    public function changeLabel($id, UserLabelRepository $labelRepository)
    {
        $label_id = (array)$this->request->param('label_id', []);
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        foreach ($label_id as $k => $value) {
            $label_id[$k] = (int)$value;
            if (!$labelRepository->exists((int)$value))
                return app('json')->fail('标签不存在');
        }
        $label_id = implode(',', $label_id);
        $this->repository->update($id, compact('label_id'));
        return app('json')->success('修改成功');
    }

    /**
     * @param UserLabelRepository $labelRepository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020-05-08
     */
    public function batchChangeLabel(UserLabelRepository $labelRepository)
    {
        $label_id = (array)$this->request->param('label_id', []);
        $ids = (array)$this->request->param('ids', []);
        if (!count($ids))
            return app('json')->fail('数据不存在');
        foreach ($label_id as $k => $value) {
            $label_id[$k] = (int)$value;
            if (!$labelRepository->exists((int)$value))
                return app('json')->fail('标签不存在');
        }
        $this->repository->batchChangeLabelId($ids, $label_id);
        return app('json')->success('修改成功');
    }


    /**
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-08
     */
    public function changeLabelForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changeLabelForm($id)));
    }
    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-08
     */
    public function batchChangeLabelForm()
    {
        $ids = $this->request->param('ids', '');
        $ids = array_filter(explode(',', $ids));
        if (!count($ids))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changeLabelForm($ids)));
    }

    /**
     * 批量微信入账公证处
     * @return mixed
     * @author php迷途小书童
     * @created 2021/3/10 15:37
     */
    public function batchGzc()
    {
        $ids = $this->request->param('ids', '');
        $type = $this->request->param('type', '');
        $ids = array_filter(explode(',', $ids));
        if (!count($ids))
            return app('json')->fail('数据不存在');
        $OrderMerchantRepository = app()->make(OrderMerchantRepository::class);
        foreach ($ids as $id) {
            $user = $this->repository->get($id);
            switch ($type) {
                case 'WX':
                    if (!$user->wechat_user_id)
                        return app('json')->fail('账号：'.$user->account.'暂未微信授权，操作停止');
                    $pay_user_id = $user->wechat_user_id;
                    break;
                case 'ALI':
                    if (!$user->ali_user_id)
                        return app('json')->fail('账号：'.$user->account.'暂未支付宝授权，操作停止');
                    $pay_user_id = $user->ali_user_id;
                    break;
                default:
                    return app('json')->fail('请求参数错误');
                    break;
            }
            $count = OrderMerchant::getDB()
                ->where('pay_user_id', $pay_user_id)
                ->where('paid', 1)
                ->where('gzc', 0)
            ->count();
            if (!$count)
                return app('json')->fail('账号：'.$user->account.'暂无要发起的入账信息，操作停止');
            $certification = UserCertification::getDB()
                ->where('uid', $user->uid)
                ->find();
            if (!$certification)
                return app('json')->fail('账号：'.$user->account.'暂未实名认证，操作停止');
            $OrderMerchantRepository->batchGzc($certification,$user,$type);
        }
        return app('json')->success('发起成功');
    }
    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-08
     */
    public function batchChangeGroupForm()
    {
        $ids = $this->request->param('ids', '');
        $ids = array_filter(explode(',', $ids));
        if (!count($ids))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changeGroupForm($ids)));
    }

    /**
     * @param $id
     * @param UserGroupRepository $groupRepository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeGroup($id, UserGroupRepository $groupRepository)
    {
        $group_id = (int)$this->request->param('group_id', 0);
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        if ($group_id && !$groupRepository->exists($group_id))
            return app('json')->fail('分组不存在');
        $this->repository->update($id, compact('group_id'));
        return app('json')->success('修改成功');
    }

    /**
     * @param UserGroupRepository $groupRepository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020-05-07
     */
    public function batchChangeGroup(UserGroupRepository $groupRepository)
    {
        $group_id = (int)$this->request->param('group_id', 0);
        $ids = (array)$this->request->param('ids', []);
        if (!count($ids))
            return app('json')->fail('数据不存在');
        if ($group_id && !$groupRepository->exists($group_id))
            return app('json')->fail('分组不存在');
        $this->repository->batchChangeGroupId($ids, $group_id);
        return app('json')->success('修改成功');
    }

    /**
     * @param $id
     * @return mixed
     * @throws FormBuilderException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeGroupForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changeGroupForm($id)));
    }

    /**
     * @param $id
     * @return mixed
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeNowMoneyForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changeNowMoneyForm($id)));
    }

    /**
     * @param $id
     * @param UserNowMoneyValidate $validate
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeNowMoney($id, UserNowMoneyValidate $validate)
    {
        $data = $this->request->params(['now_money', 'type']);
        $validate->check($data);
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $this->repository->changeNowMoney($id, $this->request->adminId(), $data['type'], $data['now_money']);

        return app('json')->success('修改成功');
    }


    /**
     * @param $id
     * @return mixed
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeProForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $formData = formToData($this->repository->changeProForm($id));
        return app('json')->success($formData);
    }


    /*
     * 更改用户推荐信息
     * cabbage
     * 2020-11-04
     * */
    public  function  changePro($id,UserRepository $repository)
    {
        $spread_account = $this->request->param('spread_account');
        $adminId = $this->request->adminId();
        $adminInfo = $this->request->adminInfo();
        $operation = $adminInfo['account'].'修改用户推荐人';
        $mark = $this->request->param('mark');
        if (!empty($mark)) {
            $mark = "($mark)";
        }
        $mark = $operation.$mark;
        $olld_id = Db::name('user')->where('uid', $id)->value('spread_uid')??0;
        $spread = Db::name("user")->where('account',$spread_account)->field("uid")->find();
        if(!$spread){
            return app('json')->fail("推荐人信息不存在");
        }
        if($repository->update_spread($id,$spread_account,$mark,$olld_id,$adminId,$spread)){
            return app('json')->success("修改成功");
        }else{
            return app('json')->fail("失败");
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeProLevelForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $formData = formToData($this->repository->changeProFormLevel($id));
        return app('json')->success($formData);
    }




    /*
     * 更改用户节点人信息
     * cabbage
     * 2020-11-04 哈基米哦南北绿豆
     * */
    public function changeProLevel($id,UserRepository $repository) {
        $level_account = $this->request->param('level_account');
        $olld_id = Db::name('user')->where('uid', $id)->value('level_id')??0;
        $adminId = $this->request->adminId();
        $adminInfo = $this->request->adminInfo();
        $operation = $adminInfo['account'].'修改用户节点人';
        $mark = $this->request->param('mark');
        if (!empty($mark)) {
            $mark = "($mark)";
        }
        $mark = $operation.$mark;
        $level = Db::name("user")->where('account',$level_account)->field("uid,account")->find();
        if(!$level){
            return app('json')->fail("节点人信息不存在");
        }
        if (!$id) {
            return app('json')->fail("参数丢失");
        }
        if($repository->update_level_uid($id,$olld_id,$level_account,$mark,$adminId,$level)){
            return app('json')->success("修改成功");
        }else{
            return app('json')->fail("失败"); }
    }

    /**
     * 更改用户身份
     */
    public function changeProGroupFrom($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $formData = formToData($this->repository->changeProFormGroup($id));
        return app('json')->success($formData);
    }
    public function changeProGroup($id,UserRepository $repository)
    {
        $old_identity_id = $this->request->param('old_identity_id');
        $new_identity_id = $this->request->param('new_identity_id');
        $adminId = $this->request->adminId();
        $adminInfo = $this->request->adminInfo();
        $operation = $adminInfo['account'].'修改用户身份';
        $mark = $this->request->param('mark');
        if (!empty($mark)) {
            $mark = "($mark)";
        }
        $mark = $operation.$mark;
        if (empty($id) || empty($old_identity_id) || empty($new_identity_id)) {
            return app('json')->fail("参数丢失");
        }
        if ($repository->update_user_group($id, $old_identity_id, $new_identity_id, $adminId, $mark)) {
            return app('json')->success("修改成功");
        } else {
            return app('json')->fail("失败");
        }
    }

    /**
     * 修改用户奖励表单
     * @param $id
     * @return mixed
     * @throws FormBuilderException
     */
    public function changeAwardForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changeAwardForm($id)));
    }


    /**
     * 修改用户奖励
     * @param $id
     * @param UserRepository $repository
     * @return mixed
     */
    public  function  changeAward($id,UserRepository $repository)
    {
        $type = $this->request->param('type');
        $award_type = $this->request->param('award_type');
        $num = $this->request->param('num');
        $mark = $this->request->param('mark','');
        $admin_id = $this->request->param('admin_id');
        if (!$id || !$award_type || !$num){
            return app('json')->fail('参数丢失');
        }
        if($repository->changeAward($id,$type,$award_type,$num,$mark,$admin_id)){
            return app('json')->success("修改成功");
        }else{
            return app('json')->fail("失败");
        }
    }
    /**
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-08
     */
    public function changePassForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->changePassForm($id)));
    }
    /*
     * 更改用户密码
     * cabbage
     * 2021-2-23
     * */
    public  function  changePass($id,UserRepository $repository)
    {
        $pass_word = $this->request->param('pass_word');
        if (!$pass_word || !$id){
            return app('json')->fail('参数丢失');
        }
        if($repository->changePass($id,$pass_word)){
            return app('json')->success("修改成功");
        }else{
            return app('json')->fail("失败");
        }
    }
    /**
     * @param WechatNewsRepository $wechatNewsRepository
     * @param WechatUserRepository $wechatUserRepository
     * @return mixed
     * @author xaboy
     * @day 2020-05-11
     */
    public function sendNews(WechatNewsRepository $wechatNewsRepository, WechatUserRepository $wechatUserRepository)
    {
        $ids = array_filter(array_unique(explode(',', $this->request->param('ids'))));
        $news_id = (int)$this->request->param('news_id', 0);
        if (!$news_id)
            return app('json')->fail('请选择图文消息');
        if (!$wechatNewsRepository->exists($news_id))
            return app('json')->fail('数据不存在');
        if (!count($ids))
            return app('json')->fail('请选择微信用户');
        $wechatUserRepository->sendNews($news_id, $ids);
        return app('json')->success('发送成功');
    }

//    public function promoterList()
//    {
//        $where = $this->request->params(['keyword', 'user_type', 'status', 'sex', 'group_id']);
////        $where['is_promoter'] = 1;
//        [$page, $limit] = $this->getPage();
//        return app('json')->success($this->repository->getList($where, $page, $limit));
//    }
    public function promoterList()
    {
        $where = $this->request->params(['keyword']);
//        $where['is_promoter'] = 1;
        [$page, $limit] = $this->getPage();
        return app('json')->success($this->repository->getAgent($where, $page, $limit));
    }


    public function promoterAgent()
    {
        $where = $this->request->params(['keyword', 'identity']);
//        $where['is_promoter'] = 1;
        [$page, $limit] = $this->getPage();
        return app('json')->success($this->repository->getAgentList($where, $page, $limit));
    }

    public function getPromoter($id)
    {
//        $where = $this->request->params(['id']);
        $where['id'] =$id;
//        [$page, $limit] = $this->getPage();s
        return app('json')->success($this->repository->getonePromoter($where));
    }
    public function updateAgent($id)
    {
        $where = $this->request->params(["status"]);
        $res = $this->repository->updateAgent($where,$id);
        if($res['code'] == 400){

            return app('json')->fail($res['msg']);
        }
        return app('json')->success("审核成功");
    }


    /*线下支付*/
    public function  xianPay($id){
        $mark = input("mark");
        $res = $this->repository->xianPayAgent($id,$mark);
        if($res['code'] == 400){
            return app('json')->fail($res['msg']);
        }
        return app('json')->success("线下支付成功");
    }

    public function detail($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $data = $this->repository->userOrderDetail($id);
        $data['enterprise_user'] = null;
        $where=["uid"=>$id,"type"=>"commission","commission_type"=>5];
        $ylj=Db::name("user_bill")->where($where)->whereIn('status',[0,1])->sum('number');
        $data['ylj']=$ylj?$ylj:0;
        $revenue = Db::name("user_bill")
            ->where(["uid" => $id, "type" => "commission"])
            ->whereNotIn('commission_type', [0, 5, 7, 17, 19])
            ->whereIn('status', [1])
            ->sum('number');
        $data['revenue']=$revenue?$revenue:0;
        return app('json')->success($data);
    }

    public function order($id, StoreOrderRepository $repository)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        [$page, $limit] = $this->getPage();
        return app('json')->success($repository->userList($id, $page, $limit));
    }

    public function coupon($id, StoreCouponUserRepository $repository)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        [$page, $limit] = $this->getPage();
        return app('json')->success($repository->userList($id, $page, $limit));
    }

    public function bill($id, UserBillRepository $repository)
    {
        if (!$this->repository->exists(intval($id)))
            return app('json')->fail('数据不存在');
        [$page, $limit] = $this->getPage();
        return app('json')->success($repository->userList([
            'now_money' => 0,
            'status' => 1
        ], $id, $page, $limit));
    }

    /**
     * @return mixed
     * @author xaboy
     * @day 2020/6/22
     */
    public function new_bill($id, UserBillRepository $billRepository)
    {
        [$page, $limit] = $this->getPage();
        $where = [
//            'now_money' => $this->request->param('type', 0),
            'status' => $this->request->param('status'),
//            'mer_id' => $this->request->merId()
            'not_commission_type' => [0, 5, 7, 17, 19],
        ];
        if ($this->request->param('is_red') == true) {
            $where['is_red_brokerage'] = 1;
        }
        $bill_list = $billRepository->userList($where, $id, $page, $limit);

        foreach ($bill_list['list'] as $key => $item) {
            if ($item['status'] == 1) $bill_list['list'][$key]['jiesuan_string'] = "已结算";
            if ($item['status'] == 0) $bill_list['list'][$key]['jiesuan_string'] = "未结算";
            if ($item['status'] == -1) $bill_list['list'][$key]['jiesuan_string'] = "已失效";
        }

        return app('json')->success($bill_list);
    }

    /*
     * 用户养老金信息
     * @author cabbage
     * @date 2020-11-03
     * */
    public function annuity($id, UserRepository $repository)
    {
        if (!$this->repository->exists(intval($id)))
            return app('json')->fail('数据不存在');
        return app('json')->success($repository->get_yanglao($id));
    }

    /**
     * 养老金明细
     */
    public function annuitylog($id, UserRepository $repository){

        [$page, $limit] = $this->getPage();
        $where=["uid"=>$id,"type"=>"commission","commission_type"=>5];
        $res = $repository->yanglaolog($where,$page,$limit);
        return app('json')->success($res);

    }

    /*用户银行卡信息*/
    public function getAccount($id){

        $where['user_id']=$id;
        $data = app()->make(UserExtractRepository::class)->list($where);
        return app('json')->success($data);

    }

    /*设置用户身份*/
    /*
     * pay:1-付费。2-未付费
     * type:3-银卡。4-金卡。5-商户。6-渠道商
     * */
    public function setIdentity(){
        $data = $this->request->params(["uid","pay","type","dc_id","recommend_phone"]);
        $dc_id = $data['dc_id'];
        if(empty($data['uid'])){
            return app('json')->fail('参数错误');
        }
        $time = date('Y-m-d', time());
        $time = strtotime($time);
        $end_time = $time + 31536000 - 1;
        $recommend = Db::name('user') -> where('account',$data['recommend_phone']) -> value('uid');
        $storeOrderRepository = app()->make(StoreOrderRepository::class);
        $access = new Access();
        //付费
        if($data['pay'] == 1){
            switch ($data['type']){
                case 3:
                case 4:
                    if($data['type'] == 3){
                        $order['pay_price'] = '399';
                    }else{
                        $order['pay_price'] = '999';
                    }
                    $order['uid'] = $data['uid'];
                    $order['order_id'] = 0;
                    $order['order_sn'] = 'sIO'.$storeOrderRepository->getNewOrderId();
                    $order['mer_id'] = 0;
                    $order['dacang_id'] = $dc_id;
                    if($data['type'] == 3){
                        $storeOrderRepository -> dacang_yin($order,0);
                    }elseif($data['type'] == 4){
                        $storeOrderRepository -> dacang($order,0);
                    }
                break;
                case 5:
                    //赠送商户
                    $merchant=Db::name('merchant')->where('uid',$data['uid'])->find();
                    if(!$merchant)
                        Db::name('merchant_intention')->insert(['uid'=>$data['uid'],'status'=>3,'activation_code'=>rand('000000000','999999999')]);
                    $mer = Db::name('user_mer') -> where('uid',$data['uid']) -> find();
                    if(!$mer){
                        Db::name('user_mer') -> insert(['uid'=>$data['uid'],'mer'=>2]);
                    }else{
                        Db::name('user_mer') -> where('uid',$data['uid'])->inc('mer', 2) ->update();
                    }
                    $order_sn = 'sIM'.$storeOrderRepository->getNewOrderId();
                    $insertData=[
                        'mer_id'=>0,
                        'pay_price'=>systemConfig("annual"),
                        'status'=>1,
                        'order_no'=>$order_sn,
                        'uid'=>$data['uid']
                    ];
                    $id = Db::name('merchant_annual_cost_order')->insertGetId($insertData);
                    $access->nianfei_yj($id);
                break;
                case 6:
                    //赠送返本商户
                    $mer = Db::name('user_mer') -> where('uid',$data['uid']) -> find();
                    if(!$mer){
                        Db::name('user_mer') -> insert(['uid'=>$data['uid'],'mer'=>10]);
                    }else{
                        Db::name('user_mer') -> where('uid',$data['uid'])->inc('mer', 10) ->update();;
                    }
                    //赠送商户
                    $merchant=Db::name('merchant')->where('uid',$data['uid'])->find();
                    if(!$merchant)
                        Db::name('merchant_intention')->insert(['uid'=>$data['uid'],'activation_code'=>rand('000000000','999999999')]);
                    //赠送大仓会员资格
                    $dacang_user = Db::name('da_cang_user')->where('uid', $data['uid'])->find();
                    $dc_id = 1;
                    //如果不是金卡会员,赠送金卡会员一年
                    if (!$dacang_user) {
                        Db::name('da_cang_user')->insert(['uid' => $data['uid'], 'ctime' => time(), 'end_time' => $end_time, 'dc_id' => $dc_id,'status'=>1,'type'=>1]);
                    }else{
                        //如果是银卡会员,变成金卡，一年 || 是否已过期,如果已过期,赠送金卡会员一年
                        if($dacang_user['type'] == 2 || $dacang_user['end_time'] < $time){
                            Db::name('da_cang_user')->where('uid', $data['uid'])->where('dc_id', $dc_id)->update(['end_time' => $end_time,'status'=>1,'type'=>1]);
                        }
                    }
                    $order_sn = 'sIC'.$storeOrderRepository->getNewOrderId();
                    $insertData=[
                        'pay_price'=>systemConfig("channel_price"),
                        'status'=>1,
                        'order_no'=>$order_sn,
                        'uid'=>$data['uid']
                    ];
                    Db::name('channel_order')->insertGetId($insertData);
                    //渠道商
                    $channel_user=Db::name('channel_user')->where('uid',$data['uid']) -> find();
                    if($channel_user){
                        Db::name('channel_user')->where('uid',$data['uid'])->update(['status'=>1]);
                    }else{
                        Db::name('channel_user')->insert(['uid'=>$data['uid'],'status'=>1,'ctime'=>time(),'recommend_uid'=>$recommend]);
                    }
                    $access->channel_fenyong($order_sn);
                break;
            }
            return app('json')->success('付费身份设置成功');
        }else{
            //未付费
            switch ($data['type']){
                case 3:
                case 4:
                    $dacang_user = Db::name('da_cang_user')->where('uid', $data['uid'])->find();
                    $type = $data['type'] == 3 ? 2 : 1;
                    //如果原来有大仓会员。修改
                    if ($dacang_user) {
                        Db::name('da_cang_user')->where('uid', $data['uid'])->where('dc_id', $dc_id)->update(['end_time' => $end_time,'status'=>1,'type'=>$type]);
                    } else {
                        //新会员
                        Db::name('da_cang_user')->insert(['uid' => $data['uid'], 'ctime' => time(), 'end_time' => $end_time, 'dc_id' => $dc_id,'status'=>1,'type'=>$type]);
                    }
                    break;
                case 5:
                    //赠送商户
                    $merchant=Db::name('merchant')->where('uid',$data['uid'])->find();
                    if(!$merchant)
                        Db::name('merchant_intention')->insert(['uid'=>$data['uid'],'status'=>3,'activation_code'=>rand('000000000','999999999')]);
                    break;
                case 6:
                    //渠道商
                    $channel_user=Db::name('channel_user')->where('uid',$data['uid']) -> find();
                    if($channel_user){
                        Db::name('channel_user')->where('uid',$data['uid'])->update(['status'=>1]);
                    }else{
                        Db::name('channel_user')->insert(['uid'=>$data['uid'],'status'=>1,'ctime'=>time(),'recommend_uid'=>$recommend]);
                    }
            }
            return app('json')->success('未付费身份设置成功');
        }

    }

    public function gongfu_user(){

        $data = $this->request->params(["uid","red","type"]);
        if(empty($data['uid']) || empty($data['type'])){
            return app('json')->fail('参数错误');
        }
        $type = $data['type'];
        $red = $data['red'];
        $uid = $data['uid'];

        $check = Db::name('user_rich')->where('uid',$uid)->find();

        if($check){
            $update['type'] = $type;
            Db::name('user_rich')->where('uid',$uid)->update($update);
        }else{
            Db::name('user_rich')->insert(['uid' => $uid, 'type' => $type]);
        }

        if ($red > 0){
            Db::name('user_rich')->where('uid',$uid)->inc('red', $red)->update();
            Db::name('user_rich_log')->insert([
                'uid' => $uid,
                'red' => $red,
                'pm' => 1,
                'time' => time(),
                'order_id' => 0,
                'mark' => '系统赠送红积分'
            ]);
        }
        return app('json')->success('身份设置成功');
    }

    public function bangfu(){
        $data = $this->request->params(["uid"]);
        if(empty($data['uid'])){
            return app('json')->fail('参数错误');
        }
        $uid = $data['uid'];
        $check = Db::name('user_bangfu') -> where('uid', $uid) -> find();
        if (!$check){
            Db::name('user_bangfu')->insert([
                'uid' => $uid,
                'time' => time(),
                'status' => 1
            ]);
        }
        return app('json')->success('身份设置成功');
    }

    public function bangfu_list(){
        [$page, $limit] = $this->getPage();
        $list = Db::name('user_bangfu')
            -> alias('ub')
            -> join('user u', 'u.uid = ub.uid')
            -> leftJoin('user_rich ur', 'ub.uid = ur.uid')
            -> field('u.nickname,u.account,ub.status,ur.type,ub.id as uid')
            -> page($page, $limit)
            -> select();
        return app('json')->success($list);
    }

    public function bangfu_examine(){
        $data = $this->request->params(["uid","status"]);
        if(empty($data['uid'])){
            return app('json')->fail('参数错误');
        }
        $uid = $data['uid'];
        $check = Db::name('user_bangfu') -> where('id', $uid) -> find();
        if (!$check){
            return app('json')->fail('不存在');
        }
        $save = Db::name('user_bangfu') -> where('uid', $uid) -> update(['status'=>$data['status']]);
        if ($save){
            return app('json')->success('修改成功');
        }
        return app('json')->fail('出错');
    }

    public function importExcel()
    {
        $file = request()->file('file');
        if(!$file){
            return app('json')->fail('请上传文件');
        }
        $extension = pathinfo($file->getOriginalName(), PATHINFO_EXTENSION);
        if ($extension != 'xlsx' && $extension != 'xls') {
            return app('json')->fail('请上传xlx或xlsx文件');
        }

        // 创建一个新的Excel读取器对象
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load($file);
        // 选择活动工作表
        $objPHPExcel->setActiveSheetIndex(0);
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
        // 循环遍历行和列
        $yonghu=[];
        foreach ($sheetData as $k=>$row) {
            if($k==1){
                continue;
            }
            if($row['A'] && $row['A']!=NULL && $row['A']!=''){
                $yonghu[]=array('a'=>$row['A'],'b'=>$row['B']);
            }
        }
        if(count($yonghu)<1){
            return app('json')->fail('未获取到数据');
        }

        $repository = app()->make(UserRepository::class);
        foreach ($yonghu as $k=>$v){
            $user = $repository->accountByUser($v['a']);
            if ($user){
//                return app('json')->fail('手机号已存在');
                $yonghu[$k]['user'] = $user;
            }else{
                $yonghu[$k]['user'] = $repository->registr($v['a'],'A123456','APP',0);
            }
        }
        foreach ($yonghu as $v){
            $user=$v['user'];
            $spread_uid=$v['user']['spread_uid'];
            if($v['b'] && $v['b']!=null && $v['b']!=''){
                $pid=Db::name('user')->where('account',$v['b'])->value('uid');
                if($pid){
                    $repository->bindSpread($user, intval($pid));
                    $spread_uid=$pid;
                }
            }
            $mer_count=Db::name('merchant')->where('uid',$user['uid'])->count();
            if(!$mer_count){
//                $code_insert['uid']=$v['uid'];
//                $code_insert['code']=time().'_'.$this->generateRandomCode(20);
//                $code_insert['ctime']=time();
//                $code_insert['type']=2;
//                $re=Db::name('activation_code')->insertGetId($code_insert);
                $mer_insert['uid']=$user['uid'];
                $mer_insert['spread_uid']=$spread_uid;
                $mer_id=Db::name('merchant')->insertGetId($mer_insert);
                $merchant_admin_insert['mer_id']=$mer_id;
                $merchant_admin_insert['uid']=  $user['uid'];
                $merchant_admin_insert['account']=  $user['account'];
                $merchant_admin_insert['real_name']=  $user['account'];
                $merchant_admin_insert['phone']=  $user['account'];
                $merchant_admin_insert['level']=  0;
                $re=Db::name('merchant_admin')->insertGetId($merchant_admin_insert);

                $merchant_intention['mer_id']=$mer_id;
                $merchant_intention['uid']=  $user['uid'];
                $merchant_intention['phone']=   $user['account'];
                Db::name('merchant_intention')->insertGetId($merchant_intention);

//                insert into rrx_merchant_admin(mer_id,uid,account,pwd,phone,real_name,level) values (#{mer_id},#{uid},#{account},#{pwd},#{phone},#{real_name},#{level})
            }
        }


        return app('json')->success('导入成功');
    }

    public function getImAdmin(){

        try {

            $data = json_decode('{
                "im_pass": 873947,
                "im_user_id": "admin",
                "im_uuid": "53d0f370-f104-11ee-8cd6-45641584429c"
            }',true);
            return app('json')->success($data);


            $im = new Im();

            $data = [];
            $data['im_pass'] = mt_rand(100000,999999);
            $data['im_user_id'] = 'admin';
            $data['im_uuid']= $im->createImUser('useradmin', 'admin',$data['im_pass']);
            return app('json')->success($data);
        } catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'注册异常'.$e->getFile().$e->getMessage().$e->getLine()]);
        }
        return app('json')->fail('注册失败');
    }

    public function enterpriseUserScoreApi(){
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['uid']);
        $list=Db::name('user_sign_score')->where($where)->page($page, $limit)->order('id desc')->select();

        foreach ($list as $k=>$v){
            $v['pm_text']='收入';
            if($v['pm']==2 || $v['pm']==4){
                $v['pm_text']='支出';
                $v['reward_socre']='-'.$v['reward_socre'];
            }else{
                $v['pm_text']='收入';
                $v['reward_socre']='+'.$v['reward_socre'];
            }
            if($v['order_id'] && empty($v['order_sn'])){
                $v['order_sn']=Db::name('store_order')->where('order_id',$v['order_id'])->value('order_sn');
            }
            if(empty($v['order_sn'])){
                $v['order_sn']='--';
            }
            $v['create_time'] = $v['settlement_time'];
            $v['create_time'] = date("Y-m-d H:i:s", $v['addtime']);
            $list[$k]=$v;
        }
        $data['list']=$list;
        $data['count']=Db::name('user_sign_score')->where($where)->count();
        return app('json')->success($data);
    }

    /**
     * 获取统计导出
     */
    public function getStatisticsExcel($header,$arr,$title)
    {
        $filename = $title.'_'.date('YmdHis').'_'.rand(10000,99999);
        $name = $filename;
        $info = '生成时间:' . date('Y-m-d H:i:s',time());
        $suffix='xlsx';
        $path='extract';
        unset($_instance);

        $_instance = SpreadsheetExcelService::instance_xin();

        $_path =$_instance
            ->createOrActive()
            ->setExcelHeader($header)
            ->setExcelTile($title, $name, $info)
            ->setExcelContent($arr)
            ->excelSave($filename, $suffix, $path);

        $domain = request()->domain();
        $data= [
            'name' => $filename.'.'.$suffix,
            'status' => 1,
            'path' => $domain.'/'.$_path
        ];

        return $data;
    }

    /**
     * 获取合伙人分红记录
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getWeekAwardList()
    {
        [$page, $limit] = $this->getPage();
        $nickname = request()->param('nickname', '');
        $account = request()->param('account', '');
        $user_group = request()->param('user_group', '');
        $dateRange = request()->param('dateRange', []);
        $where = [];
        if ($nickname) $where[] = ['u.nickname', 'like', '%' . $nickname . '%'];
        if ($account) $where[] = ['u.account', 'like', '%' . $account . '%'];
        if ($user_group) $where[] = ['w.user_group', '=', $user_group];
        if (!empty($dateRange)) {
            $where[] = ['w.create_time', 'between', [$dateRange[0], $dateRange[1]]];
        }

        $query = Db::name('partner_profit_records')->alias('w')
            ->leftJoin('user u', 'w.user_id=u.uid')
            ->leftJoin('user_identity identity', 'identity.user_group_id=w.user_group')
            ->field('w.*,u.uid,u.account,u.real_name,u.nickname,identity.user_group_name')
            ->where($where);
        // 导出
        $is_excel = request()->param('is_excel', 0);
        if ($is_excel == 1) {
            $data = $query->select();
            $arr = [];
            foreach ($data as $item) {
                $arr[] = [
                    $item['id'],
                    $item['nickname'],
                    $item['account'],
                    $item['user_group_name'],  // 合伙人等级
                    $item['start_time'],       // 账期开始时间
                    $item['end_time'],         // 账期结束时间
                    $item['performance'],      // 账期平台业绩
                    $item['red_envelope'],     // 账期内发放红包
                    $item['reality_performance'], // 实际分红业绩
                    $item['dividend_ratio'],   // 分红比例（%）
                    $item['dividend'],         // 分红金额
                    $item['performance_part'], // 个人小区业绩
                    $item['performance_part_all'], // 等级内小区业绩和
                    $item['part_money'],       // 小区业绩占比分红金额
                    $item['performance_total'], // 个人总业绩
                    $item['performance_total_all'], // 等级内总业绩和
                    $item['total_money'],      // 总业绩占比分红金额
                    $item['brokerage'],        // 分红佣金
                    $item['fugou'],            // 分红复购金
                    $item['radio'],            // 分红状态
                    $item['create_time'],      // 创建时间
                ];
            }
            return app('json')->success($this->getStatisticsExcel([
                'ID',
                '用户昵称',
                '用户账号',
                '合伙人等级',
                '账期开始时间',
                '账期结束时间',
                '账期平台业绩',
                '账期内发放红包',
                '实际分红业绩',
                '分红比例（%）',
                '分红金额',
                '个人小区业绩',
                '等级内小区业绩和',
                '小区业绩占比分红金额',
                '个人总业绩',
                '等级内总业绩和',
                '总业绩占比分红金额',
                '分红佣金',
                '分红复购金',
                '分红状态',
                '创建时间'
            ], $arr, '合伙人分红明细'));
        }

        $query1 = clone($query);
        $query2 = clone($query);
        $query3 = clone($query);
        // Primary, intermediate, advanced
        $partner_profit_primary_part_money = $query1->where('w.user_group', '=', 4)->sum('part_money');
        $partner_profit_primary_total_money = $query1->where('w.user_group', '=', 4)->sum('total_money');
        $partner_profit_primary = bcadd($partner_profit_primary_part_money, $partner_profit_primary_total_money, 2);

        $partner_profit_intermediate_part_money = $query2->where('w.user_group', '=', 5)->sum('part_money');
        $partner_profit_intermediate_total_money = $query2->where('w.user_group', '=', 5)->sum('total_money');
        $partner_profit_intermediate = bcadd($partner_profit_intermediate_part_money, $partner_profit_intermediate_total_money, 2);

        $partner_profit_advanced_part_money = $query3->where('w.user_group', '=', 6)->sum('part_money');
        $partner_profit_advanced_total_money = $query3->where('w.user_group', '=', 6)->sum('total_money');
        $partner_profit_advanced = bcadd($partner_profit_advanced_part_money, $partner_profit_advanced_total_money, 2);

        $data = $query->page($page)
            ->limit($limit)
            ->order('w.id desc')
            ->select();
        $count = $query->count();
        if ($data) {
            $data = $data->toArray();
            foreach ($data as $k => $v) {
                $data[$k]['radio'] = $v['radio'] == 2 ? '已发放' : '未发放';
            }
        }
        $return_data['list'] = $data;
        $return_data['count'] = $count;
        $return_data['partner_profit_primary'] = $partner_profit_primary ?: 0.00;
        $return_data['partner_profit_intermediate'] = $partner_profit_intermediate ?: 0.00;
        $return_data['partner_profit_advanced'] = $partner_profit_advanced ?: 0.00;
        return app('json')->success($return_data);
    }

    /**
     * 获取联创奖励记录
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOriginatorList()
    {
        [$page, $limit] = $this->getPage();
        $nickname = request()->param('nickname','');
        $account = request()->param('account','');
        $user_lianc_id = request()->param('user_lianc_id', '');
        $dateRange = request()->param('dateRange', []);
        $where = [];

        if (!empty($dateRange)) {
            $where[] = ['o.create_time', 'between', [strtotime($dateRange[0]), strtotime($dateRange[1])]];
        }
        if($nickname) $where[] = ['u.nickname','like','%'.$nickname.'%'];
        if($account) $where[] = ['u.account','like','%'.$account.'%'];
        if ($user_lianc_id) $where[] = ['o.user_lianc_id', '=', $user_lianc_id];

        $query = Db::name('old_user_originator')->alias('o')
            ->leftJoin('user u','o.user_id=u.uid')
            ->leftJoin('old_user_lianc lianc','lianc.id=o.user_lianc_id')
            ->field('o.*,u.uid,u.real_name,u.nickname,u.account,lianc.title, lianc.number')
            ->where($where);

        // 导出
        $is_excel = request()->param('is_excel', 0);
        if ($is_excel == 1) {
            $data = $query->select();
            $arr = [];
            foreach ($data as $item) {
                $arr[] = [
                    $item['id'],
                    $item['nickname'],
                    $item['account'],
                    $item['title'],
                    $item['number'],
                    $item['all_record'],
                    $item['all_amount'],
                    $item['money'],
                    date('Y-m-d H:i:s', $item['create_time'])
                ];
            }

            return app('json')->success($this->getStatisticsExcel([
                'ID',
                '用户昵称',
                '用户账号(手机号)',
                '联创等级',
                '联创缴纳金额',
                '本次联创分红总金额',
                '当前等级分红总金额',
                '获得分红金额',
                '创建时间'
            ], $arr, '联创分红明细'));
        }

        $query1 = clone($query);
        $originator_dividend_payout_money = $query1->sum('money');

        $data = $query->page($page)
            ->limit($limit)
            ->order('o.id desc')
            ->select();
        $count = $query->count();
        if($data) {
            $data = $data->toArray();
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }
        $return_data['list'] = $data;
        $return_data['count'] = $count;
        $return_data['originator_dividend_payout_money'] = $originator_dividend_payout_money;
        return app('json')->success($return_data);
    }

    /**
     * 获取股权分红记录
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getStockList()
    {
        [$page, $limit] = $this->getPage();
        $nickname = request()->param('nickname','');
        $account = request()->param('account','');
        $dateRange = request()->param('dateRange', []);
        $where = [];

        if (!empty($dateRange)) {
            $where[] = ['o.create_time', 'between', [strtotime($dateRange[0]), strtotime($dateRange[1])]];
        }
        if($nickname) $where[] = ['u.nickname','like','%'.$nickname.'%'];
        if($account) $where[] = ['u.account','like','%'.$account.'%'];
        $query = Db::name('old_user_stock')->alias('o')
            ->leftJoin('user u','o.user_id=u.uid')
            ->field('o.*,u.uid,u.real_name,u.nickname,u.account')
            ->where($where);

        // 导出
        $is_excel = request()->param('is_excel', 0);
        if ($is_excel == 1) {
            $data = $query->select();
            $arr = [];
            foreach ($data as $item) {
                $arr[] = [
                    $item['id'],
                    $item['nickname'],
                    $item['account'],
                    $item['pack'],
                    $item['getcomm'],
                    $item['allgetcomm'],
                    date('Y-m-d H:i:s', $item['create_time']),
                    date('Y-m-d H:i:s', $item['update_time'])
                ];
            }
            return app('json')->success($this->getStatisticsExcel([
                'ID',
                '用户昵称',
                '用户账号(手机号)',
                '份数',
                '本次佣金',
                '累计佣金',
                '创建时间',
                '更新时间'
            ], $arr, '股权分红明细'));
        }

        $query1 = clone($query);
        $stock_getcomm = $query1->sum('getcomm');
        $stock_allgetcomm = $query1->sum('allgetcomm');

        $data = $query->page($page)
            ->limit($limit)
            ->order('o.id desc')
            ->select();
        $count = $query->count();
        if($data) {
            $data = $data->toArray();
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                $data[$k]['update_time'] = date('Y-m-d H:i:s',$v['update_time']);
            }
        }
        $return_data['list'] = $data;
        $return_data['count'] = $count;
        $return_data['stock_getcomm'] = $stock_getcomm;
        $return_data['stock_allgetcomm'] = $stock_allgetcomm;
        return app('json')->success($return_data);
    }

    /**
     * 股权分红创建表单
     * @return mixed
     */
    public function stockCreateForm()
    {
        return app('json')->success(formToData($this->repository->stockCreateForm()));
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param $id
     * @return mixed
     */
    public function stockUpdateForm($id)
    {
        if (!$id) return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->stockUpdateForm($id)));
    }

    /**
     * 添加
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function stockCreate()
    {
        $user_id = request()->param('user_id',0);
        $pack = request()->param('pack',0);
        if(!$user_id) return app('json')->fail('请选择用户');
        if(!$pack) return app('json')->fail('请输入份数');
        $user_data = Db::name('old_user_stock')->where('user_id',$user_id)->find();
        if($user_data) return app('json')->fail('用户已存在');
        $insert_data = [
            'user_id' => $user_id,
            'pack' => $pack,
            'getcomm' => 0,
            'allgetcomm' => 0,
            'create_time' => time(),
        ];
        Db::name('old_user_stock')->save($insert_data);
        return app('json')->success('添加成功');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param $id
     * @param validate $validate
     * @return mixed
     */
    public function stockUpdate($id)
    {
        $pack = request()->param('pack',0);
        if(!$pack) return app('json')->fail('请输入份数');
        Db::name('old_user_stock')->where('id',$id)->update(['pack' => $pack,'update_time'=>time()]);
        return app('json')->success('编辑成功');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param $id
     * @return mixed
     */
    public function stockDelete($id)
    {
        if (!$id) return app('json')->fail('数据不存在');
        Db::name('old_user_stock')->where('id',$id)->delete();
        return app('json')->success('删除成功');
    }

    /**
     * 获取零号线用户列表
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getZeroLineUserList()
    {
        $team_name = request()->param('team_name', '');
        $status = request()->param('status', '');
        $user_account = request()->param('account', '');
        [$page, $limit] = $this->getPage();

        $query = Db::name('user_zero_line')
            ->alias('uzl')
            ->leftJoin('user u', 'u.uid = uzl.team_uid');
        if ($status != '') {
            $query->where('uzl.status', '=', $status);
        }

        if ($team_name != '') {
            $query->whereLike('uzl.team_name', '%' . $team_name . '%');
        }

        if ($user_account != '') {
            $query
                ->whereLike('u.account', '%' . $user_account . '%');
        }
        $result['count'] = $query->count();
        $result['list'] = $query
            ->field('uzl.*, u.account')
            ->order("uzl.id desc")
            ->page($page, $limit)
            ->select()
            ->toArray();

        foreach ($result['list'] as &$team_data) {
            //查询当前团队的用户列表
            $sql = "select getUserLevelId({$team_data['team_uid']}) as uids";
            try {
                $spread_user_list = Db::query($sql);
            } catch (\Exception $exception) {
                $team_data['team_user_num'] = 0;
                continue;
            }
            $spread_user_list = explode(",", trim($spread_user_list[0]['uids'], '$,'));
            $team_data['team_user_num'] = count($spread_user_list);
        }


        return app('json')->success('获取成功', $result);
    }

    /**
     * 获取零号线用户列表
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setZeroLineUser()
    {
        $team_uid = request()->param('team_uid', 0);
        $team_name = request()->param('team_name', null);
        $status = request()->param('status', null);
        $custom_code = request()->param('custom_code', null);

        $userData = Db::name('user')
            ->where('uid', '=', $team_uid)
            ->where('is_del', '=', 0)
            ->find();
        if (!$userData) {
            return app('json')->fail('用户不存在');
        }

        if ($team_name === '') {
            $team_name = $userData['nickname'] . '0号线';
        }

        $isExist = Db::name('user_zero_line')
            ->where('team_uid', '=', $team_uid)
            ->find();

        Db::startTrans();
        try {
            // 0 号线可以有上级
            // Db::name('user')
            //     ->where('uid', '=', $team_uid)
            //     ->where('is_del', '=', 0)
            //     ->update(['level_id' => 0]);
            if ($isExist) {
                $result = Db::name('user_zero_line')
                    ->where('team_uid', '=', $team_uid)
                    ->update([
                        'team_name' => $team_name,
                        'status' => $status,
                        'custom_code' => $custom_code,
                    ]);
            } else {
                $result = Db::name('user_zero_line')
                    ->insert([
                        'team_uid' => $team_uid,
                        'team_name' => $team_name,
                        'status' => $status,
                        'custom_code' => $custom_code,
                    ]);
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return app('json')->fail('设置失败');
        }
        if ($result) {
            return app('json')->success('设置成功', $result);
        }
        return app('json')->fail('设置失败');
    }

    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserListByFuzzy()
    {
        $fuzzy = request()->param('fuzzy', null);
        if (is_null($fuzzy)) {
            return app('json')->success('查询成功', []);
        }
        $userData = Db::name('user')
            ->where('is_del', '=', 0)
            ->where(function ($query) use ($fuzzy) {
                $query->where('nickname', 'like', '%' . $fuzzy . '%')
                    ->whereOr('account', 'like', '%' . $fuzzy . '%');
            })
            ->field('uid, nickname, account')
            ->select()
            ->toArray();
        return app('json')->success('查询成功', $userData);
    }
    /**
     * 用户操作记录
     */
    public function getOperatingRecordList(){
        $records = Db::name('user_operating_record')
            ->alias('r')
            ->join('user u', 'r.uid = u.uid', 'LEFT')
            ->field('r.*, u.phone, u.nickname')
            ->where(function ($query) {
                $nickname = request()->param('nickname');
                $account  = request()->param('account');
                $nickname && $query->whereLike('u.nickname', "%{$nickname}%");
                $account  && $query->whereLike('u.account', "%{$account}%");
            })
            ->order('r.create_time DESC')
            ->paginate(20)
            ->toArray();
        return app('json')->success($records, '获取成功');
    }
    //用户身份修改记录
    public function getUserIdentityChangeRecord($id){
        $uid = $id;
        $records = Db::name('user_identity_change_records')
            ->alias('r')
            ->join('user u', 'r.uid = u.uid', 'LEFT')
            ->field('r.operation_id,r.old_identity_id,r.uid,r.new_identity_id,r.mark,r.create_time,u.nickname,u.account');
            if($uid){
                $records->where('r.uid', $uid);
            }
            $query=$records
            ->order('create_time DESC')
            ->paginate(20)
            ->toArray();
        return app('json')->success($query, '获取成功');
    }
    //用户推荐人修改记录
    public function getUserSpreadChangeRecord($id){
        $uid = $id;
        $records = Db::name('user_spread_change_records')
            ->alias('r')
            ->join('user u', 'u.uid = r.old_spread_id', 'LEFT')
            ->join('user ua', 'ua.uid = r.new_spread_id', 'LEFT')
            ->field('r.operation_id,r.uid,u.account as old_account,ua.account as new_account,r.mark, r.create_time');

        if ($uid) {
            $records->where('r.uid', $uid);
        }

        $query = $records
            ->order('r.create_time DESC')
            ->paginate(20)
            ->toArray();

        return app('json')->success($query, '获取成功');
    }

    //用户节点人修改记录
    public function getUserLevelChangeRecord($id){
        $uid = $id;
        $records = Db::name('user_level_change_records')
            ->alias('r')
            ->join('user u', 'u.uid = r.old_level_id', 'LEFT')
            ->join('user ua', 'ua.uid = r.new_level_id', 'LEFT')
            ->field('r.operation_id, r.uid, u.account as old_account, ua.account as new_account, r.mark, r.create_time');
        if($uid){
            $records->where('r.uid', $uid);
        }
        $query=$records
            ->order('create_time DESC')
            ->paginate(20)
            ->toArray();
        return app('json')->success($query, '获取成功');
    }
    /**
     * 查询用户上下级
     */
    public function getUserLevelList($id)
    {
        $uid = $id;
        $query = Db::name('user')
            ->where('level_id', $uid)
            ->where('is_del', 0)
            ->field('uid, account, nickname')
            ->select()
            ->toArray();
        return app('json')->success($query, '获取成功');
    }
}
