<?php
/**
 *  我的线索
 * @author  system
 * @version    1.0
 * @date 2018-11-20 02:55:06
 *
 */

namespace App\Http\Controllers\Admin\User;

use App\Exports\ThreadsExport;
use App\Http\Controllers\Admin\Controller;
use App\Models\CallListModel;
use App\Models\CompanyContactsModel;
use App\Models\ThreadsProgressModel;
use App\Models\UserThreadsModel;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\User\Threads\Criteria\MultiWhere;
use App\Repositories\User\ThreadsRepository;
use Maatwebsite\Excel\Facades\Excel;

class ThreadsController extends Controller
{
    private $repository;

    public function __construct(ThreadsRepository $repository)
    {
        if (!$this->repository) $this->repository = $repository;
    }

    /**
     * 列表页
     */
    function index(Request $request)
    {
        $user_id = \Auth::guard('admin')->user()->id;


        $search = $request->all();

        $search['keyword'] = $request->input('keyword');
        if (is_numeric($search['keyword'])) {
            $list = UserThreadsModel::whereHas('contact', function ($query) use ($search) {
                $query->where('phone', 'like', '%' . $search['keyword'] . '%');
            })->where('ower_id', $user_id)->orderBy('updated_at', 'desc');

        } else {
            $list = UserThreadsModel::whereHas('company', function ($query) use ($search) {
                $query->where('company_name', 'like', '%' . $search['keyword'] . '%')
                    ->orWhere('reg_no', 'like', '%' . $search['keyword'] . '%');
            })->where('ower_id', $user_id)->orderBy('updated_at', 'desc');
        }

        if (isset($search['process']) && $search['process'] == 1) {
            $list = $list->has('progress');
        }

        if (isset($search['process']) && $search['process'] == 2) {
            $list = $list->has('progress', '=', 0);
        }

        $allIds = $list->pluck('id');
        $list = $list->paginate(10);

        if ($request->ajax()) {
            $view = view('admin.user.threads.data', compact('list', 'allIds'))->render();

            return response()->json(['html' => $view]);

        }

        return view('admin.user.threads.index', compact('list', 'allIds'));
    }


    /**
     * 添加线索
     */
    public function create(Request $request)
    {
        $data['ower_id'] = \Auth::guard('admin')->user()->id;
        $data['company_id'] = $request->get('company_id');
        $data['contact_id'] = $request->get('contact_id');
        $data['status'] = 0;
        $res = $this->repository->create($data);

        /*添加初始化跟进备注*/
        if ($request->get('remark')) {
            ThreadsProgressModel::create(['threads_id' => $res->id, 'remark' => $request->get('remark')]);
        }

        if ($res) {
            $url[] = array('url' => U('User/Threads/index'), 'title' => '我的线索');
            $this->showMessage('添加成功', $url);
        } else {
            $url[] = array('url' => U('User/Threads/index'), 'title' => '我的线索');
            return $this->showWarning('添加失败', $url);
        }
    }


    /**
     * 添加线索跟进
     */
    public function update(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->_updateSave();
        }
        $data = $this->repository->find($request->get('id'));
        $progress = $data->progress()->orderBy('id', 'desc')->get();
        return view('admin.user.threads.edit', compact('data', 'progress'));
    }

    /**
     * 保存修改
     */
    private function _updateSave()
    {
        $data = (array)request('data');
        ThreadsProgressModel::create($data);

        $progress = ThreadsProgressModel::where('threads_id', $data['threads_id'])->orderBy('id', 'desc')->get();

        $view = view('admin.user.threads.progress', compact('progress'))->render();

        return response()->json(['html' => $view]);
    }

    public function view(Request $request)
    {
        $data = $this->repository->find(request('id'));
        return view('admin.user.threads.view', compact('data'));
    }


    /**
     * 删除
     */
    public function destroy(Request $request)
    {
        $bool = $this->repository->destroy($request->get('id'));
        if ($bool) {
            return $this->showMessage('操作成功');
        } else {
            return $this->showWarning("操作失败");
        }
    }

    /*
     * 添加到AI电话拨打列表
     * */
    public function addCallList(Request $request)
    {
        $thread_ids = $request->get('contact_ids');
        $ip = $request->get('ip');

        foreach ($thread_ids as $thread_id) {
            $thread = $this->repository->find($thread_id);
            if ($thread->contact()->count()) {
                $phone = $thread->contact->phone;
                $hasAdd = CallListModel::where('phone', $phone)->where('sync', 0)->count();
                if (!$hasAdd) {
                    CallListModel::create(['phone' => $phone, 'sync' => 0, 'ip' => $ip]);
                    ThreadsProgressModel::create(['threads_id' => $thread->id, 'remark' => '添加到AI电话列表']);
                }

            }
        }
        return 200;
    }

    /***
     * 导出我的线索
     * @param Request $request
     * @return int|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function export_threads(Request $request)
    {
        $type =  $request->get('type');
        if($type){
            return 200;
        }

        $thread_ids = $request->get('threads_ids');

        $threads = UserThreadsModel::whereIn('id', $thread_ids)->get();

        $fileds =$request->get('check_fields');

        return Excel::download(new ThreadsExport($threads, $fileds), '我的线索.xlsx');
    }
}