<?php

namespace app\company\controller;

use app\common\controller\Apic;
use think\Db;
use app\common\model\User as Usermodel;
use think\Exception;
use app\common\library\Tenim;
/**
 * 客户管理
 */
class Usercompany extends Apic
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['selectpage','info'];

    protected $table = 'user_company';

    public function index(){
        $search = [];
        $user_nickname = input('user_nickname','');
        $projectname = input('projectname','');
        $weituo = input('weituo','');
        $header = input('header','');
        if(!empty($user_nickname)){
            $search['user.nickname'] = ['LIKE','%'.$user_nickname.'%'];
        }
        if(!empty($projectname)){
            $search['a.projectname'] = ['LIKE','%'.$projectname.'%'];
        }
        if(!empty($weituo)){
            $search['a.weituo'] = ['LIKE','%'.$weituo.'%'];
        }
        if(!empty($header)){
            $search['a.header'] = ['LIKE','%'.$header.'%'];
        }

        $list = Db::name($this->table)->alias('a')
            ->field('a.id,a.projectname,a.starttime,a.endtime,a.weituo,a.fuwujigou,a.header,a.header_mobile,
            user.id as user_id,user.avatar as user_avatar,user.nickname as user_nickname,user.mobile as user_mobile')
            ->join('user','a.user_id = user.id','LEFT')
            ->where('a.company_id',$this->auth->company_id)
            ->where('a.deletetime',NULL)
            ->where($search)
            ->order('a.id desc')
            ->paginate();
        $total = $list->total();
        $list = $list->items();
        $list = list_domain_image($list,['user_avatar']);

        $rs = [
            'list' => $list,
            'total'=> $total,
        ];

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

    //下拉
    public function selectpage(){

        $list = Db::name($this->table)
            ->field('id,projectname')
            ->where('company_id',$this->auth->company_id)
            ->where('deletetime',NULL)
            ->select();

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

    //添加客户
    public function add(){
        $mobile = input('user_mobile','');
        if(empty($mobile)){
            $this->error('手机号必填');
        }

        //检查用户
        $find = Db::name('user')->where('mobile',$mobile)->find();
        if($find){
            $this->error('该手机号已被注册为客户');
        }

        //注册到用户表
        $nickname = input('user_nickname','');
        if(empty($nickname)){
            $this->error('客户名称必填');
        }
        $extend = [
            'nickname'    => $nickname,
            'company_id'  => $this->auth->company_id,

            'contactname' => $nickname,                   //默认给用户
            'address'     => input('projectaddress',''),  //默认给用户
            'avatar'      => input('image',''),           //默认给用户
        ];
        $register_rs = $this->register($mobile,$extend);
        if($register_rs === false){
            $this->error('添加客户失败');
        }

        $user_id = $register_rs;

        //注册到im
        //user_用户端小程序,master_师傅,kefu_客服
        $tenim = new Tenim();
        $rs = $tenim->register('user_'. $user_id, $extend['nickname'], localpath_to_netpath($extend['avatar']));

        $zuobiao = input('zuobiao','','trim');
        $zuobiao = explode(',',$zuobiao);

        Db::startTrans();
        //添加客户
        $data = [
            'user_id'    => $user_id,
            'company_id' => $this->auth->company_id,
            'projectname'      => input('projectname',''),
            'projectaddress'   => input('projectaddress',''),
            'image'            => input('image',''),
            'starttime'        => input('starttime','','strtotime'),
            'endtime'          => input('endtime','','strtotime'),
            'header'           => input('header',''),
            'header_avatar'    => input('header_avatar',''),
            'header_mobile'    => input('header_mobile',''),
            'xiaofang'         => input('xiaofang',''),
            'xiaofang_mobile'  => input('xiaofang_mobile',''),
            'weituo'           => input('weituo',''),
            'fuwujigou'        => input('fuwujigou',''),
            'weibaofanwei'     => input('weibaofanwei',''),
            'longitude'        => isset($zuobiao[0]) ? $zuobiao[0] : '',
            'latitude'         => isset($zuobiao[1]) ? $zuobiao[1] : '',
        ];
        $uc_id = Db::name($this->table)->insertGetId($data);
        if(!$uc_id){
            Db::rollback();
            $this->error('添加客户失败,请重新再试');
        }

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

    public function info(){
        $id = input('id',0);
        $info = Db::name($this->table)->alias('a')
            ->field('a.*,user.nickname as user_nickname,user.mobile as user_mobile')
            ->join('user','a.user_id = user.id','LEFT')
            ->where('a.id',$id)
            ->where('a.company_id',$this->auth->company_id)
            ->find();
        $info = info_domain_image($info,['image','header_avatar']);

        $info['zuobiao'] = '';
        if(!empty($info['longitude']) && !empty($info['longitude'])){
            $info['zuobiao'] = $info['longitude'].','.$info['latitude'];
        }

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

    public function edit(){
        $id = input('id',0);
        $info = Db::name($this->table)->where('id',$id)->where('company_id',$this->auth->company_id)->find();
        if(empty($info)){
            $this->error('没找到该信息,请刷新重试');
        }

        //修改用户
        $mobile = input('user_mobile','');
        if(empty($mobile)){
            $this->error('手机号必填');
        }

        //检查用户
        $find = Db::name('user')->where('mobile',$mobile)->where('id','NEQ',$info['user_id'])->find();
        if($find){
            $this->error('该手机号已被注册为客户');
        }

        //修改昵称
        $nickname = input('user_nickname','');
        if(empty($nickname)){
            $this->error('客户名称必填');
        }
        $extend = [
            'nickname' => $nickname,
            'mobile'   => $mobile,
        ];
        $update_rs = Db::name('user')->where('id',$info['user_id'])->update($extend);
        if($update_rs === false){
            $this->error('操作失败');
        }

        //如果有修改头像或昵称,同步到im
        //user_用户端小程序,master_师傅,kefu_客服
        $tenim = new Tenim();
        $rs = $tenim->useredit('user_'. $info['user_id'], $nickname, '');

        //
        $zuobiao = input('zuobiao','','trim');
        $zuobiao = explode(',',$zuobiao);

        $data = [
            'projectname'      => input('projectname',''),
            'projectaddress'   => input('projectaddress',''),
            'image'            => input('image',''),
            'starttime'        => input('starttime','','strtotime'),
            'endtime'          => input('endtime','','strtotime'),
            'header'           => input('header',''),
            'header_avatar'    => input('header_avatar',''),
            'header_mobile'    => input('header_mobile',''),
            'xiaofang'         => input('xiaofang',''),
            'xiaofang_mobile'  => input('xiaofang_mobile',''),
            'weituo'           => input('weituo',''),
            'fuwujigou'        => input('fuwujigou',''),
            'weibaofanwei'     => input('weibaofanwei',''),
            'longitude'        => isset($zuobiao[0]) ? $zuobiao[0] : '',
            'latitude'         => isset($zuobiao[1]) ? $zuobiao[1] : '',
        ];

        Db::name($this->table)->where('id',$id)->update($data);

        $this->success();
    }

    public function del(){
        $ids = input('ids','');
        $ids = explode(',',$ids);

        if (empty($ids)) {
            $this->error();
        }

        Db::startTrans();

        $user_company = Db::name($this->table)->where('id','IN',$ids)->where('company_id',$this->auth->company_id)->where('deletetime',NULL)->select();
        if(!empty($user_company)){
            foreach($user_company as $key => $uc){
                $rs1 = Db::name($this->table)->where('id',$uc['id'])->update(['deletetime'=>time()]); //软删除
                $rs2 = Db::name('user')->where('id',$uc['user_id'])->update(['company_id'=>0]);       //用户解除绑定
                if($rs1 === false || $rs2 === false){
                    Db::rollback();
                    $this->error('删除失败');
                }
            }
        }
        Db::commit();
        $this->success();
    }


    //来自app\common\library\register

    private function register($mobile = '', $extend = [])
    {
        $ip = request()->ip();
        $time = time();

        $data = [
            'mobile'   => $mobile,
            'avatar'   => config('user_default_avatar'),
        ];
        $params = array_merge($data, [
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 1
        ]);
        $params = array_merge($params, $extend);

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = Usermodel::create($params, true);

            $this->_user = Usermodel::get($user->id);
            $this->_user->username = 'u' . (10000 + $user->id);
            $this->_user->save();

            Db::commit();
            return $user->id;
        } catch (Exception $e) {

            Db::rollback();
//            return $e->getMessage();
            return false;
        }
        return false;
    }



}