Contacts.php 9.92 KB
<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Contacts as ContactsModel;
use addons\qingdong\model\ContactsFile;
use addons\qingdong\model\ContactsOther;
use addons\qingdong\model\FormField;
use addons\qingdong\model\Record;
use addons\qingdong\model\Event as EventModel;
use addons\qingdong\model\OperationLog;
use addons\qingdong\model\Staff;
use think\Db;
use think\Exception;

/**
 * 联系人接口
 */
class Contacts extends StaffApi {

	protected $noNeedLogin = ['getContactsList','getContactsId','introduce'];
	protected $noNeedRight = [];



    //递归查询联系人并构建拓扑关系数据
    public function introduce() {
        $param = $this->request->param();
        $model = new ContactsModel();
        $find = $model->with('contacts')->where('id', $param['id'])->field('id, name, role, post, is_signin, referee_id, referee')->find();

        if (!$find) {
            $this->error('Contact not found');
        }

        $processed[] = $param['id']; // 用于记录已经处理过的联系人
        //上级关系
        $result = $this->buildTree($find['is_signin'], $find['referee_id'], $find['referee'],$processed  , $depth = 1);

        //下级关系
        $result2 = $this->buildTree2($param['id']);

        $this->success('联系人拓扑关系数据',['find'=>$find,'list'=>$result,'list2'=>$result2]);
    }

    public function buildTree($is_signin = '', $referee_id = '', $referee = '',$processed,$depth = 1) {
        $model = new ContactsModel();
        $arr = [];

        if ($depth > 2) {
            return $arr; // 超过两级时返回空数组,停止递归
        }

        if(!empty($referee_id) || $referee){
            if ($is_signin == 1) {
                $list = $model->with('contacts')->where('id', $referee_id)->field('id, name, role, post, is_signin, referee_id, referee')->select();
            } else {
                $list = $model->with('contacts')->where('referee', $referee)->field('id, name, role, post, is_signin, referee_id, referee')->select();
            }
            foreach ($list as $item) {
                if (in_array($item['id'], $processed)) {
                    continue; // 跳过已经处理过的联系人,避免死循环
                }
                //halt($item);
                $processed[] = $item['id']; // 记录处理过的联系人
                $children = $this->buildTree($item['is_signin'], $item['referee_id'], $item['referee'], $processed,$depth + 1);
                $arr[] = [
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'role' => $item['role'],
                    'post' => $item['post'],
                    'is_signin'=>$item['is_signin'],
                    'referee_id'=>$item['referee_id'],
                    'referee'=>$item['referee'],
                    'contacts'=>$item['contacts'],
                    'children' => $children,
                ];
            }
        }



        return $arr;
    }


    public function buildTree2($id,$depth = 1) {
        $model = new ContactsModel();
        $arr = [];


        if ($depth > 2) {
            return $arr; // 超过两级时返回空数组,停止递归
        }
        $list = $model->with('contacts')->where('referee_id', $id)->field('id, name, role, post, is_signin, referee_id, referee')->select();

        foreach ($list as $item) {

            $children = $this->buildTree2($item['id'],$depth + 1);
            $arr[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'role' => $item['role'],
                'post' => $item['post'],
                'is_signin'=>$item['is_signin'],
                'referee_id'=>$item['referee_id'],
                'referee'=>$item['referee'],
                'contacts'=>$item['contacts'],
                'children' => $children,
            ];
        }

        return $arr;
    }






    //创建联系人
	public function addContacts() {
		$params = $this->request->post();
		if (empty($params['contacts'])) {
			$this->error('联系人信息不能为空');
		}
		// 表单验证
        if (($result = $this->qingdongValidate($params['contacts'], get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params['contacts']);
        if ($result !== true) {
            $this->error($result);
        }
		if (ContactsModel::where([
			'mobile'      => $params['contacts']['mobile'],
			'customer_id' => $params['contacts']['customer_id']
		])->find()) {
			$this->error('联系人手机号已存在');
		}
		Db::startTrans();
		try {
			$mobile =$params['contacts']['mobile'];
			$email =$params['contacts']['email']??'';
			if(empty($mobile) && empty($email)){
				$this->error('手机号码和邮箱至少填写一项!');
			}
			$rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
			$rule2 = '^[0-9]+$^';
			if (preg_match($rule, $mobile) == false && preg_match($rule2, $mobile) ==false) {
				$this->error('手机号格式错误,国外手机号请填写区号,例如 86XXXX');
			}

            $contactsId = ContactsModel::createContacts($params['contacts']);
			if (isset($params['is_event']) && $params['is_event'] == 1) {//跟进任务
				$event                  = $params['event'];
				$event['type']          = 2;//任务
				$event['relation_type'] = EventModel::CONTACTS_TYPE;//联系人
				$event['relation_id']   = $contactsId;
				$event['end_time']      = $event['start_time'];
				$event['level']         = 1;
				$result                 = EventModel::createEvent($event);
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('创建联系人成功');
		}
	}


	//编辑联系人
	public function editContacts() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ContactsModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('客户信息不存在');
		}
		// 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
		if (ContactsModel::where([
			'mobile'      => $params['mobile'],
			'customer_id' => $row['customer_id'],
			'id'          => ['neq', $params['id']]
		])->find()) {
			$this->error('联系人手机号已存在');
		}
		Db::startTrans();
		try {
			$result = ContactsModel::updateContacts($params);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

		$this->success('编辑联系人成功');
	}


	//删除联系人
	public function delContacts() {
		$id = input('id');

		$row = ContactsModel::where(['id' => $id, 'owner_staff_id' => $this->auth->id])->find();
		if (empty($row)) {
			$this->error('您不是客户归属人,无法删除当前联系人');
		}
		$model = new ContactsModel();
		if ($model->destroy(['id' => $id])) {
			$this->success('删除成功');
		}
		Record::quickCreateRecord(Record::CUSTOMER_TYPE, $row['customer_id'],
            '删除联系人:' . $row['name']);
		OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $row['customer_id'], '删除联系人:' . $row['name']);
		$this->error('删除失败');
	}


	//获取联系人列表
	public function getList() {
		$limit       = input("limit/d", 10);
		$customer_id = input('customer_id');
		$name        = input('name');

        $params = input();
        $where = FormField::updateWhereField(FormField::CONTACTS_TYPE, $params);
        if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}else{
			$where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
		}
		if ($name) {
			$where['name'] = ['like', "%{$name}%"];
		}
		$records                 = ContactsModel::where($where)->with(['customer'])->order('id desc')->paginate($limit);
		$this->success('请求成功', $records);
	}


	//获取select联系人列表
	public function getSelectList() {
		$customer_id = input('customer_id');
        $name = input('name','');
		$where       = [];
		if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}
        if ($name) {
            $where['name'] = ['like',"%$name%"];
        }
		$list                    = ContactsModel::where($where)->with(['customer'])->field('id,customer_id,name,mobile')->select();
		$list                    = collection($list)->toArray();
		foreach ($list as $k => $v) {
			$v['new_mobile'] = $v['mobile'];
			$list[$k]        = $v;
		}
		$this->success('请求成功', $list);
	}


	//获取联系人详情
	public function getDetail() {
		$id       = input('id');
		$contract = ContactsModel::where(['id' => $id])->with([
			'customer',
			'ownerStaff'
		])->find();

		if (empty($contract)) {
			$this->error('信息不存在');
		}
		$contract               = $contract->toArray();
        $contract=ContactsOther::getOther($contract);

		$this->success('请求成功', $contract);
	}


	//获取附件列表
	public function getFilesList() {
		$id = input('contacts_id');

		$files = ContactsFile::where(['contacts_id' => $id])->field('file_id')->with(['file'])->select();
		$this->success('请求成功', $files);
	}



    public function getContactsId(){

        $param = $this->request->param();

        $data = (new ContactsModel())->where('customer_id',$param['customer_id'])->find();

        $this->success('',$data);

    }



    public function getContactsList(){

        $param = $this->request->param();

        $data = (new ContactsModel())->where('customer_id',$param['customer_id'])->select();

        $this->success('',$data);

    }

}