<?php


namespace app\wechat\service;


use app\model\MarketCustomer;
use app\model\MarketCustomerFollow;
use support\Db;
use support\exception\BusinessException;
use Tinywan\Jwt\JwtToken;

class FollowService
{
    /**
     * Notes: 添加跟进记录
     * User: yb
     * Date: 2024/8/13
     * Time: 11:26
     * @param $params
     */
    public static function add($params)
    {
        $consultantId = JwtToken::getCurrentId();
        //查询客户是否存在
        $where = [
            ['consultant_id', '=', $consultantId],
            ['id', '=', $params['market_customer_id']]
        ];
        $customInfo = MarketCustomer::where($where)->first();
        if (empty($customInfo)) {
            return json_fail('客户不存在');
        }
        $currentStatus = $customInfo->current_status;
        if ($currentStatus == -1) {
            return json_fail('无效客户,无法跟进');
        }
        if ($currentStatus == 1) {
            $visitTime = $customInfo->visit_time;
            $now = time();
            $start = strtotime($visitTime);
            $end = $start + CustomService::DIFF_TIME;
            if ($end < $now) {
                return json_fail('已失效,请重新添加客户信息');
            }
        }
        $insertData = [
            'market_customer_id' => $params['market_customer_id'],
            'consultant_id' => $consultantId,
            'visit_type' => $params['visit_type'],
            'intention_type' => $params['intention_type'],
            'follow_time' => strtotime($params['follow_time']),
            'follow_way' => $params['follow_way'],
            'follow_content' => $params['follow_content'],
            'created_at' => time()
        ];
        $result = false;
        Db::beginTransaction();
        try {
            if ($currentStatus == 1) {
                if ($insertData['visit_type'] == 2) {
                    $customInfo->current_status = 2;
                }
            }
            $customInfo->follow_num = $customInfo->follow_num + 1;
            $customInfo->level = $insertData['intention_type'];
            $customInfo->visit_time = $insertData['follow_time'];
            $customInfo->save();
            $result = MarketCustomerFollow::insert($insertData);
            Db::commit();
        }catch (BusinessException|\Exception $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        }
        if ($result) {
            return json_success('跟进成功');
        } else {
            return json_fail('跟进失败');
        }
    }

    /**
     * Notes: 跟进列表
     * User: yb
     * Date: 2024/8/13
     * Time: 15:56
     * @param $params
     */
    public static function index($params)
    {
        $page = $params['page'] ?? 1;
        $size = $params['size'] ?? 10;
        $ids = UserService::getIds();
        //查询顾问下的客户信息
        $customIds = [];
        if (!empty($ids)) {
            $customIds = MarketCustomer::whereIn('consultant_id', $ids)->pluck('id')->toArray();
        }
        $where = [
            [function($query) use ($customIds) {
            $query->whereIn('market_customer_id',$customIds);
            }]
        ];
        $whereCustom = [];
        $whereConsultant = [];
        if (!empty($params['market_customer_id'])) {
            $where[] = ['market_customer_id', '=', $params['market_customer_id']];
        }
        if (!empty($params['consultant_id'])) {
            $where[] = ['consultant_id', '=', $params['consultant_id']];
        }
        if (!empty($params['follow_way'])) {
            $where[] = ['follow_way', '=', $params['follow_way']];
        }
        if (!empty($params['follow_time'])) {
            $date = $params['follow_time'];
            $start = strtotime($date['start'].' 00:00:00');
            $end = strtotime($date['end'].' 23:59:59');
            $where[] = [function($query) use ($start, $end) {
                $query->whereBetween('follow_time', [$start, $end]);
            }];
        }
        if (!empty($params['custom'])) {
            $custom = $params['custom'];
            $whereCustom[] = [function($query) use ($custom) {
                $query->orWhere('name', 'like', "%{$custom}%")->orWhere('mobile', 'like', "%{$custom}%");
            }];
        }
        if (!empty($params['consultant'])) {
            $consultant = $params['consultant'];
            $whereConsultant[] = [function($query) use ($consultant) {
                $query->orWhere('name', 'like', "%{$consultant}%")->orWhere('mobile', 'like', "%{$consultant}%");
            }];
        }
        if (!empty($params['created_at'])) {
            $createdAt = $params['created_at'];
            if (is_array($createdAt)) {
                $createdAtStart = strtotime($createdAt[0]);
                $createdAtEnd = strtotime($createdAt[1]);
            } else {
                //本月开始和结束
                $createdAtStart = strtotime(date('Y-m-01 00:00:00'));
                $createdAtEnd = strtotime(date('Y-m-t 23:59:59'));
            }
            $where[] = [function($query) use ($createdAtStart,$createdAtEnd) {
                $query->whereBetween('created_at', [$createdAtStart, $createdAtEnd]);
            }];
        }
        $paginator = MarketCustomerFollow::with(['custom', 'consultant'])->whereHas('custom', function($query) use ($whereCustom){
            $query->where($whereCustom);
        })->whereHas('consultant', function($query) use ($whereConsultant) {
            $query->where($whereConsultant);
        })->where($where)->orderBy('follow_time', 'desc')->paginate($size, '*', 'page', $page);
        $total = $paginator->total();
        $items = $paginator->items();
        $data = [
            'total' => $total,
            'rows' => $items
        ];
        return json_success('success', $data);

    }

    /**
     * Notes: 跟进详情
     * User: yb
     * Date: 2024/8/13
     * Time: 16:50
     * @param $params
     */
    public static function info($id)
    {
        $info = MarketCustomerFollow::with(['custom', 'consultant'])->where('id', $id)->first();
        if (empty($info)) {
            return json_fail('跟进记录不存在');
        }
        if (!empty($info->custom->mobile)) {
            $mobile = $info->custom->mobile;
            $info->custom->mask_mobile = CustomService::handlePhone($mobile);
        }
        return json_success('请求成功', $info);
    }
}