<?php


namespace app\wechat\service;


use app\model\Consultant;
use app\model\MarketCustomer;
use app\model\MarketCustomerFollow;
use app\model\MarketCustomerLogs;
use app\wechat\validate\CustomValidate;
use support\Db;
use support\exception\BusinessException;
use Tinywan\Jwt\JwtToken;

class CustomService
{
    const DIFF_TIME = (60 * 60 * 24 * 30);
    /**
     * Notes: 选项配置
     * User: yb
     * Date: 2024/8/8
     * Time: 15:18
     * @return array
     */
    public static function config()
    {
        $options = MarketCustomer::config();
        if (isset($options['visit_type'])) {
            //如果存在拜访方式,直接在后台处理完成后返回前台
            foreach ($options['visit_type'] as $key => $val) {
                $data = [];
                foreach ($val as $index => $item) {
                    $data[] = ['text' => $item, 'value' => $index];
                }
                $options['visit_type'][$key] = $data;
            }
        }
        return $options;
    }

    /**
     * Notes: 客户列表
     * User: yb
     * Date: 2024/8/12
     * Time: 11:08
     * @param $params
     */
    public static function index($params)
    {
        $page = $params['page'] ?? 1;
        $size = $params['size'] ?? 10;
        //查询顾问信息
        $consultantId = JwtToken::getCurrentId();
        $consultantInfo = Consultant::firstWhere(['id' => $consultantId]);
        $deptId = $consultantInfo->dept_id;
        $type = $consultantInfo->type;
        $currentTime = time();
        $diffNums = self::DIFF_TIME;
        $where = [];
        $whereFollow = [];
        if ($type == 1) {
            //团队下所有的
            $deptIds = TeamService::getIds($deptId);
            $where[] = [function($query) use ($deptIds) {
                $query->whereIn('dept_id', $deptIds);
            }];
            if (!empty($params['consultant_id'])) {
                $where[] = ['consultant_id', '=', $params['consultant_id']];
                $whereFollow[] = ['consultant_id', '=', $params['consultant_id']];
            } else {
                $consultantIds = UserService::getIds(1);
                $whereFollow[] = [function($query) use ($consultantIds) {
                    $query->whereIn('consultant_id', $consultantIds);
                }];
            }

        } else {
            //个人的
            $where[] = ['consultant_id', '=', $consultantId];
            $whereFollow[] = ['consultant_id', '=', $consultantId];
        }
        if (!empty($params['custom'])) {
            $keywords = $params['custom'];
            $where[] = [function($query) use ($keywords) {
                $query->orWhere('name', 'like', "%{$keywords}%")->orWhere('mobile', 'like', "%{$keywords}%");
            }];
        }
        if (!empty($params['report_status'])) {
            if ($params['report_status'] == 1) {
                //已报备
                $where[] = [function($query) use ($diffNums, $currentTime) {
                    $query->whereRaw("((visit_time + {$diffNums}) - {$currentTime} > 0)")->where('current_status', '=', 1)->where('check_status', '=', 2);
                }];
            } else if ($params['report_status'] == 3) {
                //已锁定
                $where[] = [function($query) {
                    $query->whereIn('current_status', [2,3,4])->where('check_status', '=', 2);
                }];
            } else if ($params['report_status'] == 2) {
                //已失效
                $where[] = [function($query) use ($diffNums, $currentTime){
                    $query->orWhere('current_status', '=', -1)->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND current_status = 1)");
                }];
                $where[] = ['check_status', '=', 2];
            } else if ($params['report_status'] == '-1') {
                //待审核
                $where[] = ['check_status', '=', 1];
            }
        }
        if (!empty($params['check_status'])) {
            $where[] = ['check_status', '=', $params['check_status']];
        }
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        if (!empty($params['visit_time'])) {
            $datetime = $params['visit_time'];
            $startTime = strtotime($datetime['start'].' 00:00:00');
            $endTime = strtotime($datetime['end'].' 23:59:59');
            $where[] = [function($query) use ($startTime, $endTime) {
                $query->whereBetween('visit_time', [$startTime, $endTime]);
            }];
        }
        if (!empty($params['current_status'])) {
            $currentStatus = $params['current_status'];
            $where[] = [function($query) use ($currentStatus) {
                $query->where('current_status', $currentStatus)->where('check_status', 2);
            }];
        }
        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]);
            }];
        }
        $fn = function ($query) {
            $query->select('name', 'mobile', 'id');
        };
        $paginator = MarketCustomer::with(['consultant' => $fn])->where($where)->orderBy('visit_time', 'desc')->paginate($size, '*', 'page', $page);
        $total = $paginator->total();
        $items = $paginator->items();
        if (!empty($items)) {
            $now = time();
            foreach ($items as &$item) {
                $item->mask_mobile = self::handlePhone($item->mobile);
                $visitTimeInt = strtotime($item->visit_time);
                $endTime = $visitTimeInt + 60 * 60 * 24 * 30;
                $visitTimeInt = $endTime - $now;
                if ($visitTimeInt <= 0) {
                    $visitTimeInt = 0;
                }
                $item->visit_time_int = $visitTimeInt;
            }
        }
        //本日新增
        $date = date('Y-m-d');
        $start = strtotime($date.' 00:00:00');
        $end = strtotime($date.' 23:59:59');
        $newNums = MarketCustomer::where($where)->whereBetween('created_at', [$start, $end])->count();
        $followNums = MarketCustomerFollow::where($whereFollow)->whereBetween('created_at', [$start, $end])->count();
        $data = [
            'new_follow_num' => $followNums,
            'new_custom_num' => $newNums,
            'total' => $total,
            'rows' => $items
        ];
        return json_success('success', $data);


    }

    /**
     * Notes: 我的客户
     * User: yb
     * Date: 2024/8/13
     * Time: 15:14
     * @param $params
     */
    public static function myCustomList($params)
    {
        $page = $params['page'] ?? 1;
        $size = $params['size'] ?? 10;
        //查询有效顾问信息
        $consultantId = JwtToken::getCurrentId();
        $consultantInfo = Consultant::firstWhere(['id' => $consultantId]);
        $deptId = $consultantInfo->dept_id;
        $type = $consultantInfo->type;
        $where = [];
        if ($type == 1) {
            //团队下所有的
            $deptIds = TeamService::getIds($deptId);
            $where[] = [function($query) use ($deptIds) {
                $query->whereIn('dept_id', $deptIds);
            }];
        } else {
            //个人的
            $where[] = ['consultant_id', '=', $consultantId];
        }
        $where[] = ['check_status', '=', 2];
        $where[] = [function($query) {
            $query->orWhere(function ($query){
                $diffNums = (60 * 60 * 24 * 30);
                $currentTime = time();
                $query->whereRaw("((visit_time + {$diffNums}) - {$currentTime} > 0)")->where('current_status', '=', 1);
            })->orWhereIn('current_status', [2,3,4]);
        }];
        if (!empty($params['custom'])) {
            $keywords = $params['custom'];
            $where[] = [function($query) use ($keywords) {
                $query->orWhere('name', 'like', "%{$keywords}%")->orWhere('mobile', 'like', "%{$keywords}%");
            }];
        }
        $paginator = MarketCustomer::where($where)->orderBy('created_at', 'desc')->paginate($size, ['id','name','mobile','gender'], 'page', $page);
        $total = $paginator->total();
        $items = $paginator->items();
        if (!empty($items)) {
            foreach ($items as &$item) {
                $item->mask_mobile = self::handlePhone($item->mobile);
            }
        }
        $data = [
            'total' => $total,
            'rows' => $items
        ];
        return json_success('success', $data);
    }

    /**
     * Notes: 添加客户
     * User: yb
     * Date: 2024/8/6
     * Time: 11:20
     */
    public static function add($params)
    {
        $params = MarketCustomer::handleNumParams($params);
        $mobile = $params['mobile'];
        //查询客户手机号是否已经存在
        if (MarketCustomer::checkCustomExists($mobile)) {
            return json_fail('客户已经登记过了');
        }
        //查询顾问信息
        $consultantId = JwtToken::getCurrentId();
        $consultantInfo = Consultant::firstWhere(['id' => $consultantId]);
        if (empty($consultantInfo)) {
            return json_fail('顾问信息不存在');
        }
        $deptId = $consultantInfo->dept_id;
        $insertData = [
            'name' => $params['name'],
            'mobile' => $mobile,
            'consultant_id' => $consultantId,
            'dept_id' => $deptId,
            'gender' => $params['gender'] ?? null,
            'visit_type' => $params['visit_type'] ?? null,
            'require_area' => $params['require_area'] ?? null,
            'area' => $params['area'] ?? null,
            'requirement' => $params['requirement'] ?? null,
            'age_range' => $params['age_range'] ?? null,
            'focus' => $params['focus'] ?? null,
            'region' => $params['region'] ?? null,
            'purpose' => $params['purpose'] ?? null,
            'level' => $params['level'] ?? null,
            'type' => $params['type'] ?? null,
            'visit_time' => time(),
            'note' => $params['note'] ?? '',
            'check_status' => 1,
            'current_status' => $params['current_status'] ?? null,
            'created_at' => time()
        ];
        if ($insertData['type'] == 1) {
            $insertData['current_status'] = 1;
        } else if ($insertData['type'] == 2) {
            $insertData['current_status'] = 2;
        }
        Db::beginTransaction();
        try {
            $customId = MarketCustomer::insertGetId($insertData);
            Db::commit();
        }catch (BusinessException|\Exception $e){
            Db::rollBack();
            return json_fail($e->getMessage());
        }
        if ($customId) {
            return json_success('添加成功');
        } else {
            return json_fail('添加失败');
        }
    }

    /**
     * Notes: 编辑客户
     * User: yb
     * Date: 2024/8/12
     * Time: 10:23
     * @param $params
     * @return \support\Response
     */
    public static function edit($params)
    {
        $consultantId = JwtToken::getCurrentId();
        $params = MarketCustomer::handleNumParams($params);
        if (empty($params['id'])) {
            return json_fail('客户id不能为空');
        }
        $consultantInfo = Consultant::firstWhere(['id' => $consultantId]);
        if (empty($consultantInfo)) {
            return json_fail('顾问信息不存在');
        }
        $info = MarketCustomer::firstWhere(['id' => $params['id'], 'consultant_id' => $consultantId]);
        if (empty($info)) {
            return json_fail('客户信息不存在');
        }
        $updateData = [
            'name' => $params['name'],
            'gender' => $params['gender'] ?? null,
            'visit_type' => $params['visit_type'] ?? null,
            'require_area' => $params['require_area'] ?? null,
            'area' => $params['area'] ?? null,
            'requirement' => $params['requirement'] ?? null,
            'age_range' => $params['age_range'] ?? null,
            'focus' => $params['focus'] ?? null,
            'region' => $params['region'] ?? null,
            'purpose' => $params['purpose'] ?? null,
            'level' => $params['level'] ?? null,
            'type' => $params['type'] ?? null,
            'note' => $params['note'] ?? '',
            'updated_at' => time()
        ];
        if (empty($params['mobile'])) {
            return  json_fail('手机号不能为空');
        }
        $mobile = $params['mobile'];
        if (false === strpos($mobile,'****')) {
            //校验手机号格式
            $validate = new CustomValidate();
            if (!$validate->scene('phone')->check(['mobile' => $mobile])) {
                return  json_fail($validate->getError());
            }
            //修改手机号操作
            if (MarketCustomer::checkCustomExists($mobile, $params['id'])) {
                return json_fail('客户已经登记过了');
            }
            $updateData['mobile'] = $mobile;
        }
        $currentStatus = $info->current_status;
        if ($currentStatus == 1) {
            //已来电改为已到访
            if ($params['type'] == 2) {
                $updateData['current_status'] = 2;
            }
        }
        $result = false;
        Db::beginTransaction();
        try {
            $result = MarketCustomer::where('id', $params['id'])->update($updateData);
            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/8
     * Time: 15:36
     * @param $params
     */
    public static function info($id)
    {
        $customInfo = MarketCustomer::firstWhere(['id' => $id]);
        if (empty($customInfo)) {
            return json_fail('客户不存在');
        }
        //手机号加密处理
        $customInfo->mask_mobile = self::handlePhone($customInfo->mobile);
        //查询负责顾问
        $consultantName = Consultant::where('id', $customInfo->consultant_id)->value('name');
        $customInfo->consultant_name = $consultantName;
        //查询最新的跟进记录
        $follow = MarketCustomerFollow::where('market_customer_id', $id)->orderBy('created_at', 'desc')->first();
        $customInfo->follow = $follow;
        $focus = $customInfo->focus;
        if (!empty($focus)) {
            $customInfo->focus = explode(',', $focus);
        }
        return json_success('', $customInfo);
    }

    /**
     * Notes: 更新客户状态
     * User: yb
     * Date: 2024/8/14
     * Time: 13:23
     * @param $params
     */
    public static function updateStatus($params)
    {
        $customId = $params['id'];
        $currentStatus = $params['current_status'];
        if (!in_array($currentStatus, [-1, 3, 4])) {
            return json_fail('状态值非法');
        }
        $info = MarketCustomer::firstWhere(['id' => $customId]);
        if (empty($info)) {
            return json_fail('客户不存在');
        }
        $info->current_status = $currentStatus;
        $result = $info->save();
        if ($result) {
            return json_success('更新成功');
        } else {
            return json_fail('更新失败');
        }
    }

    /**
     * Notes: 转移客户
     * User: yb
     * Date: 2024/8/7
     * Time: 14:27
     * @param $params
     */
    public static function moveCustom($params)
    {
        $userId = JwtToken::getCurrentId();
        //获取绑定的管理信息
        $userInfo = Consultant::firstWhere(['id' => $userId]);
        if (empty($userInfo)) {
            return json_fail('管理员信息不存在');
        }
        if ($userInfo->type != 1) {
            return json_fail('操作权限不足');
        }
        $relationUserId = $userInfo->relation_user_id;

        $currentConsultantId = $params['consultant_id']; //当前顾问
        $consultantId = $params['move_consultant_id'] ?? 0;
        $customId = $params['move_market_customer_id'] ?? 0;
        $note = $params['note'] ?? '';
        $consultantInfo = Consultant::firstWhere(['id' => $currentConsultantId]);
        if (empty($consultantInfo)) {
            return json_fail('接收成员不存在');
        }
        $currentDeptId = $consultantInfo->dept_id; //当前部门
        $logsInertData  = [];
        $now = time();
        $whereCustom = [];
        if (!empty($customId)) {
            $whereCustom[] = ['id', '=', $customId];
        }
        if (!empty($consultantId)) {
            $whereCustom[] = ['consultant_id', '=', $consultantId];
        }
        $customList = MarketCustomer::where($whereCustom)->select(['id','consultant_id','dept_id'])->get();
        if (!$customList->isEmpty()) {
            foreach ($customList as$item) {
                $logsInertData[] = [
                    'market_customer_id' => $item->id,
                    'consultant_id' => $currentConsultantId,
                    'dept_id' => $currentDeptId,
                    'before_consultant_id' => $item->consultant_id,
                    'before_dept_id' => $item->dept_id,
                    'note' => $note,
                    'change_user_id' => $relationUserId,
                    'change_consultant_id' => $userId,
                    'created_at' => $now
                ];
            }
        }
        if ($customList->isEmpty()) {
            return json_fail('成员没有客户记录');
        }
        if (empty($logsInertData)) {
            return json_fail('移交记录不能为空');
        }
        Db::beginTransaction();
        $result = false;
        try {
            foreach ($customList as $item) {
                $item->consultant_id = $currentConsultantId;
                $item->dept_id = $currentDeptId;
                $item->save();
            }
            $result = MarketCustomerLogs::insert($logsInertData);
            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/7
     * Time: 15:33
     * @param $params
     */
    public static function moveLogs($params)
    {
        $page = $params['page'] ?? 1;
        $size = $params['size'] ?? 10;
        $where = [];
        if (!empty($params['custom_id'])) {
            $where[] = ['market_customer_id', '=', $params['custom_id']];
        }
        $selectFn = function ($query){
            $query->select('name', 'mobile', 'id');
        };
        $paginator = MarketCustomerLogs::with(['custom' => $selectFn, 'beforeMan' => $selectFn, 'currentMan' => $selectFn])
            ->where($where)
            ->orderBy('created_at', '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/16
     * Time: 11:21
     * @param $params
     */
    public static function checkCustom($params)
    {
        $userId = JwtToken::getCurrentId();
        $adminId = Consultant::where('id', '=', $userId)->value('relation_user_id');
        //查询客户是否已经存在
        $customId = $params['id'];
        $checkStatus = $params['check_status'];
        if (!in_array($checkStatus, [-1,2])) {
            return json_fail('状态值非法');
        }
        $info = MarketCustomer::firstWhere(['id' => $customId]);
        if (empty($info)) {
            return json_fail('客户不存在');
        }
        $status = $info->check_status;
        if ($status != 1) {
            return json_fail('客户不是待审核状态');
        }
        $mobile = $info->mobile;
        if ($checkStatus == 2) {
            if (MarketCustomer::checkCustomExists($mobile)) {
                return json_fail('客户已经存在');
            }
        }
        $result = false;
        Db::beginTransaction();
        try {
            $info->check_status = $checkStatus;
            if ($checkStatus == -1) {
                //拒绝录入拒绝理由
                $info->check_note = $params['note'] ?? '无拒绝理由';
            }
            $info->check_time = time();
            $info->check_admin_id = $adminId;
            $info->check_consultant_id = $userId;
            $result = $info->save();
            if ($checkStatus == 2) {
                //将其他待审的相同手机号的改拒绝
                $where = [
                    ['mobile' , '=', $mobile],
                    ['check_status', '=', 1],
                    ['id', '<>', $customId]
                ];
                MarketCustomer::where($where)->update(['check_time' => time(),'check_status' => -1,'check_note' => '客户已经被其他顾问报备']);
            }
            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/21
     * Time: 9:40
     * @param $params
     * @return \support\Response
     */
    public static function checkPhone($params)
    {
        if (empty($params['mobile'])) {
            return json_fail('请输入联系电话');
        }
        $mobile = $params['mobile'];
        //添加和编辑
        if (!empty($params['id'])) {
            //编辑的情况
            if (false === strpos($mobile,'****')) {
                //校验手机号格式
                $validate = new CustomValidate();
                if (!$validate->scene('phone')->check(['mobile' => $mobile])) {
                    return  json_fail($validate->getError());
                }
                //修改手机号操作
                if (MarketCustomer::checkCustomExists($mobile, $params['id'])) {
                    return json_fail('客户已经登记过了');
                }
            }
            return json_success('请求成功',['is_ex' => 2]);
        } else {
            $validate = new CustomValidate();
            if (!$validate->scene('phone')->check(['mobile' => $mobile])) {
                return  json_fail($validate->getError());
            }
            //添加
            $result = MarketCustomer::checkCustomExists($mobile);
            if ($result) {
                $isEx = 1;
            } else {
                $isEx = 2;
            }
            return json_success('请求成功',['is_ex' => $isEx]);
        }
    }

    /**
     * Notes: 对手机号加密处理
     * User: yb
     * Date: 2024/8/8
     * Time: 15:41
     * @param $val
     * @return string|string[]
     */
    public static function handlePhone($val)
    {
        return substr_replace($val, '****', 3, 4);
    }

    /**
     * Notes: 处理拜访时间
     * User: yb
     * Date: 2024/8/8
     * Time: 16:06
     * @param $val
     * @return float|int
     */
    protected static function handleVisitTime($val) {
        return (strtotime($val) * 1000);
    }
}