<?php

namespace App\Http\Controllers\Api\ChannelManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\ChannelManage\VerifyChannelUnitController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Http\Controllers\Api\YongYou\YongYouController;
use app\Models\ChannelUnit;
use App\Http\Models\Api\Export;
use App\Http\Models\Services\PublicSearch;
use App\Http\Models\Services\ChannelManage\ChannelUnit as ChannelUnitServices;

// 运营系统 -- 客户单位
class ChannelUnitController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $page_size  = (int) $request->input('show_count', 10);
        $list_data = DB::table('channel_unit as u')
            ->leftjoin('channel_info as i', 'u.chun_id', '=', 'i.chin_chun_id')
            ->where('u.chun_cid', $user_info->adm_cid)
            ->where('u.chun_superior_shop_id', $shop_id)
            ->where('u.chun_state', '<>', 3)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('chun_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('chun_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('chun_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_search_letter'])) {
                    $query->where('u.chun_search_letter', 'like', '%' . $search_data['chun_search_letter'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_unit_name'])) {
                    $query->where('u.chun_unit_name', 'like', '%' . $search_data['chun_unit_name'] . '%')
                        ->orwhere('u.chun_search_letter', 'like', '%' . $search_data['chun_unit_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_name'])) {
                    $query->where('u.chun_name', 'like', '%' . $search_data['chun_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_phone'])) {
                    $query->where('u.chun_phone', 'like', '%' . $search_data['chun_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_payment_way'])) {
                    $query->where('u.chun_payment_way', $search_data['chun_payment_way']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_state'])) {
                    $query->where('u.chun_state', $search_data['chun_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_adm_id'])) {
                    $query->where('chun_adm_id', $search_data['chun_adm_id']);
                }
            }) //业务员id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chin_remarks'])) {
                    $query->where('chin_remarks', 'like', '%' . $search_data['chin_remarks'] . '%');
                }
            }) //备注
            ->select('u.chun_id', 'u.chun_search_letter', 'u.chun_unit_name', 'u.chun_name', 'u.chun_phone', 'u.chun_state', 'u.chun_payment_way', 'u.chun_delivertype', 'u.chun_invoicetype', 'u.chun_province', 'u.chun_city', 'u.chun_county', 'u.chun_address', 'u.chun_img', 'i.chin_level', 'i.chin_main_brand', 'i.chin_second_brand', 'i.chin_owe_day', 'i.chin_owe_money', 'i.chin_data', 'i.chin_type', 'i.chin_caution_day', 'i.chin_type', 'i.chin_prec_id', 'i.chin_remarks', 'chun_class', 'chun_adm_id')
            ->orderBy('u.chun_id', 'desc')
            ->paginate($page_size);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        $prec_id = []; //业务划区id
        $adm_id = [];
        //结算方式对应关系
        $unit_data_list = ChannelUnitServices::getPaymentWayName(1,true);
        //交货方式对应关系
        $unit_deliver_type = ChannelUnitServices::getDeliverTypeName(true);
        //票据类型对应关系
        $unit_invoice_type = ChannelUnitServices::getInvoiceTypeName(true);
        foreach ($data_info['data'] as $key => $value) {
            $prec_id[] = $value->chin_prec_id;
            $adm_id[] = $value->chun_adm_id;
            $data_info['data'][$key]->chun_payment_way_name = empty($value->chun_payment_way) ? '' : $unit_data_list[$value->chun_payment_way];
            $data_info['data'][$key]->chun_delivertype_name = empty($value->chun_delivertype) ? '' : $unit_deliver_type[$value->chun_delivertype];
            if($value->chun_invoicetype == ''){
                $data_info['data'][$key]->chun_invoicetype_name = '';
            }else{
                $data_info['data'][$key]->chun_invoicetype_name = $unit_invoice_type[$value->chun_invoicetype];
            }

        }
        // 业务划区
        $prec_data = DB::table('precincts')
            ->whereIn('prec_id', $prec_id)
            ->get(['prec_id', 'prec_name']);
        // 业务员
        $adm_data = DB::table('admin')
            ->whereIn('adm_id', $adm_id)
            ->select('adm_id', 'adm_name')
            ->get();
        $data_info['prec_data'] = $prec_data; //业务划区
        $data_info['adm_data'] = $adm_data; //业务员

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 搜索业务员
    public function searchSalesman(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        $list_data = DB::table('admin as a')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->where('asr.shop_cid', $user_info->adm_cid)
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->where('asr.adm_state', 1)
            ->whereIn('asr.adm_shop_leave', [4, 5])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('a.adm_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            }) //创建时间
            ->select('a.adm_id', 'a.adm_name', 'a.adm_phone')
            ->orderBy('a.adm_id', 'desc')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'error', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1. 判断客户单位名称是否存在
        $find_chun = DB::table('channel_unit')
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->where('chun_unit_name', $request['chun_unit_name'])
            ->first(['chun_id']);
        if ($find_chun) {
            return response()->json(['code'=>500, 'msg'=>'供应商名称已存在', 'data'=>'error']);
        }
        DB::beginTransaction();
        
        // 2 新增一个客户单位
        // 联系人电话json数据
        if (!empty($request['info_name'])) {
            // 处理联系人属性数组数据
            foreach ($request['info_name'] as $key => $value) {
                if (empty($value) || empty($request['info_content'][$key])) {
                    return response()->json(['code'=>500, 'msg'=>'信息项存在空项', 'data'=>'error']);
                }
                $chin_data[$key]['key'] = $value; //名称
                $chin_data[$key]['value'] = $request['info_content'][$key]; //内容
                $chin_data[$key]['default'] = $request['info_default'][$key]; //是否默认
                if ($chin_data[$key]['default'] == 1) {
                    $chun_add_data['chun_name'] = $value;
                    $chun_add_data['chun_phone'] = $request['info_content'][$key];
                }
            }
            $chin_add_data['chin_data'] = json_encode($chin_data);
        }
        $chun_add_data['chun_cid'] = $user_info->adm_cid;
        $chun_add_data['chun_shop_id'] = $user_info->adm_shop_id;
        $chun_add_data['chun_superior_shop_id'] = $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($request['chun_unit_name']) ? '' : $request['chun_unit_name'];
        $chun_add_data['chun_state'] = 1;
        //$chun_add_data['chun_payment_way'] = 2; //结算方式1.账期 2.现结
        $chun_add_data['chun_province'] = empty($request['chun_province']) ? '' : $request['chun_province'];
        $chun_add_data['chun_city'] = empty($request['chun_city']) ? '' : $request['chun_city'];
        $chun_add_data['chun_county'] = empty($request['chun_county']) ? '' : $request['chun_county'];
        $chun_add_data['chun_address'] = empty($request['chun_address']) ? '' : $request['chun_address'];
        $chun_add_data['chun_payment_way'] = $request['chun_payment_way'];//结算方式
        $chun_add_data['chun_delivertype'] = $request['chun_delivertype'];//交货方式
        $chun_add_data['chun_invoicetype'] = $request['chun_invoicetype'];//票据类型

        if ($request['chun_img']) {
            $chun_add_data['chun_img'] = uploadBase64Img($request['chun_img']); //调用全局函数 上传门面图片
        }
        if ($request['chun_shop_fid']) {
            $chun_add_data['chun_shop_fid'] = $request['chun_shop_fid'];//上级门店
            $chun_fshop_data = DB::table('shop')
                ->where('shop_id',$request['chun_shop_fid'])
                ->first();
            $chun_add_data['chun_fshop_code'] = $chun_fshop_data->shop_code;//上级门店编码

            $data['bucl_cid'] = 1;
            $data['bucl_shop_id'] = $request['chun_shop_fid'];
            $data['bucl_bind_shop_id'] = $user_info->adm_shop_id;
            $data['bucl_bind_shop_code'] = DB::table('shop')->where('shop_id', $user_info->adm_shop_id)->value('shop_code');
            $data['bucl_create_id'] = 0;
            $data['bucl_update_id'] = 0;
            $data['bucl_name'] = $chun_fshop_data->shop_store_name; //企业客户名称
            $data['bucl_user_phone'] = $chun_fshop_data->shop_phone; //联系人电话
            $data['bucl_user_name'] = $chun_fshop_data->shop_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($chun_fshop_data->shop_province) ? $chun_fshop_data->shop_province : ''; //省
            $data['bucl_city'] = isset($chun_fshop_data->shop_city) ? $chun_fshop_data->shop_city : ''; //市
            $data['bucl_county'] = isset($chun_fshop_data->shop_county) ? $chun_fshop_data->shop_county : ''; //县
            $data['bucl_address'] = isset($chun_fshop_data->shop_address) ? $chun_fshop_data->shop_address : ''; //详细地址
            $bucl_id = DB::table('business_client')->insertGetId($data);
            $password = md5('123456' . 'faster123456');
            $new_data['buac_cid'] = 1;
            $new_data['buac_shop_id'] = $request['chun_shop_fid'];
            $new_data['buac_create_adm_id'] = 0;
            $new_data['buac_bucl_id'] = $bucl_id; //企业客户id
            $new_data['buac_name'] = $chun_fshop_data->shop_name; //企业客户名称
            $new_data['buac_phone'] = $chun_fshop_data->shop_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);
        }
        $chun_res =  DB::table('channel_unit')->insertGetId($chun_add_data);

        $chin_add_data['chin_chun_id'] = $chun_res;
        // $chin_add_data['chin_level'] = $request['chin_level']; //客户等级
        // $chin_add_data['chin_prec_id'] = !empty($request['chin_prec_id']) ? $request['chin_prec_id'] : ''; //业务划区id
        $chin_add_data['chin_remarks'] = !empty($request['chin_remarks']) ? $request['chin_remarks'] : ''; //备注
        // $chin_add_data['chin_main_brand'] = $request['chin_main_brand'] ? $request['chin_main_brand'] : ''; //主营品牌
        // $chin_add_data['chin_second_brand'] = $request['chin_second_brand'] ? $request['chin_second_brand'] : ''; //次营品牌
        $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;
        // 将百度经纬度 转化为高德经纬度
        // $lat_lon = Common::convert($request['chin_latitude'], $request['chin_longitude']);
        // $chin_add_data['chin_longitude'] = $lat_lon['lng'];//经度
        // $chin_add_data['chin_latitude'] = $lat_lon['lat'];//维度
        $chin_add_data['chin_longitude'] = !empty($request['chin_longitude']) ? $request['chin_longitude'] : ''; //经度
        $chin_add_data['chin_latitude'] = !empty($request['chin_latitude']) ? $request['chin_latitude'] : ''; //维度
        $chin_add_data['chin_caution_money'] = !empty($request['chin_caution_money']) ? $request['chin_caution_money'] : 0; //警示金额
        $chin_res =  DB::table('channel_info')->insert($chin_add_data);
        
        if ($chun_res && $chin_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '供应商', '新增', '新增供应商：' . $request['chun_unit_name'] . '成功');
            $return_data['chun_id'] =  $chun_res;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增供应商成功', 'return_data'=>$return_data]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'新增供应商失败', 'data'=>'error']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if ($request['type'] == 1) { //获取页面数据
            $list_data = DB::table('channel_unit as u')
                ->leftjoin('channel_info as i', 'u.chun_id', '=', 'i.chin_chun_id')
                ->where('u.chun_cid', $user_info->adm_cid)
                ->where('u.chun_superior_shop_id', $shop_id)
                ->where('u.chun_id', $request['chun_id'])
                ->select('u.chun_id', 'u.chun_search_letter', 'u.chun_unit_name', 'u.chun_name', 'u.chun_phone', 'u.chun_state', 'u.chun_payment_way', 'u.chun_delivertype', 'u.chun_invoicetype', 'u.chun_province', 'u.chun_city', 'u.chun_county', 'u.chun_address', 'u.chun_img', 'i.chin_level', 'i.chin_main_brand', 'i.chin_second_brand', 'i.chin_owe_day', 'i.chin_owe_money', 'i.chin_data', 'u.chun_adm_id', 'i.chin_type', 'i.chin_caution_day', 'i.chin_prec_id', 'i.chin_remarks', 'chin_longitude', 'chin_latitude', 'chun_class', 'chun_type', 'chin_caution_money')
                ->first();
            // 获取业务员名称
            $list_data->adm_name = DB::table('admin')
                ->where('adm_id', $list_data->chun_adm_id)
                ->value('adm_name');
            // 获取业务划区
            if ($list_data->chin_prec_id) {
                $list_data->chin_prec_name = DB::table('precincts')
                    ->where('prec_id', $list_data->chin_prec_id)
                    ->value('prec_name');
            } else {
                $list_data->chin_prec_name = '';
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        }
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->editShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        DB::beginTransaction();
        // 1. 判断商品名称是否存在
        $find_chun = DB::table('channel_unit')
            ->where('chun_id', '<>', $request['chun_id'])
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->where('chun_unit_name', $request['chun_unit_name'])
            ->first(['chun_id']);

        if ($find_chun) {
            return response()->json(['code'=>500, 'msg'=>'供应商名称已存在', 'data'=>'供应商名称已存在']);
        }

        // 联系人、电话
        if (!empty($request['info_name'])) {
            // 处理商品属性数组数据
            foreach ($request['info_name'] as $key => $value) {
                if (empty($value) || empty($request['info_content'][$key])) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'信息项存在空项']);
                }
                $chin_data[$key]['key'] = $value; //名称
                $chin_data[$key]['value'] = $request['info_content'][$key]; //内容
                $chin_data[$key]['default'] = $request['info_default'][$key]; //是否默认1是2否
                if ($chin_data[$key]['default'] == 1) {
                    $chun_edit_data['chun_name'] = $value;
                    $chun_edit_data['chun_phone'] = $request['info_content'][$key];
                }
            }
            $chin_edit_data['chin_data'] = json_encode($chin_data);
        }

        // 2 编辑一个客户单位数据
        $chun_edit_data['chun_search_letter'] = $request['chun_search_letter'];
        if ($request['chun_adm_id']) {
            $chun_edit_data['chun_adm_id'] = $request['chun_adm_id'];
        } else {
            $chun_edit_data['chun_adm_id'] = 0;
        }
        $chun_edit_data['chun_unit_name'] = $request['chun_unit_name'];
        //$chun_edit_data['chun_payment_way'] = 2; //结算方式1.账期 2.现结
        $chun_edit_data['chun_province'] = $request['chun_province'];
        $chun_edit_data['chun_city'] = $request['chun_city'];
        $chun_edit_data['chun_county'] = $request['chun_county'];
        $chun_edit_data['chun_address'] = $request['chun_address'];
        $chun_edit_data['chun_payment_way'] = $request['chun_payment_way'];//结算方式
        $chun_edit_data['chun_delivertype'] = $request['chun_delivertype'];//交货方式
        $chun_edit_data['chun_invoicetype'] = $request['chun_invoicetype'];//票据类型
        //判断是否重新上传图片 (调用全局函数上传)
        if (stristr($request['chun_img'], 'data:image')) {
            $chun_edit_data['chun_img'] = uploadBase64Img($request['chun_img']);
        } else {
            $chun_edit_data['chun_img'] = $request['chun_img'];
        }
        $chun_edit_data['chun_update_time'] = date('Y-m-d H:i:s');

        // $chin_edit_data['chin_level'] = $request['chin_level']; //客户等级
        // $chin_edit_data['chin_main_brand'] = $request['chin_main_brand']; //主营品牌
        // $chin_edit_data['chin_second_brand'] = $request['chin_second_brand']; //次营品牌
        // $chin_edit_data['chin_prec_id'] = !empty($request['chin_prec_id']) ? $request['chin_prec_id'] : ''; //业务划区id
        $chin_edit_data['chin_remarks'] = isset($request['chin_remarks']) ? $request['chin_remarks'] : ''; //备注
        // $chin_edit_data['chin_owe_day'] = $request['chin_owe_day'];
        // $chin_edit_data['chin_caution_day'] = $request['chin_caution_day'];
        // $chin_edit_data['chin_owe_money'] = $request['chin_owe_money'];
        $chin_edit_data['chin_update_time'] = date('Y-m-d H:i:s');

        // $lat_lon = Common::convert($request['chin_latitude'], $request['chin_longitude']);
        // $chin_edit_data['chin_longitude'] = $lat_lon['lng'];//经度
        // $chin_edit_data['chin_latitude'] = $lat_lon['lat'];//维度
        $chin_edit_data['chin_longitude'] = $request['chin_longitude']; //经度
        $chin_edit_data['chin_latitude'] = $request['chin_latitude']; //维度
        // $chin_edit_data['chin_caution_money'] = $request['chin_caution_money'] ?: 0; //警示金额


        $chun_res = DB::table('channel_unit')
            ->where('chun_id', $request['chun_id'])
            ->update($chun_edit_data);
        // 是否为虚拟加盟店1否2是
        /* if ($chun_chty_info->chun_type == 2) {
            $vish['vish_store_name'] = $request['chun_unit_name'];
            $vish['vish_update_time'] = date('Y-m-d H:i:s');
            $vish['vish_name'] = $chun_edit_data['chun_name'];
            $vish['vish_phone'] = $chun_edit_data['chun_phone'];

            $vish_res = DB::table('virtual_shop')
                ->where('vish_chun_id', $request['chun_id'])
                ->update($vish);
        } else {
            $vish_res = true;
        } */

         // 判断是否更改客户单位所属渠道类型
        // if ($request['chun_chty_id'] != $chun_chty_info->chun_chty_id) {
        //     // 更改客户单位所属渠道类型
        //     $save_type1 = DB::table('channel_type')
        //         ->where('chty_id', $request['chun_chty_id'])
        //         ->increment('chty_channel_number'); //将要更改成的渠道类型下的客户单位数量+1
        //     if ($chun_chty_info->chun_chty_id) {
        //         $save_type2 = DB::table('channel_type')
        //             ->where('chty_id', $chun_chty_info->chun_chty_id)
        //             ->decrement('chty_channel_number'); //将要更改成的渠道类型下的客户单位数量-1
        //     } else {
        //         $save_type2 = true;
        //     }
        //     if ($save_type1 && $save_type2) {
        //         $save_type = true;
        //     } else {
        //         $save_type = false;
        //     }
        // } else {
        //     $save_type = true;
        // }
        $chin_res = DB::table('channel_info')
            ->where('chin_chun_id', $request['chun_id'])
            ->update($chin_edit_data); 
        if ($chun_res /*&& $save_type*/ /*&& $chin_res && $vish_res*/) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '供应商', '编辑', '编辑供应商：' . $request['chun_unit_name'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑供应商成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑供应商失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_sepr = DB::table('channel_unit')
            ->whereIn('chun_id', $request['chun_id'])
            ->select('chun_unit_name')
            ->get();
        foreach ($find_sepr as $key => $value) {
            $chun_unit_name[] = $value->chun_unit_name;
        }

        // 启用
        $update_data['chun_state'] = 1; //状态1启用2停用
        $update_data['chun_update_time'] = date('Y-m-d H:i:s');
        $goo_res = DB::table('channel_unit')
            ->whereIn('chun_id', $request['chun_id'])
            ->update($update_data);

        if ($goo_res) {
            Common::addLog($user_info, getRealIp($request), '供应商', '启用', '供应商：（' . implode(',', $chun_unit_name) . '）启用成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'启用成功']);
        } else {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'启用失败']);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_sepr = DB::table('channel_unit')
            ->whereIn('chun_id', $request['chun_id'])
            ->get(['chun_unit_name']);
        foreach ($find_sepr as $key => $value) {
            $chun_unit_name[] = $value->chun_unit_name;
        }

        // 启用
        $update_data['chun_state'] = 2; //状态1启用2停用
        $update_data['chun_update_time'] = date('Y-m-d H:i:s');
        $goo_res = DB::table('channel_unit')
            ->whereIn('chun_id', $request['chun_id'])
            ->update($update_data);

        if ($goo_res) {
            Common::addLog($user_info, getRealIp($request), '供应商', '停用', '供应商：（' . implode(',', $chun_unit_name) . '）停用成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'停用成功']);
        } else {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'停用失败']);
        }
    }

    // 搜索渠道类型
    public function searchChannelType(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();

        $find_data = DB::table('channel_type')
            ->where('chty_cid', $user_info->adm_cid)
            ->where('chty_superior_shop_id', $shop_id)
            ->where('chty_state', 1)
            ->where('chty_delete', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('chty_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->get(['chty_id', 'chty_name']);
        return response()->json(["code"=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 导出
    public function export(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('channel_unit as u')
            ->leftjoin('channel_info as i', 'u.chun_id', '=', 'i.chin_chun_id')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'u.chun_adm_id')
            ->leftjoin('precincts as p', 'i.chin_prec_id', '=', 'p.prec_id')
            ->where('u.chun_cid', $user_info->adm_cid)
            ->where('u.chun_superior_shop_id', $shop_id)
            ->where('u.chun_state', '<>', 3)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('chun_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('chun_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('chun_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_search_letter'])) {
                    $query->where('u.chun_search_letter', 'like', '%' . $search_data['chun_search_letter'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_unit_name'])) {
                    $query->where('u.chun_unit_name', 'like', '%' . $search_data['chun_unit_name'] . '%')
                        ->orwhere('u.chun_search_letter', 'like', '%' . $search_data['chun_unit_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_name'])) {
                    $query->where('u.chun_name', 'like', '%' . $search_data['chun_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_phone'])) {
                    $query->where('u.chun_phone', 'like', '%' . $search_data['chun_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_payment_way'])) {
                    $query->where('u.chun_payment_way', $search_data['chun_payment_way']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_state'])) {
                    $query->where('u.chun_state', $search_data['chun_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_adm_id'])) {
                    $query->where('chun_adm_id', $search_data['chun_adm_id']);
                }
            }) //业务员id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chin_remarks'])) {
                    $query->where('chin_remarks', 'like', '%' . $search_data['chin_remarks'] . '%');
                }
            }) //备注
            // ->select('chun_search_letter', 'chun_unit_name', 'chty_name', 'chin_data', 'chin_caution_day', 'chin_owe_day', 'chin_level', DB::raw('CASE chun_payment_way WHEN 1 THEN \'账期\' WHEN 2 THEN \'现结\' ELSE \'无\' END chun_payment_way_case'), DB::raw('CASE chin_type WHEN 1 THEN \'是\' WHEN 2 THEN \'否\' ELSE \'否\' END chin_type_case'), 'chin_owe_money', 'adm_name', 'adm_phone', 'prec_name', DB::raw('CONCAT(chun_province,chun_city,chun_county) as site'), 'chun_address', 'chin_remarks')
            ->select('chun_search_letter', 'chun_unit_name', 'chun_name', 'chun_phone', 'chin_data', 'chin_caution_day', 'chin_owe_day', 'chin_level', DB::raw('CASE chun_payment_way WHEN 1 THEN \'账期\' WHEN 2 THEN \'现结\' ELSE \'无\' END chun_payment_way_case'), 'chin_caution_money', 'chin_owe_money', 'adm_name', 'prec_name', 'chun_province', 'chun_city', 'chun_county', 'chun_address', 'chin_remarks')
            ->orderBy('u.chun_id', 'desc')
            ->get()->toArray();
        $data = json_decode(json_encode($list_data), true);
        foreach ($data as $key => $value) {
            if (!empty($value['chin_data'])) {
                $chin_data = json_decode($value['chin_data'], true);
                $name = '';
                $phone = '';
                foreach ($chin_data as $k => $v) {
                    unset($v['default']);
                    if (!empty($name)) {
                        $name = $name . ',' . $v['key'];
                    } else {
                        $name = $v['key'];
                    }
                    if (!empty($phone)) {
                        $phone = $phone . ',' . $v['value'];
                    } else {
                        $phone = $v['value'];
                    }
                }

                $data[$key]['chun_name'] = $name;
                $data[$key]['chun_phone'] = $phone;

                unset($name);
                unset($phone);
            }
            unset($data[$key]['chin_data']);
        }
        // foreach ($data as $key => $value) {
        //     if (!empty($value['chin_data'])) {
        //         $chin_data = json_decode($value['chin_data'], true);
        //         $t = '';
        //         foreach ($chin_data as $k => $v) {
        //             unset($v['default']);
        //             $v = join("：", $v); // 可以用implode将一维数组转换为用逗号连接的字符串，join是别名
        //             $temp[] = $v;
        //         }
        //         foreach ($temp as $a) {
        //             $t .= $a . ", ";
        //         }
        //         $t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个逗号
        //         $t = rtrim($t, ',');
        //         $data[$key]['chin_data'] = $t;
        //         unset($temp);
        //         unset($t);
        //     }
        // }
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }
        $streamFileRand = '客户单位' . time() . rand(1000, 9999) . '.xlsx';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '客户单位';
        // $where['field_name'] = ['检索字母', '客户单位', '单位类型', '联系人和电话', '警示天数', '可欠天数', '客户等级', '结算方式', '是否铺货', '铺货金额', '业务员', '业务员电话', '业务划区', '所在地区', '详细地址', '备注'];
        $where['field_name'] = ['检索字母', '客户单位', '单位类型', '联系人', '联系电话', '警示天数', '可欠天数', '客户等级', '结算方式', '预警金额', '可欠金额', '业务员', '业务划区', '省', '市', '县', '详细地址', '备注'];

        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data     //导出数据
        );
        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($pathName)) {
            Common::addLog($user_info, getRealIp($request), '客户单位', '导出', '导出成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    // 导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->leadValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $file = $request->file('file');

        $res = $this->verifyLead($request);
        if (empty($res)) {
            try {
                if ($file->isValid()) {
                    // 获取表格的大小，限制上传表格的大小5M
                    $file_size = $_FILES['file']['size'];
                    if ($file_size > 5 * 1024 * 1024) {
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'文件大小不能超过5M']);
                    }

                    // 限制上传表格类型
                    $ext = $file->getClientOriginalExtension(); //文件拓展名
                    if ($ext != 'xlsx') {
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仅允许上传以xlsx结尾的后缀文件']);
                    }

                    // 有Xls和Xlsx格式两种
                    $objReader = IOFactory::createReader('Xlsx');
                    $filename = $_FILES['file']['tmp_name'];
                    $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
                    $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                    $highestRow = $sheet->getHighestRow();       // 取得总行数
                    if ($highestRow > 452) {
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'一次最多导入450条数据']);
                    }

                    // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
                    $usersExits = [];

                    DB::beginTransaction();
                    for ($j = 3; $j <= $highestRow; $j++) {
                        $chun_add['chun_cid'] = $user_info->adm_cid; //所属企业id
                        $chun_add['chun_shop_id'] = $user_info->adm_shop_id; //所属门店id
                        $chun_add['chun_superior_shop_id'] = $shop_id; //所属门店id

                        // 检索字母
                        $chun_add['chun_search_letter'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                        if (empty($chun_add['chun_search_letter'])) {
                            $chun_add['chun_search_letter'] = '';
                        }
                        if (strlen($chun_add['chun_search_letter']) > 30) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'检索字母长度超过最大限制']);
                        }

                        // 客户单位名称
                        $chun_add['chun_unit_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                        if (empty($chun_add['chun_unit_name'])) {
                            continue;
                            return response()->json(['code'=>5001, 'msg'=>'error', 'data'=>'供应商名称必填']);
                        }
                        if (strlen($chun_add['chun_unit_name']) > 152) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'供应商名称最多50个字符']);
                        }
                        // 1. 判断客户单位名称是否存在
                        $find_chun = DB::table('channel_unit')
                            ->where('chun_cid', $user_info->adm_cid)
                            ->where('chun_superior_shop_id', $shop_id)
                            ->where('chun_unit_name', $chun_add['chun_unit_name'])
                            ->select('chun_id', 'chun_unit_name')
                            ->first();
                        // if (isset($find_chun->chun_id)) {
                        //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'供应商名称已存在']);
                        // }
                        // 单位类型
                        $chty_name = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                        if (empty($chty_name)) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'供应商类型必填']);
                        }
                        // 联系人和电话
                        $supplier = [];
                        // $chin_data = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                        // if (!empty($chin_data)) {
                        //     $chin_data = explode(',', trim($chin_data));
                        //     foreach ($chin_data as $key => $value) {
                        //         if ($value) {
                        //             $chin_datas = explode('：', $value);
                        //             if ($key === 0) {
                        //                 $supplier[] = ['key' => $chin_datas[0], 'value' => $chin_datas[1], 'default' => 1];
                        //             } else {
                        //                 $supplier[] = ['key' => $chin_datas[0], 'value' => $chin_datas[1], 'default' => 2];
                        //             }
                        //             $chun_add['chun_name'] = $supplier[0]['key'];
                        //             $chun_add['chun_phone'] = $supplier[0]['value'];
                        //             $chin_add['chin_data'] = json_encode($supplier);
                        //             unset($chin_datas);
                        //         }
                        //     }
                        // } else {
                        //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'联系人和电话必填']);
                        // } 
                        // 处理联系人数组数据
                        $chun_name = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                        if (empty($chun_name)) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'联系人必填']);
                        }

                        $chun_phone = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                        if (empty($chun_phone)) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'联系电话必填']);
                        }
                        $chun_name = explode(',', trim($chun_name));
                        // $chun_phone = str_replace("\n", ",", $chun_phone);
                        $chun_phone = explode(',', trim($chun_phone));

                        $chun_add['chun_name'] = $chun_name[0];
                        $chun_add['chun_phone'] = $chun_phone[0];
                        foreach ($chun_name as $key => $value) {
                            if ($key == 0) {
                                if (isset($chun_phone[$key])) {
                                    $supplier[$key] = ['key' => $value, 'value' => $chun_phone[$key], 'default' => 1];
                                } else {
                                    $supplier[$key] = ['key' => $value, 'value' => '', 'default' => 1];
                                }
                            } else {
                                if (isset($chun_phone[$key])) {
                                    $supplier[$key] = ['key' => $value, 'value' => $chun_phone[$key], 'default' => 2];
                                } else {
                                    $supplier[$key] = ['key' => $value, 'value' => '', 'default' => 2];
                                }
                            }
                        }
                        // if (!empty($chun_name)) {
                        //     $supplier[] = ['key'=>$chun_name, 'value'=>$chun_phone[0], 'default'=>1];
                        // }
                        // if (!empty($chun_phone[1])) {
                        //     $supplier[] = ['key'=>$chun_name, 'value'=>$chun_phone[1], 'default'=>2];
                        // }
                        if (!empty($supplier)) {
                            $chin_add['chin_data'] = json_encode($supplier);
                        } else {
                            $chin_add['chin_data'] = '';
                        }
                        // 警示天数
                        $chin_add['chin_caution_day'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                        if (empty($chin_add['chin_caution_day'])) {
                            $chin_add['chin_caution_day'] = 0;
                        }
                        // 可欠天数
                        $chin_add['chin_owe_day'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());
                        if (empty($chin_add['chin_owe_day'])) {
                            $chin_add['chin_owe_day'] = 0;
                        }
                        if ($chin_add['chin_caution_day'] > $chin_add['chin_owe_day']) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'警示天数不能大于可欠天数']);
                        }
                        // 客户等级
                        $chin_add['chin_level'] = trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue());
                        if (empty($chin_add['chin_level'])) {
                            $chin_add['chin_level'] = 'A';
                        }
                        if (!in_array($chin_add['chin_level'], [0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D'])) {
                            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '客户等级只能为ABCD四个等级']);
                        }
                        // 结算方式
                        $chun_payment_way = trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());
                        if (empty($chun_payment_way)) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结算方式必填']);
                        }
                        if ($chun_payment_way == '账期' || $chun_payment_way == '挂账' || $chun_payment_way == '挂帐') {
                            $chun_add['chun_payment_way'] = 1;
                        } else {
                            $chun_add['chun_payment_way'] = 2;
                        }
                        // 预警金额
                        $chin_caution_money = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
                        $chin_add['chin_caution_money'] = $chin_caution_money ? $chin_caution_money : 0;
                        // 可欠金额
                        $chin_owe_money = trim($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue());
                        $chin_add['chin_owe_money'] = $chin_owe_money ? $chin_owe_money : 0;
                        if ($chin_add['chin_caution_money'] > $chin_add['chin_owe_money']) {
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'预警金额不能大于可欠金额']);
                        }
                        // 业务员
                        $adm_phone = trim($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue());
                        // if (empty($adm_phone)) {
                        //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'业务员必填']);
                        // }

                        $chun_add['chun_adm_id'] = DB::table('admin')
                            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
                            ->where('asr.shop_cid', $user_info->adm_cid)
                            ->where('asr.shop_id', $user_info->adm_shop_id)
                            ->where('admin.adm_name', $adm_phone)
                            ->value('admin.adm_id');
                        if (empty($chun_add['chun_adm_id'])) {
                            $chun_add['chun_adm_id'] = 0;
                        }
                        // if ($user_info->shop_versions == 1) { //系统版本：1门店版2运营中心版
                        //     // 省
                        //     $chun_add['chun_province'] = trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue());
                        //     if (empty($chun_add['chun_province'])) {
                        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'省必填']);
                        //     }
                        //     // 市
                        //     $chun_add['chun_city'] = trim($objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue());
                        //     if (empty($chun_add['chun_city'])) {
                        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'市必填']);
                        //     }
                        //     // 县
                        //     $chun_add['chun_county'] = trim($objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue());
                        //     if (empty($chun_add['chun_county'])) {
                        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'县必填']);
                        //     }
                        //     // 详细地址
                        //     $chun_add['chun_address'] = trim($objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue());
                        //     if (empty($chun_add['chun_address'])) {
                        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'详细地址必填']);
                        //     }
                        //     if (strlen($chun_add['chun_address']) > 510) {
                        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'详细地址不得超过255位字符']);
                        //     }
                        //     // 备注
                        //     $chin_add['chin_remarks'] = trim($objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue());
                        // } else { //系统版本：1门店版2运营中心版
                            // 业务划区
                            $prec_name = trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue());
                            $chin_add['chin_prec_id'] = DB::table('precincts')
                                ->where('prec_cid', $user_info->adm_cid)
                                ->where('prec_shop_id', $user_info->adm_shop_id)
                                ->where('prec_name', $prec_name)
                                ->value('prec_id');
                            if (empty($chin_add['chin_prec_id'])) {
                                $chin_add['chin_prec_id'] = '';
                            }
                            // 省
                            $chun_add['chun_province'] = trim($objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue());
                            if (empty($chun_add['chun_province'])) {
                                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'省必填']);
                            }
                            // 市
                            $chun_add['chun_city'] = trim($objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue());
                            if (empty($chun_add['chun_city'])) {
                                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'市必填']);
                            }
                            // 县
                            $chun_add['chun_county'] = trim($objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue());
                            if (empty($chun_add['chun_county'])) {
                                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'县必填']);
                            }
                            // 详细地址
                            $chun_add['chun_address'] = trim($objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue());
                            if (empty($chun_add['chun_address'])) {
                                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'详细地址必填']);
                            }
                            if (strlen($chun_add['chun_address']) > 510) {
                                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'详细地址不得超过255位字符']);
                            }
                            // 备注
                            $chin_add['chin_remarks'] = trim($objPHPExcel->getActiveSheet()->getCell("R" . $j)->getValue());
                        // }

                        if ($find_chun) {
                            $chun_add['chun_update_time'] = date('Y-m-d H:i:s');
                            $channel_unit = DB::table('channel_unit')
                                ->where('chun_id', $find_chun->chun_id)
                                ->update($chun_add);
                            $chin_add['chin_chun_id'] =  $find_chun->chun_id; //客户单位id
                            $chin_add['chin_update_time'] = date('Y-m-d H:i:s');
                            $channel_info = DB::table('channel_info')
                                ->where('chin_chun_id', $find_chun->chun_id)
                                ->update($chin_add);
                            $save_type = true;
                        } else {
                            // 客户单位表添加数据
                            $channel_unit = DB::table('channel_unit')->insertGetId($chun_add);
                            // 客户单位信息表添加数据
                            $chin_add['chin_chun_id'] =  $channel_unit; //客户单位id
                            $chin_add['chin_update_time'] = date('Y-m-d H:i:s');
                            $channel_info = DB::table('channel_info')->insert($chin_add);
                            $chun_id = $channel_unit;
                        }
                        if (!$channel_unit || !$channel_info) {
                            DB::rollBack();
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'上传失败']);
                        }
                        // 判断门店是否使用用友u8财务系统
                        // if (config('apiu8cloud.CODE_START') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                        //     // 调用u8系统接口，将客商数据传到用友系统上
                        //     $yongyou = new YongYouController;
                        //     // 客商基本档案新增
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['creator'] = config('apiu8cloud.pk_prepared'); //否  创建人
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['custcode'] = config('apiu8cloud.custcode.unit') . $user_info->adm_shop_id . config('apiu8cloud.project.item') . $chun_id; //是 客商编码
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['custname'] =$chun_add['chun_unit_name']; //是 客商名称
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['custprop'] = '0'; //否 客商类型(0 - 外部单位,1 - 内部核算单位,2 - 内部法人单位,3 - 内部渠道成员)
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['custshortname'] = $chun_add['chun_unit_name']; //是    客商简称
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['pk_areacl'] = config('apiu8cloud.SHOP_BASIC_SETUP')[$user_info->adm_shop_id]['areaclcode']; //否   所属地区(填写编码)
                        //     $u8cloud_data['cbdocvo'][0]['parentvo']['mnecode'] = $chun_add['chun_search_letter']; //否 助记码
                        //     // 调用u8系统接口
                        //     $curl_return = $yongyou->u8cloudApi('客商基本档案新增', $u8cloud_data);
                        //     // 判断用友接口返回的数据
                        //     if ($curl_return['status'] != 'success') {
                        //         DB::rollBack();
                        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'U8财务系统添加客户失败！']);
                        //     }
                        //     // 客户数据添加成功，分配客商到门店
                        //     $curl_data = json_decode($curl_return['data'], true);
                        //     $chin_add_data['pk_cubasdoc'] = $curl_data[0]['parentvo']['pk_cubasdoc']; //客商基本档案主键--添加门店系统

                        //     $custbasvo['custbasvo'][0]['pk_corp'] = config('apiu8cloud.SHOP_BASIC_SETUP')[$user_info->adm_shop_id]['pk_corp']; //公司主键
                        //     $custbasvo['custbasvo'][0]['pk_cubasdoc'] = $curl_data[0]['parentvo']['pk_cubasdoc']; //客商基本档案主键
                        //     $curl_return = $yongyou->u8cloudApi('客商基本档案分配', $custbasvo);
                        // }
                    }
                    Common::addLog($user_info, getRealIp($request), '客户单位', '导入', '导入客户单位成功');
                    DB::commit();
                    return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'上传成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'上传有误,请重新上传']);
                }
            } catch (Exception $e) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$e->getMessage()]);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$res]);
        }
    }

    // 返回提示错误
    public function verifyLead($request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $file = $request->file('file');
        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return '文件大小不能超过5M';
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return '仅允许上传以xlsx结尾的后缀文件';
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow > 452) {
                return '一次最多导入450条数据';
            }
            if ($highestRow < 3) {
                return '未获取到客户单位数据';
            }

            $hint = '';
            for ($j = 3; $j <= $highestRow; $j++) {
                // 检索字母
                $chun_add['chun_search_letter'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                if (strlen($chun_add['chun_search_letter']) > 30) {
                    $hint .= '检索字母长度超过最大限制，';
                }
                // 客户单位名称
                $chun_add['chun_unit_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                if (empty($chun_add['chun_unit_name'])) {
                    // continue;
                    // $hint .= '客户单位名称必填，';
                }
                if (strlen($chun_add['chun_unit_name']) > 152) {
                    $hint .= '供应商名称最多50个字符，';
                }
                // 1. 判断客户单位名称是否存在
                $find_chun = DB::table('channel_unit')
                    ->where('chun_cid', $user_info->adm_cid)
                    ->where('chun_superior_shop_id', $shop_id)
                    ->where('chun_unit_name', $chun_add['chun_unit_name'])
                    ->select('chun_id', 'chun_unit_name')
                    ->first();
                if (isset($find_chun->chun_id)) {
                    $hint .= $find_chun->chun_unit_name . '供应商名称已存在，';
                }
                // 单位类型
                $chty_name = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                if (empty($chty_name)) {
                    $hint .= '供应商类型必填，';
                }

                // 处理联系人数组数据
                $chun_name = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                if (empty($chun_name)) {
                    $hint .= '联系人必填，';
                }
                $chun_phone = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                if (empty($chun_phone)) {
                    $hint .= '联系电话必填，';
                }
                // 警示天数
                $chin_add['chin_caution_day'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                if (empty($chin_add['chin_caution_day'])) {
                    $chin_add['chin_caution_day'] = 0;
                }
                // 可欠天数
                $chin_add['chin_owe_day'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());
                if (empty($chin_add['chin_owe_day'])) {
                    $chin_add['chin_owe_day'] = 0;
                }
                if ($chin_add['chin_caution_day'] > $chin_add['chin_owe_day']) {
                    $hint .= '警示天数不能大于可欠天数，';
                }
                // 客户等级
                $chin_add['chin_level'] = trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue());
                if (empty($chin_add['chin_level'])) {
                    $chin_add['chin_level'] = 'A';
                }
                if (!in_array($chin_add['chin_level'], [0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D'])) {
                    $hint .= '客户等级只能为ABCD四个等级，';
                }
                // 结算方式
                $chun_payment_way = trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());
                if (empty($chun_payment_way)) {
                    $hint .= '结算方式必填，';
                }
                // 预警金额
                $chin_caution_money = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
                $chin_add['chin_caution_money'] = $chin_caution_money ? $chin_caution_money : 0;
                // 可欠金额
                $chin_owe_money = trim($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue());
                $chin_add['chin_owe_money'] = $chin_owe_money ? $chin_owe_money : 0;
                if ($chin_add['chin_caution_money'] > $chin_add['chin_owe_money']) {
                    $hint .= '预警金额不能大于可欠金额，';
                }

                // if ($user_info->shop_versions == 1) { //系统版本：1门店版2运营中心版
                //     // 省
                //     $chun_add['chun_province'] = trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue());
                //     if (empty($chun_add['chun_province'])) {
                //         $hint .= '省必填，';
                //     }
                //     // 市
                //     $chun_add['chun_city'] = trim($objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue());
                //     if (empty($chun_add['chun_city'])) {
                //         $hint .= '市必填，';
                //     }
                //     // 县
                //     $chun_add['chun_county'] = trim($objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue());
                //     if (empty($chun_add['chun_county'])) {
                //         $hint .= '县必填，';
                //     }
                //     // 详细地址
                //     $chun_add['chun_address'] = trim($objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue());
                //     if (empty($chun_add['chun_address'])) {
                //         $hint .= '详细地址必填，';
                //     }
                //     if (strlen($chun_add['chun_address']) > 510) {
                //         $hint .= '详细地址不得超过255位字符，';
                //     }
                //     // 备注
                //     $chin_add['chin_remarks'] = trim($objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue());
                // } else { //系统版本：1门店版2运营中心版
                    // 省
                    $chun_add['chun_province'] = trim($objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue());
                    if (empty($chun_add['chun_province'])) {
                        $hint .= '省必填，';
                    }
                    // 市
                    $chun_add['chun_city'] = trim($objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue());
                    if (empty($chun_add['chun_city'])) {
                        $hint .= '市必填，';
                    }
                    // 县
                    $chun_add['chun_county'] = trim($objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue());
                    if (empty($chun_add['chun_county'])) {
                        $hint .= '县必填，';
                    }
                    // 详细地址
                    $chun_add['chun_address'] = trim($objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue());
                    if (empty($chun_add['chun_address'])) {
                        $hint .= '详细地址必填，';
                    }
                    if (strlen($chun_add['chun_address']) > 510) {
                        $hint .= '详细地址不得超过255位字符，';
                    }
                // }
            }
            return $hint;
        } else {
            return '上传有误,请重新上传';
        }
    }

    // 导入-下载模板
    public function downTemplate(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // if ($user_info->shop_versions == 1) { //系统版本：1门店版2运营中心版
        //     $date = time();
        //     return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/Template/1630318413shopChannelUnit.xlsx']);
        // } else { //系统版本：1门店版2运营中心版
            $date = time();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/Template/1630318413ChannelUnit.xlsx']);
        // }
    }

    // 搜索客户单位名称
    public function searchCustomer(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $find_data =  DB::table('channel_unit as u')
            ->leftjoin('channel_info as i', 'u.chun_id', '=', 'i.chin_chun_id')
            ->where('u.chun_cid', $user_info->adm_cid)
            ->where('u.chun_superior_shop_id', $shop_id)
            ->where('u.chun_state', '<>', 3)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_unit_name'])) {
                    $query->where('chun_unit_name', 'like', '%' . $search_data['chun_unit_name'] . '%');
                }
            })
            ->select('u.chun_id', 'u.chun_unit_name')
            ->get();
        return response()->json(["code"=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 合并
    public function merge(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->mergeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1. 判断客户单位名称是否存在
        $find_chun = DB::table('channel_unit')
            ->where('chun_id', '<>', $request['chun_id'])
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->where('chun_unit_name', $request['chun_unit_name'])
            ->select('chun_id')
            ->first();
        if ($find_chun) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'供应商名称已存在']);
        }

        $find_chuns = DB::table('channel_unit')
            ->where('chun_id', $request['chun_id'])
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone')
            ->first();
        $chun_edit_data['chun_unit_name'] = $request['chun_unit_name'] ? $request['chun_unit_name'] : $find_chuns->chun_unit_name;
        $chun_edit_data['chun_update_time'] = date('Y-m-d H:i:s');

        $order_data['ord_update_time'] = date('Y-m-d H:i:s');
        $order_data['ord_client_id'] = $request['chun_id'];
        $order_data['orcl_channel_unit'] = $request['chun_unit_name'];
        $order_data['orcl_name'] = $find_chuns->chun_name;
        $order_data['orcl_phone'] = $find_chuns->chun_phone;

        $work_data['wocl_update_time'] = date('Y-m-d H:i:s');
        $work_data['wocl_client_id'] = $request['chun_id'];
        $work_data['wocl_channel_unit'] = $request['chun_unit_name'];
        $work_data['wocl_name'] = $find_chuns->chun_name;
        $work_data['wocl_phone'] = $find_chuns->chun_phone;

        DB::beginTransaction();
        // 修改客户单位表
        $chun_res = DB::table('channel_unit')
            ->where('chun_id', $request['chun_id'])
            ->update($chun_edit_data);

        // 删除被合并的客户单位数据
        $update_res = DB::table('channel_unit')
            ->where('chun_id', $request['chun_more_id'])
            ->update(['chun_state' => 3]);

        // 订单表 修改客户单位
        $order_res = DB::table('order as ord')
            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_type', 2)
            ->where('ord_client_id', $request['chun_more_id'])
            ->update($order_data);

        // 工单客户表 修改客户单位
        $work_res = DB::table('work_order as o')
            ->leftJoin('work_client as c', 'o.wor_id', '=', 'c.wocl_wor_id')
            ->where('wor_type', 2)
            ->where('wocl_client_id', $request['chun_more_id'])
            ->update($work_data);

        if ($chun_res && $update_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '供应商', '合并', '合并供应商：' . $request['chun_unit_name'] . '成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'合并供应商成功']);
        } else {
            DB::rollBack();
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'合并供应商失败']);
        }
    }

    // 列表下拉搜索客户单位
    public function pulldownSearch(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $select_field = "chun_id, chun_unit_name, chun_name, chun_phone, chun_province, chun_city, chun_county, chun_address";

        $public_search = new PublicSearch;
        $list_data = $public_search->searchChannelUnit($user_info, $request->all(), $this->show_count, $select_field);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data['data']]);
    }

    // 列表下拉搜索客户单位  停用启用都搜到
    public function pulldownChan(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $find_data =  DB::table('channel_unit')
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('chun_unit_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('chun_search_letter', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('chun_id', 'chun_unit_name')
            ->offset(0)->limit(10)
            ->get();
        return response()->json(["code"=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 获取客户单位
    public function getChannelUnit(Request $request)
    {
        $search_data = $request->all();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $find_data =  DB::table('channel_unit')
            ->where('chun_cid', $user_info->adm_cid)
            ->where('chun_superior_shop_id', $shop_id)
            ->where('chun_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('chun_unit_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('chun_search_letter', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_type'])) {
                    $query->where('chun_type', 1);
                }
            })
            ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_province', 'chun_city', 'chun_county', 'chun_address')
            ->offset(0)->limit(10)
            ->get();
        return response()->json(["code"=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 客户单位详情路由
    public function details(Request $request)
    {
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->detailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $list_data = DB::table('channel_unit as u')
            ->leftjoin('channel_info as i', 'u.chun_id', '=', 'i.chin_chun_id')
            ->where('u.chun_cid', $user_info->adm_cid)
            ->where('u.chun_superior_shop_id', $shop_id)
            ->where('u.chun_id', $request['chun_id'])
            ->select('u.chun_id', 'u.chun_search_letter', 'u.chun_unit_name', 'u.chun_name', 'u.chun_phone', 'u.chun_state', 'u.chun_payment_way', 'u.chun_province', 'u.chun_city', 'u.chun_county', 'u.chun_address', 'u.chun_img', 'i.chin_level', 'i.chin_main_brand', 'i.chin_second_brand', 'i.chin_owe_day', 'i.chin_owe_money', 'i.chin_data', 'u.chun_adm_id', 'i.chin_type', 'i.chin_caution_day', 'i.chin_prec_id', 'i.chin_remarks')
            ->first();
        // 获取业务员名称
        $list_data->adm_name = DB::table('admin')
            ->where('adm_id', $list_data->chun_adm_id)
            ->value('adm_name');
        $list_data->chin_zoning = DB::table('precincts')
            ->where('prec_state', $list_data->chin_prec_id)
            ->value('prec_name');
        return response()->json(["code"=>200, 'msg'=>'success', 'data'=>$list_data]);
    }

    // 获取业务划区数据
    public function searchPrecincts(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $select_field = "prec_id, prec_name";

        $public_search = new PublicSearch;
        $list_data = $public_search->searchPrecincts($user_info, $request->all(), $select_field);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data['data']]);
    }

    // 获取门店商品提交客户单位设置商品价格
    public function searchAddChannelGoods(Request $request)
    {
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->searchAddChannelGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if (!isset($request['goo_type']) || !in_array($request['goo_type'], [1, 4])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品类型错误']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        if ($request['type'] == 1) {
            $search_data = $request->all();
            $shop_state = true;
            if (in_array($user_info->adm_shop_id, config('apisystem.NO_SHOPID'))) {
                $shop_state = false;
            }
            $goo_type = $request['goo_type'] ? $request['goo_type'] : 1;
            $list_data = DB::table('goods as g')
                ->leftJoin('brand_serie as bs', 'g.goo_brse_id', '=', 'bs.brse_id')
                ->where(function ($query) use ($user_info, $shop_state) {
                    if ($shop_state) {
                        $query->where('goo_cid', 0)
                            ->orwhere('goo_cid', $user_info->adm_cid);
                    } else {
                        $query->where('goo_cid', $user_info->adm_cid);
                    }
                })
                ->where(function ($query) use ($user_info, $shop_state) {
                    if ($shop_state) {
                        $query->where('goo_shop_id', 0)
                            ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                    } else {
                        $query->where('goo_shop_id', $user_info->adm_shop_id);
                    }
                })
                ->where('goo_type', $request['goo_type'])
                ->where('goo_delete', 1)
                ->where('goo_state', 1)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_name'])) {
                        $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                            ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_bra_id'])) {
                        $query->where('goo_bra_id', $search_data['goo_bra_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_cate_id'])) {
                        $query->where('goo_cate_id', $search_data['goo_cate_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_brse_id'])) {
                        $query->where('goo_brse_id', $search_data['goo_brse_id']);
                    }
                })
                ->select('goo_id', 'goo_type', 'goo_class', 'goo_name', 'goo_goods_encode', 'goo_wholesale_price as goo_price', 'goo_cate_name', 'goo_bra_name', 'brse_name')
                ->orderBy('goo_goods_encode', 'asc')
                ->paginate($this->show_count);
            $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
            $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data_info['total'] = $list_data->total();               //总数据个数
            $data_info['current_number'] = $this->show_count;       //一页显示多少个
            $goods_data = $list_data->items();

            $goo_id = array_column($goods_data, 'goo_id');
            // 查询客户单位设置的商品价格
            $channel_goo_data = DB::table('channel_unit_goods_correlation')
                ->where('cugc_shop_id', $user_info->adm_shop_id)
                ->where('cugc_chun_id', $request['chun_id'])
                ->whereIn('cugc_goo_id', $goo_id)
                ->pluck('cugc_set_goo_price', 'cugc_goo_id')
                ->toArray();

            // 搜索系统商品价格，门店设置的
            $gosa_goo_price = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id', $goo_id)
                ->pluck('gosa_wholesale_price', 'gosa_goo_id')
                ->toArray();

            foreach ($goods_data as $key => $value) {
                if ($value->goo_class == 2 && isset($gosa_goo_price[$value->goo_id])) {
                    // 系统商品类型，门店设置的价格
                    $goods_data[$key]->goo_price = $gosa_goo_price[$value->goo_id];
                }
                if (isset($channel_goo_data[$value->goo_id])) {
                    // 客户单位设置的商品价格
                    $goods_data[$key]->goo_price = $channel_goo_data[$value->goo_id];
                }
            }
            $data_info['data'] = $goods_data;
            if ($list_data) {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } else {
            $goods_data = json_decode($request['goo_data'], true);

            DB::beginTransaction();
            foreach ($goods_data as $key => $value) {
                $chun_goo_data = DB::table('channel_unit_goods_correlation')
                    ->where('cugc_cid', $user_info->adm_cid)
                    ->where('cugc_shop_id', $user_info->adm_shop_id)
                    ->where('cugc_chun_id', $request['chun_id'])
                    ->where('cugc_goo_id', $value['goo_id'])
                    ->select('cugc_id', 'cugc_set_goo_price')
                    ->first();
                if ($chun_goo_data) {
                    $update_data['cugc_set_goo_price'] = $value['goo_wholesale_price'] * 100;
                    $update_data['cugc_adm_id'] = $user_info->adm_id;
                    $update_data['cugc_update_time'] = date('Y-m-d H:i:s');
                    $updcugc_res = DB::table('channel_unit_goods_correlation')
                        ->where('cugc_id', $chun_goo_data->cugc_id)
                        ->update($update_data);
                    $add_data_res = true;
                } else {
                    $add_data['cugc_cid'] = $user_info->adm_cid;
                    $add_data['cugc_shop_id'] = $user_info->adm_shop_id;
                    $add_data['cugc_chun_id'] = $request['chun_id'];
                    $add_data['cugc_goo_id'] = $value['goo_id'];
                    $add_data['cugc_adm_id'] = $user_info->adm_id;
                    $add_data['cugc_goo_type'] = $request['goo_type'];
                    $add_data['cugc_set_goo_price'] = $value['goo_wholesale_price'] * 100;
                    $add_data['cugc_update_time'] = date('Y-m-d H:i:s');
                    $add_data_res = DB::table('channel_unit_goods_correlation')->insert($add_data);
                    $updcugc_res = true;
                }
                if (!$updcugc_res || !$add_data_res) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品价格设置失败']);
                }
            }

            $chun_unit_name = DB::table('channel_unit')->where('chun_id', $request['chun_id'])->value('chun_unit_name');
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '客户单位', '商品设置', $chun_unit_name . '商品价格设置成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'商品价格设置成功']);
        }
    }

    // 查询客户单位绑定商品
    public function searchGoodsList(Request $request)
    {
        $verify_data = new VerifyChannelUnitController;
        $error_message = $verify_data->searchGoodsListValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if (!isset($request['goo_type']) || !in_array($request['goo_type'], [1, 4])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品类型错误']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('channel_unit_goods_correlation as cu')
            ->leftJoin('goods as g', 'g.goo_id', '=', 'cu.cugc_goo_id')
            ->leftJoin('brand_serie as bs', 'g.goo_brse_id', '=', 'bs.brse_id')
            ->where('cugc_cid', $user_info->adm_cid)
            ->where('cugc_shop_id', $user_info->adm_shop_id)
            ->where('cugc_chun_id', $request['chun_id'])
            ->where('goo_type', $request['goo_type'])
            ->where('goo_delete', 1)
            ->where('goo_state', 1) //1启用2禁用
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            })
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_bra_name', 'cugc_set_goo_price as goo_price', 'goo_cate_name', 'brse_name')
            ->orderBy('goo_goods_encode', 'asc')
            ->paginate($this->show_count);

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据

        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 结算方式
    public function getPaymentWay(Request $request)
    {
        //$show 1全部结算方式  2部分结算方式
        $list_data = ChannelUnitServices::getPaymentWayName($request['type'],false);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 交货方式
    public function getDeliverType(Request $request)
    {
        $list_data = ChannelUnitServices::getDeliverTypeName(false);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 票据类型
    public function getInvoiceType(Request $request)
    {
        $list_data = ChannelUnitServices::getInvoiceTypeName(false);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    //结算信息
    public function getSettlementInformation(Request $request)
    {
        $payment_way_data = ChannelUnitServices::getPaymentWayName(2,false);//结算信息
        $deliver_type_data =  ChannelUnitServices::getDeliverTypeName(false);//
        $invoice_type_data =  ChannelUnitServices::getInvoiceTypeName(false);
        $list_data['payment_way'] = $payment_way_data;
        $list_data['deliver_type'] = $deliver_type_data;
        $list_data['invoice_type'] = $invoice_type_data;
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }
}
