<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-04-16
 *
 *
 */

namespace app\common\repositories\system\merchant;


use app\common\dao\system\merchant\MerchantDao;
use app\common\enum\CommonEnum;
use app\common\model\store\product\ProductReply;
use app\common\repositories\BaseRepository;
use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
use app\common\repositories\store\product\ProductCopyRepository;
use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\store\shipping\ShippingTemplateRepository;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\system\attachment\AttachmentRepository;
use app\common\repositories\user\UserRelationRepository;
use app\common\repositories\user\UserVisitRepository;
use app\common\repositories\wechat\RoutineQrcodeRepository;
use app\controller\admin\system\merchant\MerchantIntention;
use app\controller\merchant\gong\Goods;
use app\entity\data\merchant\MerchantEntity;
use app\traits\HaikeApiRequest;
use crmeb\services\QrcodeService;
use crmeb\services\UploadService;
use FormBuilder\Exception\FormBuilderException;
use FormBuilder\Factory\Elm;
use FormBuilder\Form;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Route;

/**
 * Class MerchantRepository
 * @package app\common\repositories\system\merchant
 * @mixin MerchantDao
 * @author xaboy
 * @day 2020-04-16
 */
class MerchantRepository extends BaseRepository
{
    use HaikeApiRequest;
    /**
     * MerchantRepository constructor.
     * @param MerchantDao $dao
     */
    public function __construct(MerchantDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param array $where
     * @param $page
     * @param $limit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-04-16
     */
    public function lst(array $where, $page, $limit)
    {
        if (!empty($where["city"])){
            $city_id=Db::name("user_city")->where("city_name",$where["city"])->value("city_id");
            $where['city_id'] = $city_id;
            unset($where["city"]);
        }
        $query = $this->dao->search($where);
        $query = $query->with(['merchantCategory','spread']);
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)
            ->setOption('field', [])
            ->field('mer_id,merch_no, mer_name, real_name,name, mer_phone, mer_address, mark, status, create_time,is_best,recommender,category_id,type,withdrawal_setting,dc_id,merchant_level')
            ->select();
        foreach ($list as &$item) {
            if (!$item->withdrawal_setting && $item->merch_no != '') {
                try {
                    $response = $this->merchantInfo(['merch_no' => $item->merch_no]);
                    $item->withdrawal_setting = $response['pay_product_info']['settlement_cycle'];
                    $item->save();
                } catch (\Throwable $e) {
                }
            }
            if($item['dc_id'] == 0){
                $item['dc'] = '无';
            }else{
                $item['dc'] = Db::name('big_warehouse') -> where('id',$item['dc_id']) -> value('warehouse_name');
            }
            $item['category_id']=(int)$item['category_id'];
            $item['status']=(int)$item['status'];
            $item['is_best']=(int)$item['is_best'];
        }
        unset($item);
        $merdata= [
            ['className'=> 'el-icon-s-order', 'count'=>$count, 'field'=> '个', 'name'=> '商户总数']
        ];
        return compact('count', 'list','merdata');
    }


    /**
     * @param array $where
     * @param $page
     * @param $limit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function lstLeft(array $where, $page, $limit)
    {
        if (!empty($where["city"])){
            $city_id=Db::name("user_city")->where("city_name",$where["city"])->value("city_id");
            $where['city_id'] = $city_id;
            unset($where["city"]);
        }
        $query = $this->dao->searchLeft($where);
        $query = $query->with(['merchantCategory','spread']);
        $query = $query->withJoin(['MerchantIntention']);
//        $count = $query->count($this->dao->getPk());
        $count = $query->count('merchant.mer_id');
        $list = $query->page($page, $limit)
            ->setOption('field', [])
            ->field('merchant.mer_id,merchant.merch_no, merchant.mer_name, merchant.real_name,merchant.name, merchant.mer_phone, merchant.mer_address, merchant.mark, merchant.status, merchant.create_time,merchant.is_best,merchant.recommender,merchant.category_id,merchant.type,merchant.withdrawal_setting,merchant.dc_id,merchant.merchant_level')
            ->select();
        foreach ($list as &$item) {
            if (!$item->withdrawal_setting && $item->merch_no != '') {
                try {
                    $response = $this->merchantInfo(['merch_no' => $item->merch_no]);
                    $item->withdrawal_setting = $response['pay_product_info']['settlement_cycle'];
                    $item->save();
                } catch (\Throwable $e) {
                }
            }
            if($item['dc_id'] == 0){
                $item['dc'] = '无';
            }else{
                $item['dc'] = Db::name('big_warehouse') -> where('id',$item['dc_id']) -> value('warehouse_name');
            }
            $item['category_id']=(int)$item['category_id'];
            $item['status']=(int)$item['status'];
            $item['is_best']=(int)$item['is_best'];
        }
        unset($item);
        $merdata= [
            ['className'=> 'el-icon-s-order', 'count'=>$count, 'field'=> '个', 'name'=> '商户总数']
        ];
        return compact('count', 'list','merdata');
    }
    /**
     * @param int|null $id
     * @param array $formData
     * @return Form
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-04-16
     */
    public function form(?int $id = null, array $formData = [])
    {
        $form = Elm::createForm(is_null($id) ? Route::buildUrl('systemMerchantCreate')->build() : Route::buildUrl('systemMerchantUpdate_1', ['id' => $id])->build());

        /** @var MerchantCategoryRepository $make */
        $make = app()->make(MerchantCategoryRepository::class);

//        $config = systemConfig(['broadcast_room_type', 'broadcast_goods_type']);
        $formData['category_id']=(int)$formData['category_id'];
        $formData['status']=(int)$formData['status'];
        $formData['is_audit']=(int)$formData['is_audit'];
        $formData['is_best']=(int)$formData['is_best'];
        $rule = [
            Elm::input('mer_name', '商户名称')->required(),


//            Elm::select('mer_type', '一壶茶会员专区商户')->options(function () {
//                return array(
//                    array('value'=>'0','label'=>'普通商户'),
//                    array('value'=>'1','label'=>'一壶茶会员专区商户'),
//                );
//            })->required(),

            Elm::select('category_id', '商户分类')->options(function () use ($make) {
                $data = $make->allOptions();
                $options = [];
                foreach ($data as $value => $label) {
                    $options[] = compact('value', 'label');
                }
                return $options;
            })->requiredNum(),
            Elm::input('mer_account', '商户账号')->required()->disabled(!is_null($id))->required(!is_null($id)),
            Elm::password('mer_password', '登录密码')->required()->disabled(!is_null($id))->required(!is_null($id)),
            Elm::input('real_name', '商户姓名'),
            Elm::input('mer_phone', '商户手机号')->col(12),
//            Elm::number('commission_rate', '手续费(%)')->col(12),
            Elm::input('mer_keyword', '商户关键字')->col(12),
            Elm::input('mer_address', '商户地址'),
            Elm::input('lng', '经度')->col(12),
            Elm::input('lat', '纬度')->col(12),
            Elm::textarea('mark', '备注'),
            Elm::number('sort', '排序', 0),
            Elm::switches('status', '是否开启', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
            //Elm::switches('is_bro_room', '直播间审核', $config['broadcast_room_type'] == 1 ? 0 : 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
            Elm::switches('is_audit', '产品审核', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
            //Elm::switches('is_bro_goods', '直播间商品审核', $config['broadcast_goods_type'] == 1 ? 0 : 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
            Elm::switches('is_best', '是否推荐')->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启'),
        ];

        $form->setRule($rule);
        return $form->setTitle(is_null($id) ? '添加商户' : '编辑商户')->formData($formData);
    }

    /**
     * @param array $formData
     * @return Form
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020/6/25
     */
    public function merchantForm(array $formData = [])
    {
        if(isset($formData['mer_state'])){$formData['mer_state']=(int)$formData['mer_state'];}
        $form = Elm::createForm(Route::buildUrl('merchantUpdate')->build());
        $rule = [
            Elm::input('mer_phone', '手机号')->readonly(true),
            Elm::input('email', '邮箱')->readonly(true),
            Elm::input('product_score', '商品描述评分')->readonly(true),
            Elm::input('service_score', '服务评分')->readonly(true),
            Elm::input('postage_score', '物流评分')->readonly(true),
            Elm::input('care_count', '关注总数')->readonly(true),
            Elm::input('bank_location', '开户所在地')->readonly(true),
            Elm::input('bank_deposit', '开户行')->readonly(true),
            Elm::input('bank_branch', '开户支行')->readonly(true),
            Elm::input('bank_account', '开户账号')->readonly(true),
            Elm::input('open_account', '开户许可证')->readonly(true),
//            Elm::input('district_addr', '商圈')->required(),
            Elm::textarea('mer_info', '店铺简介')->required(),
            Elm::input('service_phone', '服务电话')->required(),
            Elm::frameImage('mer_banner', '店铺 banner', '/' . config('admin.merchant_prefix') . '/setting/uploadPicture?field=mer_banner&type=1')->modal(['modal' => false])->width('896px')->height('480px')->props(['footer' => false]),
            Elm::frameImage('mer_avatar', '店铺头像', '/' . config('admin.merchant_prefix') . '/setting/uploadPicture?field=mer_avatar&type=1')->modal(['modal' => false])->width('896px')->height('480px')->props(['footer' => false]),
            Elm::switches('mer_state', '是否开启', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
        ];
        $form->setRule($rule);
        return $form->setTitle('编辑店铺信息')->formData($formData);
    }

    /**
     * @param $id
     * @return Form
     * @throws FormBuilderException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-04-16
     */
    public function updateForm($id)
    {
        $data = $this->dao->get($id)->toArray();
        /** @var MerchantAdminRepository $make */
        $make = app()->make(MerchantAdminRepository::class);
        $data['mer_account'] = $make->merIdByAccount($id);
        $data['mer_password'] = '***********';
        return $this->form($id, $data);
    }

    /**
     * @param array $data
     * @author xaboy
     * @day 2020-04-17
     */
    public function createMerchant(array $data)
    {
        /** @var MerchantAdminRepository $make */
        $make = app()->make(MerchantAdminRepository::class);
        Db::transaction(function () use ($data, $make) {
            $account = $data['mer_account'];
            $password = $data['mer_password'];
            unset($data['mer_account'], $data['mer_password']);
            $merchant = $this->dao->create($data);
            $make->createMerchantAccount($merchant, $account, $password);
            app()->make(ShippingTemplateRepository::class)->createDefault($merchant->mer_id);
            app()->make(ProductCopyRepository::class)->defaulCopyNum($merchant->mer_id);
        });
    }


    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     */
    public function getList($where, $page, $limit, $userInfo)
    {
        $where['status'] = 1;
        $where['mer_state'] = 1;
        if ($userInfo && $where['keyword'] !== '')
            app()->make(UserVisitRepository::class)->searchMerchant($userInfo['uid'], $where['keyword']);

        if($where['category_id'] == 0) {
            unset($where['category_id']);
            $query = $this->dao->search($where)->with(['showProduct']);
            $query = $query->order("create_time desc")->limit("10");
        }else{
            $query = $this->dao->search($where)->with(['showProduct']);
        }
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)->setOption('field', [])
            ->field('lat,lng,addr,mer_id,mer_banner,mer_name, mark,mer_avatar,product_score,service_score,postage_score,sales,status,create_time,category_id')
            ->select()
            ->each(function ($item) {
                $data = $item->showProduct->toArray();
                unset($item->showProduct);
                $recommend = array_slice($data, 0, 3);
                return $item['recommend'] = $recommend;
            });


        return compact('count', 'list');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param int $id
     * @return array|\think\Model|null
     */
    public function merExists(int $id)
    {
        return ($this->dao->get($id));
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param $id
     * @param $userInfo
     * @return array|\think\Model|null
     */
    public function detail($id, $userInfo, $lat='', $lng='')
    {
        $merchant = $this->dao->apiGetOne($id)->hidden(["real_name", "mer_phone", "reg_admin_id", "sort", "is_del", "is_audit", "is_best", "mer_state", "bank", "bank_number", "bank_name", 'update_time']);
        $merchant['care'] = false;
        $merchant['like']=false;
        $merchant['topping']=false;
        if ($userInfo){
            $like=Db::name('store_fabulous')->where(['uid'=>$userInfo->uid,'mer_id'=>$id])->value('status');
            if($like==1){
                $like=true;
            }else{
                $like=false;
            }
            if($userInfo->mer_topping==$id){
                $topping=true;
            }else{
                $topping=false;
            }
            $merchant['care'] = $this->getCareByUser($id, $userInfo->uid);
            $merchant['like']=$like;
            $merchant['topping']=$topping;
        }

//        Db::name("merchant")->where("mer_id",$cartInfo['mer_id'])->inc('renqizhi', 1)
        $this->dao->addrenqi($id);
        if($merchant['content_pic']){
            $merchant['content_pic'] = explode(',',$merchant['content_pic']);
        }
        $lat=empty($lat)?"34.73841":$lat;
        $lng=empty($lng)?"113.643636":$lng;
        $field = 'ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 )
                * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance';
        $distance =Db::name("merchant")
            ->where("mer_id",$id)
            ->field($field)
            ->find();
        $merchant['distance'] =sprintf("%.2f",$distance['distance']);
        return $merchant;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param int $merId
     * @param int $userId
     * @return bool
     */
    public function getCareByUser(int $merId, int $userId)
    {
        if (app()->make(UserRelationRepository::class)->getWhere(['type' => 10, 'type_id' => $merId, 'uid' => $userId]))
            return true;
        return false;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param $merId
     * @param $where
     * @param $page
     * @param $limit
     * @param $userInfo
     * @return mixed
     */
    public function productList($merId, $where, $page, $limit, $userInfo,$type439=false,$is_commercetrade = 0)
    {
        // log::info("========j进入prodctList");
        // log::info($merId);
        // log::info( $where);
        // log::info($userInfo);
        // log::info($type439);
        $list=app()->make(ProductRepository::class)->getApiSearch($merId, $where, $page, $limit, $userInfo,$type439);

        $arr=[];
        foreach ($list["list"] as $v){
            $k= app()->make(ProductRepository::class)->pvParm($v['product_id']);
            $productMerId = $v['mer_id'] ?? 0;
//            $v['special_merchant']= merchantConfig($v['mer_id'], 'special_merchant');

            // log::info("==========yang= {$k['yanglao']} ");

            $v['yanglao']='';
            $v['pv']='';
            $v['jifen']='';
            $v['gongxian']='';
            $v['jfduihuan']='';
            $v['jdduihuan']='';
            //会员专区中VR或者现金和VR+现金形式
            //支付组合
            $v['fzone_paytype'] = '';
            //$v['vr'] = 0;
            $num_yl = 0;

            if($v['price'] == '1180'){
                $num_yl = 1000;
            }else if($v['price'] == '10620'){
                $num_yl = 9000;
            }else if($v['price'] == '11800'){
                $num_yl = 10000;
            }else if($v['price'] == '2360'){
                $num_yl = 2000;
            }else if($v['price'] == '9440'){
                $num_yl = 8000;
            }else if($v['price'] == '5900'){
                $num_yl = 5000;
            }

            if($productMerId == 496){

                $v['yanglao'] = bcmul($num_yl, 0.035, 2);
                $v['pv'] = bcmul($num_yl, 0.7, 2);
                //$v['vr']=$v['price'];
                //1:为会员专区,

                $v['fzone_paytype']= [
                    1=>[
                        1=>$v['price'],//VR
                        2=>$v['price']//现金
                    ]
                ];

            }else if($productMerId == 439 || $is_commercetrade){
                //精彩生活和商贸区
                $jf = $v['price'] - bcmul($v['concession_pri'],0.3, 2) . ' + ' . bcmul($v['concession_pri'],0.3, 2);
                $jd = $v['price'] - bcmul($v['concession_pri'],0.35, 2) . ' + ' . bcmul($v['concession_pri'],0.35, 2);
                if($v['concession_pri'] !=null || $v['concession_pri'] !=0){
                    $v['yanglao'] = bcmul($v['concession_pri'],0.3, 2);
                    $v['pv'] = bcmul($v['concession_pri'],0.35, 2);
                    $v['jfduihuan'] =$jf;
                    $v['jdduihuan'] = $jd;
                    $v['jifen'] = bcmul($v['concession_pri'], 0.35, 2);
                    $v['gongxian'] = bcmul($v['concession_pri'], 0.35, 2);
                }
            }else if($productMerId == 491){
                // 获取商品sku
                $productSku = Db::name('store_product_attr_value')->where('product_id', $v['product_id'])->order('price asc')->find();
                $pv = $productSku['plate_mer_profit']??0.00;

//                $num_yl = $v['price'];
//                $pv= $num_yl * 0.3;
                $yanglao = bcmul($pv, 0.5, 2);
                $v['pv'] = $pv;
                $v['yanglao'] = $yanglao;

                $v['fzone_paytype']= [
                    1=>[
                        1=>$v['price'],//VR
                        2=>$v['price'],//现金
                        3=>$v['price']//复购金
                    ]
                ];
            }else if ($productMerId == 3447) {
                $yanglao = bcmul($v['price'], CommonEnum::ORDER_EARNING_ALLOCATION['SharedProsperity']['Self']['YangLaoJin']['Ratio']['code'], 2);
                $v['yanglao'] = $yanglao;

                // 计算共富区PV
                /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
                $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
                $sharedProsperityRecommendConfigEntityByMaxRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxRewardRatio();
                // 利润 减去 顶格的直推奖，剩下的是PV值
                $pvProportion = bcsub('1', bcdiv($sharedProsperityRecommendConfigEntityByMaxRewardRatio->getRewardRatio(), '100', 4), 2);
                // 获取利润
                $productSku = Db::name('store_product_attr_value')->where('product_id', $v['product_id'])->order('price asc')->find();
                // 计算pv
                $pv = bcmul($productSku['plate_mer_profit'], $pvProportion, CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
                $v['pv'] = $pv;
            }

            if ($v['pension_is'] != 0) {
                $v['yanglao'] = $v['pension'];
            }
//            $v=($v,$k);
//            array_push($v,$k);
            $arr[]=$v;


        }
        $list["merId"]=$merId;
        $list["list"]=$arr;
        return $list;
    }
    public function productList_yhc($merId, $where, $page, $limit, $userInfo)
    {

        unset($where['order']);
        if (isset($where['price_on']) && $where['price_on'] != '')$where['price'] = [$where['price_asc'], $where['price_desc']];
        if (isset($where['brand_id']) && $where['brand_id'] != '') $where['brand_id'] = explode(',', $where['brand_id']);
        unset($where['price_on'], $where['price_off']);

        //搜索记录
        if ($userInfo && isset($where['keyword']) && !empty($where['keyword']))
            app()->make(UserVisitRepository::class)->searchProduct($userInfo['uid'], $where['keyword']);



        $query = Db::name('store_product')->where('product_id','>',0)->where('mer_id', $merId)->where('type', 17);

        $keyArray = $whereArr = [];
        unset($where['type']);
        foreach ($where as $key => $item) {
            if ($item !== '' && $key != 'soft') {
                $keyArray[] = $key;
                $whereArr[$key] = $item;
            }
        }
        unset($whereArr['order']);
        $query->withSearch($keyArray, $whereArr)->where('is_show',1)->where('status',1);

        $query->when(isset($where['keyword']) && $where['keyword'] != '', function ($query) use ($where) {
            $query->whereLike('store_name', "%{$where['keyword']}%");
            unset($where['keyword']);
        });

        $query->order('sort DESC ,create_time DESC');

        $query->with(['merchant'])->with(['issetCoupon']);
        $count = $query->count();
//        echo DB::getlastsql();die;
        $filed = 'product_id,mer_id,brand_id,unit_name,rate,reply_count,store_info,cate_id,ficti,image,slider_image,store_name,keyword,sort,is_show,sales,price,refusal,cost,ot_price,stock,is_gift_bag,care_count,status,is_used,create_time,seckill,plate_mer_profit,type';
        $list = $query->page($page, $limit)->setOption('field', [])->field($filed)->select();
        $ProductRepository=app()->make(ProductRepository::class);

        $list->each(function ($item) use ($ProductRepository) {
            $item['sales'] = $item['sales'] + $item['ficti'];
            unset($item['ficti']);
            $item['yanglao'] = $ProductRepository->yanglaojin($item['product_id']);
            return $item;
        });

//        if ($this->getUserIsPromoter($userInfo)) $list = $list->each(function ($item) {
//            return $item['max_extension'] = $item->max_extension;
//        });



        $list= compact('count', 'list');
        $arr=[];
        foreach ($list["list"] as $v){
            $v['yanglao']= app()->make(ProductRepository::class)->yanglaojin($v['product_id']);
            $v['special_merchant']= merchantConfig($v['mer_id'], 'special_merchant');
            $arr[]=$v;
        }
        $list["list"]=$arr;
        return $list;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param int $id
     * @return mixed
     */
    public function categoryList(int $id)
    {
        return app()->make(StoreCategoryRepository::class)->getApiFormatList($id, 1);
    }
    public function offlineUserQrcode($merId, $userId,$queryString = '/h5payment/index.html', $imgName = '_store_user_offline_wap.jpg')
    {
        $siteUrl = systemConfig('site_url');
        $name = $merId . $userId . $imgName;
        $attachmentRepository = app()->make(AttachmentRepository::class);
        $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);

        if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
            $imageInfo->delete();
            $imageInfo = null;
        }
        if (!$imageInfo) {
            $codeUrl = set_http_type(rtrim($siteUrl, '/') . $queryString.'?id=' . $merId . '&user_id=' . $userId, request()->isSsl() ? 0 : 1);//二维码链接
            $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
            if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');

            $imageInfo['dir'] = path_to_url($imageInfo['dir']);
            if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];

            $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
                'attachment_category_id' => 0,
                'attachment_name' => $imageInfo['name'],
                'attachment_src' => $imageInfo['dir']
            ]);
            $urlCode = $imageInfo['dir'];
        } else $urlCode = $imageInfo['attachment_src'];
        return $urlCode;
    }
    public function wxQrcode($merId, $queryString = '/pages/store/home/index', $imgName = '_store_wap.jpg', $avatar = '')
    {
        $siteUrl = systemConfig('site_url');
        $name = $merId . $imgName;
        $attachmentRepository = app()->make(AttachmentRepository::class);
        $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);

        if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
            $imageInfo->delete();
            $imageInfo = null;
        }
        if (!$imageInfo) {
            $codeUrl = set_http_type(rtrim($siteUrl, '/') . $queryString.'?id=' . $merId, request()->isSsl() ? 0 : 1);//二维码链接
            $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name, $avatar);
            if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');

            $imageInfo['dir'] = path_to_url($imageInfo['dir']);
            if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];

            $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
                'attachment_category_id' => 0,
                'attachment_name' => $imageInfo['name'],
                'attachment_src' => $imageInfo['dir']
            ]);
            $urlCode = $imageInfo['dir'];
        } else $urlCode = $imageInfo['attachment_src'];
        return $urlCode;
    }
    public function routineQrcode($merId, $queryString = '/pages/store/home/index', $imgName = '_store_routine.jpg')
    {
        $name = $merId . $imgName;
        $attachmentRepository = app()->make(AttachmentRepository::class);
        $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);

        if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
            $imageInfo->delete();
            $imageInfo = null;
        }
        if (!$imageInfo) {
            $uploadType = (int)systemConfig('upload_type') ?: 1;
            $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
            $res = $routineQrcodeRepository->getShareCode($merId, 'store', $queryString.'?id=' . $merId, '');
            if (!$res) throw new ValidateException('二维码生成失败');
            $upload = UploadService::create($uploadType);
            $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
            if ($uploadRes === false) {
                throw new ValidateException($upload->getError());
            }
            $imageInfo = $upload->getUploadInfo();
            $imageInfo['image_type'] = $uploadType;

            $imageInfo['dir'] = path_to_url($imageInfo['dir']);
            if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];

            $attachmentRepository->create($uploadType, -2, $merId, [
                'attachment_category_id' => 0,
                'attachment_name' => $imageInfo['name'],
                'attachment_src' => $imageInfo['dir']
            ]);
            $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
            $urlCode = $imageInfo['dir'];
        } else $urlCode = $imageInfo['attachment_src'];
        return $urlCode;
    }

    public function copyForm(int $id)
    {
        $form = Elm::createForm(Route::buildUrl('systemMerchantChangeCopy', ['id' => $id])->build());
        $form->setRule([
            Elm::radio('type', '修改类型', 1)
                ->setOptions([
                    ['value' => 1, 'label' => '增加'],
                    ['value' => 2, 'label' => '减少'],
                ]),
            Elm::number('num', '修改数量', $this->dao->getCopyNum($id))->required()
        ]);
        return $form->setTitle('修改复制商品次数');
    }
    /**
     * @Author:Qinii
     * @Date: 2020/10/10
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     */
    public function getLists($data, $page, $limit, $type=1,$where=[])
    {
        $where['status'] = 1;
        $where['mer_state'] = 1;
        $field = 'ACOS(SIN(('.$data["lat"].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$data["lat"].' * 3.1415) / 180 )
                * COS((lat * 3.1415) / 180 ) *COS(('.$data["lng"].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance';
        $fields =$field.',mer_id,mer_name,mark,mer_avatar,status,create_time,category_id,district_addr,care_count,renqizhi,sales';
        if (!empty($data["city_name"])){
            $city_id=Db::name("user_city")->where("city_name",$data["city_name"])->value("city_id");
            $where['city_id'] = $city_id;
        }
        if ($type==1) {

            if ( empty($where['category_id'])){
                $order =  "mer_id desc";
            }else{
                $where['is_best'] = 1;
                $order =  "mer_id desc,distance asc";
            }
        }else if($type==2){
            if ($data["order"]==1){
                $order =  "distance asc";
            }else{
                $order =  ['care_count'=>'desc'];
            }
        }

        $query = $this->dao->search($where);
        $count = $query->count($this->dao->getPk());
        $list =Db::name("merchant")
            ->where($where)
            ->page($page, $limit)
            ->field($fields)
//            ->having('distance <= '.'10000')
            ->order($order)
            ->select()
            ->each(function ($item) {
                $item['label'] ="人气";
//                $item['sales'] =$item["renqizhi"];
                $item['distance'] =sprintf("%.2f",$item['distance']);
                $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
//                var_dump(merchantConfig($item['mer_id'], 'printing_client_id'));exit();
//                $yanglao=merchantConfig($item['mer_id'], 'printing_client_id')/100;
                $base_commission=merchantConfig($item['mer_id'], 'base_commission');
                if($base_commission <= 0){
                    $base_commission= systemConfig("extension_one_rate");
                }
                //商户养老金比例
                $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
                if(!$yanglao){
                    //若商户养老金比例不存在 则使用平台配置
                    $yanglao = systemConfig('yanglaojin_admin');
                }
                $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
                return $item;
            })->toArray();
        $counts=count($list);
        if( $counts<10 && $type==1){
            $ids=[];
            foreach($list as $v){
                $ids[]=$v["mer_id"];
            }
            $city_id=$where["city_id"];
            unset($where["city_id"]);
            $lists =Db::name("merchant")
                ->where($where)
                ->where("city_id","<>",$city_id)
                ->where("mer_id","<>",implode(",",$ids))
                ->page(1, 10-$counts)
                ->field($fields)
                ->order("distance asc")
                ->select()
                ->each(function ($item) {
                    $item['label'] ="人气";
//                    $item['sales'] =$item["renqizhi"];
                    $item['distance'] =sprintf("%.2f",$item['distance']);
                    $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
                    $base_commission=merchantConfig($item['mer_id'], 'base_commission');
                    if($base_commission <= 0){
                        $base_commission= systemConfig("extension_one_rate");
                    }
                    //商户养老金比例
                    $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
                    if(!$yanglao){
                        //若商户养老金比例不存在 则使用平台配置
                        $yanglao = systemConfig('yanglaojin_admin');
                    }
                    $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
                    return $item;
                })->toArray();
            $list=array_merge($list,$lists);
        }
        return compact('count', 'list','where');
    }


    /**
     * @Date: 2020/10/31
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     * @author cabbage
     */
    public function getLst($data, $page, $limit,$where=[])
    {
        //下过单的店铺
        $mer_ids="";
        if (!empty($data["user_id"])){
            $mer_ids=Db::name('store_order')->where("uid",$data["user_id"])->order("order_id desc")->column("mer_id");
            if ($mer_ids){
                $mer_ids=array_unique($mer_ids);
            }
        }


        $where['status'] = 1;
        $where['mer_state'] = 1;
        $where['sxy_submerchant_id'] = 1;
        $field = '';
        if(!empty($data['lat']) && !empty($data['lng'])){
            $field = 'ACOS(SIN(('.$data["lat"].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$data["lat"].' * 3.1415) / 180 )
            * COS((lat * 3.1415) / 180 ) *COS(('.$data["lng"].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance,';
        }else{
            $field = "mer_id as distance";
        }


        $fields =$field.'mer_id,mer_name,mark,mer_avatar,sales,status,create_time,category_id,care_count,sales,district_addr,renqizhi';
        if ($mer_ids){
            $order =  [
                "FIELD (id,{$mer_ids})"=>'desc',
                'sales'=>'desc', //销量
                'care_count'=>'desc', //关注
                'distance'=>"asc"//距离
            ];
        }else{
            $order =  [
                'distance'=>"asc",//距离
                'sales'=>'desc', //销量
                'care_count'=>'desc', //关注
            ];
        }

        if($data["order"]==1){
            $order =  [
                'distance'=>"asc",//距离
                'sales'=>'asc',
                'care_count'=>'asc',
            ];
        }
        $data['distance'] = ($data['distance']&&$data['distance']!=50)?$data['distance']:8000;
        $query = $this->dao->search_mer($where);
        $count = $query->count($this->dao->getPk());

        $list = $query
            ->page($page, $limit)
            ->setOption('field', [])
            ->field($fields)
            ->having('distance <= '.$data['distance'])
            ->order($order)
            ->select()
            ->each(function ($item) {

                $item['popularity'] =$item["renqizhi"];
                $item['sales'] =$item["sales"];
                $item['distance'] =sprintf("%.2f",$item['distance']);
                if ( $item['distance']<=10){
                    $item['label'] ="附近";
                }else{
                    $item['label'] ="附近";
                }
                $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
                $base_commission=merchantConfig($item['mer_id'], 'base_commission');
                if($base_commission <= 0){
                    $base_commission= systemConfig("extension_one_rate");
                }
                //商户养老金比例
                $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
                if(!$yanglao){
                    //若商户养老金比例不存在 则使用平台配置
                    $yanglao = systemConfig('yanglaojin_admin');
                }
                $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
                return $item;
            });


        return compact('count', 'list','order','where');
    }


    /**
     *
     * @param $page
     * @param $limit
     * @return array
     */
    public function merchantcategory()
    {
        return Db::name('merchant_category')->where("status",1)->order("order_sort desc,merchant_category_id desc")->select()->toArray();
    }

    /*商家分类列表*/
    public function mercat($page, $limit)
    {
        $count= Db::name('merchant_category')->count();
        $list= Db::name('merchant_category')->where("status",1)->order("order_sort desc,merchant_category_id desc")->select()->toArray();
        return compact('count', 'list');
    }

    /**
     * @param $id
     * @return Form
     * @throws FormBuilderException
     * @author xaboy
     * @day 2020-05-07
     */
    public function changeProForm($id)
    {
        return Elm::createForm(Route::buildUrl('systemMerchantChangePro', compact('id'))->build(), [
            Elm::input('spread_account', '推荐人')->required()->value("请填写推荐人手机号")
        ])->setTitle('修改商户推荐人');
    }


    /*
    * 修改商户推广人id
    *@author cabbage
    *@date 2020-10-31
    * */
    public function update_spread($id,$spread_account){
        //推荐人信息
        $spread = Db::name("user")->where('account',$spread_account)->value("uid");
        $mer_uid = Db::name("merchant")->where(['mer_id'=>$id])->value("uid");

        if($spread && $mer_uid){
            try{
                Db::name("user")->where(["uid"=>$mer_uid])->update(['spread_uid'=>$spread]);
                Db::name("merchant")->where(["mer_id"=>$id])->update(['recommender'=>$spread]);
                return  true;
            }catch (Exception $e) {
                Db::rollback();
            }
        }else{
            return false;
        }

    }

    /*下架商品*/
    public function MerUpdate($where,$data)
    {
        return Db::name("store_product")->where($where)->update($data);
    }

    /*推荐商品*/
    public function getProductGoodList($id){

        $where['is_gift_bag'] = 0;
        $where['is_used'] = 1;
        $where['product_type'] = 0;
        $where['mer_id'] = $id;
        $where['is_good'] = 1;

        return Db::name("store_product")->where($where)->field("image,product_id,store_name as title,price,ot_price")->select();
    }

    /*收款二维码*/
    public function getQrCode($mer){

        $res = Db::name("MerchantQrcode")
            -> where("mer_id",$mer -> mer_id)
            -> field("qrcode_src as url,show_src")
            -> find();
        if(!$res || $res['url'] == '' || $res['show_src'] == ''){
            Db::name("MerchantQrcode") -> where("mer_id",$mer -> mer_id) -> delete();
            $attachmentRepository = app()->make(AttachmentRepository::class);
            $siteUrl = systemConfig('site_url');

            $merchantIntertion = app() -> make(MerchantIntention::class);
            $id = $merchantIntertion -> getNewQrcodeId();
            $name = "offlinepay_".$id.".jpg";
            $codeUrl = set_http_type(rtrim($siteUrl, '/') .'/offlinepay/index.html?id=' . $id, request()->isSsl() ? 0 : 1);//二维码链接
            $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
            if (!is_string($imageInfo)){
                $imageInfo['dir'] = path_to_url($imageInfo['dir']);
                if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
                $attachmentRepository->create(systemConfig('upload_type') ?: 1, 0, 0, [
                    'attachment_category_id' => 0,
                    'attachment_name' => $imageInfo['name'],
                    'attachment_src' => $imageInfo['dir']
                ]);
                $show_src = $merchantIntertion -> show_src($imageInfo['dir'],$id);
                $codeInsert = [
                    'uid'=>$mer -> uid,
                    'mer_id' =>$mer -> mer_id,
                    'code_id'=>$id,
                    'qrcode_src' => $imageInfo['dir'],
                    'show_src' => $show_src,
                ];
                Db::name('MerchantQrcode') -> insert($codeInsert);
                return ['url'=>$imageInfo['dir'],'show_src'=>$show_src];
            }
            throw new ValidateException('收款码生成失败');
        }
        return $res;

    }

    /**
     * 根据 商户ID 获取 未删除的 商户信息
     * @param int $merchantId
     * @return MerchantEntity
     */
    public function getMerchantEntityByMerchantId(int $merchantId): MerchantEntity
    {
        $entityList = $this->getMerchantEntityListByMerchantIdList([$merchantId]);
        $entity = array_shift($entityList);
        if ($entity instanceof MerchantEntity) {
            return $entity;
        } else {
            /** @var MerchantEntity */
            return MerchantEntity::newInstance();
        }
    }

    /**
     * @param array $idList
     * @return MerchantEntity[]
     */
    public function getMerchantEntityListByMerchantIdList(array $idList): array
    {
        return $this->dao->getMerchantEntityListByMerchantIdList($idList);
    }

}
