<?php

namespace App\Services\Operation;

use Illuminate\Database\Eloquent\Model;
use App\Models\Operation\Business;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Operation\BusinessValidator;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Support\Facades\Request;

class BusinessService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new Business();
        $this->mainValidator = new BusinessValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function searchPage($user_info, $search_data, $show_count = 10, $field_columns = [])
    {
        // 判断是否传入查询字段
        if (empty($field_columns)) {
            // 查询字段
            $field_columns = ['bucl_id', 'bucl_name', 'bucl_address', 'bucl_user_phone', 'bucl_user_name', 'bucl_create_id', 'bucl_create_time', 'bucl_update_id', 'bucl_update_time', 'bucl_state', 'bucl_province', 'bucl_city', 'bucl_county'];
        }
        // 企业客户管理表
        $list_data = DB::table('business_client as bucl')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'bucl.bucl_create_id')
            ->leftJoin('business_account as buac', 'buac.buac_bucl_id', '=', 'bucl.bucl_id')
            ->where('bucl_cid', $user_info->adm_cid)
            ->where('bucl_shop_id', $user_info->adm_shop_id)
            ->where('bucl_del', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bucl_name'])) {
                    $query->where('bucl_name', 'like', '%' . $search_data['bucl_name'] . '%')
                        ->orwhere('bucl_user_name', 'like', '%' . $search_data['bucl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bucl_user_phone'])) {
                    $query->where('bucl_user_phone', 'like', '%' . $search_data['bucl_user_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bucl_state'])) {
                    $query->where('bucl_state', $search_data['bucl_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['buac_phone'])) {
                    $query->where('buac_phone', 'like', '%' . $search_data['buac_phone'] . '%');
                }
            })
            ->select($field_columns)
            ->groupBy('bucl_id')
            ->orderBy('bucl_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $bucl_create_id = array_unique(array_column($list_items, 'bucl_create_id')); //创建人id
            $bucl_update_id = array_unique(array_column($list_items, 'bucl_update_id')); //创建人id
            $adm_id_merge = array_merge($bucl_create_id, $bucl_update_id);
            // 查询人员信息
            $find_adm = DB::table('admin')
                ->whereIn('adm_id', $adm_id_merge)
                ->pluck('adm_name', 'adm_id')->toArray();
            foreach ($list_items as $key => $value) {
                // 创建人
                if ($value->bucl_create_id && isset($find_adm[$value->bucl_create_id])) {
                    $list_items[$key]->bucl_create_name = $find_adm[$value->bucl_create_id];
                } else {
                    $list_items[$key]->bucl_create_name = '';
                }
                // 更新人
                if ($value->bucl_update_id && isset($find_adm[$value->bucl_update_id])) {
                    $list_items[$key]->bucl_update_name = $find_adm[$value->bucl_update_id];
                } else {
                    $list_items[$key]->bucl_update_name = '';
                }
                $list_items[$key]->account_num = DB::table('business_account')
                    ->where('buac_bucl_id', $value->bucl_id)
                    ->where('buac_del', 1)
                    ->select('buac_id')
                    ->count();
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        return $data;
    }

    // 账号列表
    public function accIndex($user_info, $search_data, $show_count = 10, $field_columns = [])
    {
        // 判断是否传入查询字段
        if (empty($field_columns)) {
            // 查询字段
            $field_columns = ['buac_id', 'buac_name', 'buac_phone', 'buac_create_time', 'buac_create_adm_id'];
        }
        // 企业客户管理表
        $list_data = DB::table('business_account')
            ->where('buac_shop_id', $user_info->adm_shop_id)
            ->where('buac_bucl_id', $search_data['bucl_id'])
            ->where('buac_del', 1)
            ->select($field_columns)
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $buac_create_adm_id = array_unique(array_column($list_items, 'buac_create_adm_id')); //创建人id
            // 查询人员信息
            $find_adm = DB::table('admin')
                ->whereIn('adm_id', $buac_create_adm_id)
                ->pluck('adm_name', 'adm_id')->toArray();
            foreach ($list_items as $key => $value) {
                // 创建人
                if ($value->buac_create_adm_id) {
                    $list_items[$key]->buac_create_adm_name = isset($find_adm[$value->buac_create_adm_id]) ? $find_adm[$value->buac_create_adm_id]:'';
                } else {
                    $list_items[$key]->buac_create_adm_name = '';
                }
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        return $data;
    }

    /**
     * 检查是不是存在同名内容
     * @param $name 考核项名称
     * @param $type 类型：1施工部位2整车3其他
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function nameExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            return Business::where('bucl_name', $request['bucl_name'])
                ->where('bucl_shop_id', $user_info->adm_shop_id)
                ->where('bucl_del', 1)
                ->exists();
        } else {
            return Business::where('bucl_name', $request['bucl_name'])
                ->where('bucl_shop_id', $user_info->adm_shop_id)
                ->where('bucl_del', 1)
                ->where('bucl_id', '<>', $id)
                ->exists();
        }
    }

    /**
     * 检查是不是存在相同手机号
     */
    public static function phoneExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            $find_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_bucl_id', $request['bucl_id'])
                ->where('buac_del', 1)
                ->exists();
            if ($find_buac_data) { //本单位存在手机号
                return 1;
            }
            $find_all_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_del', 1)
                ->exists();
            if ($find_all_buac_data) { //其他单位存在此手机号
                return 2;
            } else {
                return 3;
            }
        } else {
            $find_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_bucl_id', $request['bucl_id'])
                ->where('buac_id', '<>', $id)
                ->where('buac_del', 1)
                ->exists();
            if ($find_buac_data) { //本单位存在手机号
                return 1;
            }
            $find_all_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_id', '<>', $id)
                ->where('buac_del', 1)
                ->exists();
            if ($find_all_buac_data) { //其他单位存在此手机号
                return 2;
            } else {
                return 3;
            }
        }
    }

    // 新增
    public static function add($user_info, $request)
    {
        $data['bucl_cid'] = $user_info->adm_cid;
        $data['bucl_shop_id'] = $user_info->adm_shop_id;
        $data['bucl_create_id'] = $user_info->adm_id;
        $data['bucl_update_id'] = $user_info->adm_id;
        $data['bucl_name'] = $request['bucl_name']; //企业客户名称
        $data['bucl_user_phone'] = $request['bucl_user_phone']??''; //联系人电话
        $data['bucl_user_name'] = $request['bucl_user_name']??''; //联系人名称
        $data['bucl_create_time'] = date('Y-m-d H:i:s');
        $data['bucl_update_time'] = date('Y-m-d H:i:s');
        $data['bucl_province'] = isset($request['bucl_province']) ? $request['bucl_province'] : ''; //省
        $data['bucl_city'] = isset($request['bucl_city']) ? $request['bucl_city'] : ''; //市
        $data['bucl_county'] = isset($request['bucl_county']) ? $request['bucl_county'] : ''; //县
        $data['bucl_address'] = isset($request['bucl_address']) ? $request['bucl_address'] : ''; //详细地址
        if (isset($request['bucl_bind_shop_id'])) {
            $data['bucl_bind_shop_id'] = $request['bucl_bind_shop_id']; //绑定门店id
            $data['bucl_bind_shop_code'] = $request['bucl_bind_shop_code']; //编码
            $find_shop = DB::table('shop')
                ->where('shop_id', $request['bucl_bind_shop_id'])
                ->first();
            if (empty($find_shop)) {
                return false;
            }
            $find_channel = DB::table('channel_unit')
                ->where('chun_shop_id', $request['bucl_bind_shop_id'])
                ->where('chun_shop_fid', $user_info->adm_shop_id)
                ->first();
            if (empty($find_channel)) {
                $chun_add_data['chun_cid'] = 1;
                $chun_add_data['chun_name'] = $find_shop->shop_name;
                $chun_add_data['chun_phone'] = $find_shop->shop_phone;
                $chun_add_data['chun_shop_id'] = $request['bucl_bind_shop_id'];
                $chun_add_data['chun_superior_shop_id'] = $request['bucl_bind_shop_id'];
                $chun_add_data['chun_adm_id'] = empty($request['chun_adm_id']) ? 0 : $request['chun_adm_id'];
                $chun_add_data['chun_search_letter'] = empty($request['chun_search_letter']) ? '' : $request['chun_search_letter'];
                $chun_add_data['chun_unit_name'] = empty($find_shop->shop_store_name) ? '' : $find_shop->shop_store_name;
                $chun_add_data['chun_state'] = 1;
                //$chun_add_data['chun_payment_way'] = 2; //结算方式1.账期 2.现结
                $chun_add_data['chun_province'] = empty($find_shop->shop_province) ? '' : $find_shop->shop_province;
                $chun_add_data['chun_city'] = empty($find_shop->shop_city) ? '' : $find_shop->shop_city;
                $chun_add_data['chun_county'] = empty($find_shop->shop_county) ? '' : $find_shop->shop_county;
                $chun_add_data['chun_address'] = empty($find_shop->shop_address) ? '' : $find_shop->shop_address;
                $chun_add_data['chun_payment_way'] = 1;//结算方式
                $chun_add_data['chun_delivertype'] = 1;//交货方式
                $chun_add_data['chun_invoicetype'] = 1;//票据类型

                $chun_add_data['chun_shop_fid'] = $user_info->adm_shop_id;//上级门店
                $chun_fshop_code = DB::table('shop')
                    ->where('shop_id',$chun_add_data['chun_shop_fid'])
                    ->value('shop_code');
                $chun_add_data['chun_fshop_code'] = $chun_fshop_code;//上级门店编码
                $chun_res =  DB::table('channel_unit')->insertGetId($chun_add_data);

                $chin_data[0]['key'] = $find_shop->shop_name; //名称
                $chin_data[0]['value'] = $find_shop->shop_phone; //内容
                $chin_data[0]['default'] = 1; //是否默认
                $chin_add_data['chin_data'] = json_encode($chin_data);
                $chin_add_data['chin_chun_id'] = $chun_res;
                $chin_add_data['chin_remarks'] = !empty($request['chin_remarks']) ? $request['chin_remarks'] : ''; //备注
                $chin_add_data['chin_owe_day'] = !empty($request['chin_owe_day']) ? $request['chin_owe_day'] : 0;
                $chin_add_data['chin_owe_money'] = !empty($request['chin_owe_money']) ? $request['chin_owe_money'] : 0;
                $chin_add_data['chin_caution_day'] = !empty($request['chin_caution_day']) ? $request['chin_caution_day'] : 0;
                // 将百度经纬度 转化为高德经纬度
                $chin_add_data['chin_longitude'] = empty($find_shop->shop_longitude) ? '' : $find_shop->shop_longitude; //经度
                $chin_add_data['chin_latitude'] = empty($find_shop->shop_latitude) ? '' : $find_shop->shop_latitude; //维度
                $chin_add_data['chin_caution_money'] = 0; //警示金额
                $chin_res =  DB::table('channel_info')->insert($chin_add_data);
            }
        }
        $bucl_id = Business::insertGetId($data);
        $password = md5('123456' . 'faster123456');
        if ($request['bucl_user_name'] || $request['bucl_user_phone']) {
            $new_data['buac_cid'] = $user_info->adm_cid;
            $new_data['buac_shop_id'] = $user_info->adm_shop_id;
            $new_data['buac_create_adm_id'] = $user_info->adm_id;
            $new_data['buac_bucl_id'] = $bucl_id; //企业客户id
            $new_data['buac_name'] = $request['bucl_user_name']??''; //企业客户名称
            $new_data['buac_phone'] = $request['bucl_user_phone']??''; //联系人电话
            $new_data['buac_password'] = $password; //密码
            $new_data['buac_create_time'] = date('Y-m-d H:i:s');
            DB::table('business_account')->insertGetId($new_data);
        }

        return $bucl_id;
    }

    // 新增账号
    public static function addAccount($user_info, $request)
    {
        $password = md5($request['buac_password'] . 'faster123456');
        $data['buac_cid'] = $user_info->adm_cid;
        $data['buac_shop_id'] = $user_info->adm_shop_id;
        $data['buac_create_adm_id'] = $user_info->adm_id;
        $data['buac_bucl_id'] = $request['bucl_id']; //企业客户id
        $data['buac_name'] = $request['buac_name']; //企业客户名称
        $data['buac_phone'] = $request['buac_phone']; //联系人电话
        $data['buac_sex'] = $request['buac_sex']; //联系人电话
        $data['buac_password'] = $password; //密码
        $data['buac_create_time'] = date('Y-m-d H:i:s');
        return DB::table('business_account')->insertGetId($data);
    }

    // 编辑
    public static function edit($user_info, $request)
    {
        $data['bucl_cid'] = $user_info->adm_cid;
        $data['bucl_shop_id'] = $user_info->adm_shop_id;
        $data['bucl_create_id'] = $user_info->adm_id;
        $data['bucl_update_id'] = $user_info->adm_id;
        $data['bucl_name'] = $request['bucl_name']; //企业客户名称
        $data['bucl_user_phone'] = $request['bucl_user_phone']; //联系人电话
        $data['bucl_user_name'] = $request['bucl_user_name']; //联系人名称
        $data['bucl_update_time'] = date('Y-m-d H:i:s');
        $data['bucl_province'] = isset($request['bucl_province']) ? $request['bucl_province'] : ''; //省
        $data['bucl_city'] = isset($request['bucl_city']) ? $request['bucl_city'] : ''; //市
        $data['bucl_county'] = isset($request['bucl_county']) ? $request['bucl_county'] : ''; //县
        $data['bucl_address'] = isset($request['bucl_address']) ? $request['bucl_address'] : ''; //详细地址
        return Business::where('bucl_id', $request['bucl_id'])->update($data);
    }

    // 删除企业
    public static function busdelete($ids)
    {
        // 删除企业下的会员
        $acc_data['buac_del'] = 2;
        $acc_update_res = DB::table('business_account')
            ->where('buac_bucl_id', $ids)
            ->update($acc_data);
        $data['bucl_del'] = 2;
        $data['bucl_update_time'] = date('Y-m-d H:i:s');
        $bucl_update_res = DB::table('business_client')->where('bucl_id', $ids)
            ->update($data);
        if ($acc_update_res && $acc_update_res) {
            return true;
        } else {
            return false;

        }
    }


    // 删除账号
    public static function accdelete($ids)
    {
        $data['buac_del'] = 2;
        return DB::table('business_account')->where('buac_id', $ids)
            ->update($data);
    }

    // 更改状态
    public static function editState($ids, $state)
    {
        $data['bucl_state'] = $state;
        $data['bucl_update_time'] = date('Y-m-d H:i:s');
        return Business::whereIn('bucl_id', $ids)
            ->update($data);
    }


    /**
     * 获取全部level
     * @param array $ids 从id数组中找
     * @param int $refresh 强制读数据库并更新redis缓存
     *
     * @return mixed
     */
    public static function getAll($ids = [], $refresh = 0)
    {
        $cacheKey = 'technical_level';
        $data = [];
        if ($refresh == 1) {
            goto NOCACHE;
        }
        $cacheExist = Cache::has($cacheKey);
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get($cacheKey);
            if (!empty($ids)) {
                foreach ($ids as $val) {
                    $data[$val] = $itemList[$val];
                }
            }
        } else {
            NOCACHE:
            $itemList = [];
            $itemData = static::getShopData();
            foreach ($itemData as $k => $val) {
                if ($ids && in_array($val['grle_id'], $ids)) {
                    $data[$val['grle_id']] = $val;
                }
                $itemList[$val['grle_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME + rand(0, 10)); //防止缓存雪崩
        }

        return !empty($ids) ? $data : $itemList;
    }

    /**
     * [getFieldsByIdAll 根据id查询数据]
     * @param  [object] $user_info [用户信息]
     * @param  [array] $ids       [数组，id]
     * @param  array $fields    [数组，查询字段]
     * @return [type]            [description]
     */
    public static function getFieldsByIdAll($user_info, $ids, $fields = '*')
    {
        $entity = Business::where('bucl_id', $ids)
            ->where('bucl_shop_id', $user_info->adm_shop_id)
            ->where('bucl_del', 1)
            ->select($fields)
            ->get()->toArray();
        return $entity;
    }

    /**
     * 获取某个level
     *
     * @param int $ID
     *
     * @return mixed
     */
    public static function getByID(int $ID)
    {
        $cacheKey = 'technical_level';
        $cacheExist = Cache::has($cacheKey);
        $data = [];
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get($cacheKey);
            foreach ($itemList as $key => $val) {
                if ($val['vacm_id'] = $ID) {
                    return $val;
                }
            }
        } else {
            $itemList = [];
            $itemData =  static::getShopData();
            foreach ($itemData as $key => $val) {
                if ($val['vacm_id'] = $ID) {
                    $data = $val;
                }
                $itemList[$val['vacm_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME + rand(0, 10)); //防止缓存雪崩
        }

        return $data;
    }

    /**
     * 修改保险公司员工停启用
     */
    public static function editAccState($request){
        $data['buac_state'] = $request['state'];
        $data['buac_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('business_account')->where('buac_id', $request['buac_id'])->update($data);
        return $res;
    }
}
