<?php

namespace app\api\controller\company;

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

use app\common\model\User;
use fast\Random;

/**
 * 客户
 */
class Customer extends Apic
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    //头部统计
    public function index(){
        $where = [
            'company_id' => $this->auth->company_id,
        ];
        if($this->auth->type == 2){
            $where['staff_id'] = $this->auth->id;
        }
        //全部
        $customer_all = Db::name('user_wallet')->where($where)->count();
        //今日
        $starttime = strtotime(date('Y-m-d'));
        $endtime = $starttime + 86399;
        $where['createtime'] = ['BETWEEN',[$starttime,$endtime]];
        $customer_today = Db::name('user_wallet')->where($where)->count();
        //七日
        $starttime = strtotime(date('Y-m-d')) - 518400;
        $where['createtime'] = ['BETWEEN',[$starttime,$endtime]];
        $customer_week = Db::name('user_wallet')->where($where)->count();

        //
        $rs = [
            'today'=>$customer_today,
            'week' => $customer_week,
            'all'  => $customer_all,
        ];

        $this->success(1,$rs);
    }

    //列表
    public function lists(){
        $keyword = input('keyword','');

        $where = [
            'w.company_id' => $this->auth->company_id,
        ];
        if(!empty($keyword)){
            $where['user.nickname|user.mobile'] = ['LIKE','%'.$keyword.'%'];
        }

        $list = Db::name('user_wallet')->alias('w')
            ->field('w.*,user.nickname,user.mobile,user.avatar')
            ->join('user','w.user_id = user.id','LEFT')
            ->where($where)
            ->order('id desc')->autopage()->select();
        $list = list_domain_image($list,['avatar']);

        //追加车牌
        if(!empty($list)){
            $user_ids = array_column($list,'user_id');
            $user_car = Db::name('user_car')->where('user_id','IN',$user_ids)->select();
            foreach($list as $key => &$val){
                $val['car_number'] = '';
                $carnumber = '';
                foreach($user_car as $k => $v){
                    if($val['user_id'] == $v['user_id']){
                        $carnumber .= $v['car_number'];
                        if(!empty($v['car_model'])){
                            $carnumber .= '('.$v['car_model'].')';
                        }
                        $carnumber .= ',';
                    }
                }
                if($carnumber != ''){
                    $carnumber = substr($carnumber,0,-1);
                }

                $val['car_number'] = $carnumber;
            }
        }

        $this->success(1,$list);
    }

    //新增
    public function add(){
        $field = ['nickname','mobile','car_number','address','comefrom','remark'];
        $data = request_post_hub($field);

        $user = Db::name('user')->field('id,nickname,mobile')->where('mobile',$data['mobile'])->find();
        //已经存在的用户
        if($user){
            //已经是我公司的客户
            $map = [
                'w.user_id'    => $user['id'],
                'w.company_id' => $this->auth->company_id,
            ];
            $check = Db::name('user_wallet')->alias('w')
                ->field('w.*,staff.truename')
                ->join('company_staff staff','w.staff_id = staff.id','LEFT')
                ->where($map)->find();

            if($check){
                $this->error('已经是['.$check['truename'].']的客户,无需重复添加');
            }

            Db::startTrans();
            //添加新客户
            $new_data = [
                'user_id'    => $user['id'],
                'company_id' => $this->auth->company_id,
                'staff_id'   => $this->auth->id,
                'money'      => 0,
                'address'    => $data['address'],
                'createtime' => time(),
                'updatetime' => time(),
                'comefrom'   => $data['comefrom'],
                'remark'     => $data['remark'],
            ];
            $rs_customer = Db::name('user_wallet')->insertGetId($new_data);
            if(!$rs_customer){
                Db::rollback();
                $this->error('客户添加失败');
            }

            //加新车
            $car_map = [
                'user_id'    => $user['id'],
                'car_number' => $data['car_number'],
            ];
            $car_info = Db::name('user_car')->where($car_map)->find();
            if(empty($car_info)){
                $car_map['createtime'] = time();
                $car_map['updatetime'] = time();
                $rs_car = Db::name('user_car')->insertGetId($car_map);
                if(!$rs_car){
                    Db::rollback();
                    $this->error('车辆添加失败');
                }
            }

            Db::commit();
            $this->success('添加完成');

        }else{
            //注册新用户
            //$introcode = User::column("introcode");

            $user_data = [
                'nickname' => $data['nickname'],
                'mobile'   => $data['mobile'],
                'avatar'   => '/assets/img/avatar.png',
                //'introcode' => $this->getUinqueNo(8, $introcode),
                'jointime'  => time(),
                'joinip'    => request()->ip(),
                'status'    => 1,
                'company_id'=> $this->auth->company_id,
            ];
            Db::startTrans();
            $user_id = Db::name('user')->insertGetId($user_data);
            if(!$user_id){
                Db::rollback();
                $this->error('添加客户失败');
            }

            $username = 'u' . (10000 + $user_id);
            Db::name('user')->where('id',$user_id)->update(['username'=>$username]);

            //添加新客户
            $new_data = [
                'user_id'    => $user_id,
                'company_id' => $this->auth->company_id,
                'staff_id'   => $this->auth->id,
                'money'      => 0,
                'address'    => $data['address'],
                'createtime' => time(),
                'updatetime' => time(),
                'comefrom'   => $data['comefrom'],
                'remark'     => $data['remark'],
            ];
            $rs_customer = Db::name('user_wallet')->insertGetId($new_data);
            if(!$rs_customer){
                Db::rollback();
                $this->error('客户添加失败');
            }

            //加新车
            $car_map = [
                'user_id'    => $user_id,
                'car_number' => $data['car_number'],
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $rs_car = Db::name('user_car')->insertGetId($car_map);
            if(!$rs_car){
                Db::rollback();
                $this->error('车辆添加失败');
            }

            Db::commit();
            $this->success('添加完成');

        }

        $this->success('添加成功');
    }


    /**
     * 生成不重复的随机数字字母组合
     */
    function getUinqueNo($length = 8, $nos = [])
    {
        $newid = Random::build("alnum", $length);
        if (in_array($newid, $nos)) {
            $newid = $this->getUinqueNo($length, $nos);
        }
        return $newid;
    }

    //检索用户
    public function searchuser(){
        $mobile = input('mobile','');

        $check = Db::name('user')->field('id,nickname,mobile')->where('mobile',$mobile)->find();
        $this->success(1,$check);
    }

    //余额管理
    public function changemoney(){
        $id = input('id',0);
        $user_id = input('user_id',0);
        $type = input('type',1); //1增加，2减少
        $money = input('money',0);

        $number  = $type == 1 ? $money : -$money;
        $logtype = $type == 1 ? 101 : 102;

        //验证
        if($this->auth->type != 1){
            $this->error('只有门店老板才能操作');
        }

        //检查
        $map = [
            'id' => $id,
            'user_id' => $user_id,
            'company_id' => $this->auth->company_id,
        ];
        $check = Db::name('user_wallet')->where($map)->find();
        if(!$check){
            $this->error('错误的客户');
        }

        Db::startTrans();
        $rs = model('wallet')->lockChangeAccountRemain($this->auth->company_id,$user_id,'money',$number,$logtype,'门店操作余额('.$this->auth->truename.')');
        if($rs['status'] === false){
            Db::rollback();
            $this->error($rs['msg']);
        }

        Db::commit();
        $this->success();
    }

    //客户详情
    public function userinfo(){
        $user_id = input('user_id',0);

        $map = [
            'w.user_id' => $user_id,
            'w.company_id' => $this->auth->company_id,
        ];

        $info = Db::name('user_wallet')->alias('w')
            ->field('w.*,user.nickname,user.mobile,user.avatar')
            ->join('user','w.user_id = user.id','LEFT')
            ->where($map)->find();

        $info = info_domain_image($info,['avatar']);

        $this->success(1,$info);
    }

    //某客户消费明细
    public function moneylog(){
        $user_id = input('user_id',0);

        $map = [
            'user_id' => $user_id,
            'company_id' => $this->auth->company_id,
        ];

        $list = Db::name('user_money_log')->where($map)->order('id desc')->autopage()->select();
        foreach($list as $key => &$val){
            $val['change_value'] = $val['change_value'] > 0 ? '+'.$val['change_value'] : $val['change_value'];
            $val['remark'] = '['.$val['remark'].'] '.$val['change_value'].'，余额'.$val['remain'];
        }
        $this->success(1,$list);
    }






}
