<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商户管理
 */
namespace app\allwin\controller;
use think\facade\Request;
use think\Validate;
use app\allwin\model\MchId as MchIdStore;
use app\allwin\model\AllwinStore;
use app\allwin\model\MchIdQueen;
use app\allwin\model\MchIdUser;
use filter\Filter;

class Mchid extends Common{

    public $allwinconfig   = []; 

    public function initialize(){
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'商户管理','url'=>url("mchid/index")]]);
        $this->allwinconfig = model('AllwinConfig')->getConfig($this->member_miniapp_id);
    }

    /**
     * 商户列表
     * @return void
     */
    public function index(int $types = 0){
        $is_pass = 0;
        switch ($types) {
            case 1:
                $is_pass =  0;
                break;
            case 2:
                $is_pass =  1;
                break;
            case 3:
                $is_pass =  2;
                break;
            case 4:
                $is_pass =  -1;
                break;
        }
        $where = [];
        if ($types) {
            $where['is_pass'] = $is_pass;
        }
        $view['lists'] = MchIdStore::where($this->mini_program)->where($where)->order('is_default desc,is_pass desc,id desc')->paginate(20);
        $view['types'] = $types;
        return view()->assign($view);
    }

    /**
     * 商家选择
     * @return void
     */
    public function selectmchid(int $types = 0){
        $keyword = Request::param('keyword');
        if(!empty($keyword)){
            $sql = MchIdStore::where($this->mini_program)->whereLike('merchant_shortname','%'.$keyword.'%'); 
        }else{
            $sql = MchIdStore::where($this->mini_program);
        }
        $where = [];
        $where['is_pass'] = 2;
        $where['status']  = 0;
        $view['lists']   = $sql->where($where)->order('is_default desc,is_pass desc,id desc')->paginate(20);
        $view['input']   = Request::param('input');
        $view['types']   = $types;
        $view['keyword'] = $keyword;
        return view()->assign($view);
    }
    
    /**
     * 商户号预览
     * @return void
     */
    public function review(){
        $condition['id']      = Request::param('id');
        $condition['is_pass'] = 2;
        $info = MchIdStore::where($this->mini_program)->where($condition)->find();
        if(empty($info)){
            $this->error('未找到你要查找的商家信息或管理员更改了商家权限');
        }
        $view['info']  = $info;
        return view()->assign($view);
    }
    
    /**
     * 申请开通小微商户
     * @return void
     */
    public function reg(){
        if(!$this->allwinconfig->is_psp){
            $this->error('非服务商模式,禁止添加小微商户');
        }
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id'  => $this->member_miniapp_id,
                'merchant_shortname' => Request::param('merchant_shortname/s'),
                'store_name'         => Request::param('store_name/s'),
                'store_street'       => Request::param('store_street/s'),
                'contact_phone'      => Request::param('contact_phone/s'),
                'product_desc'       => Request::param('product_desc/s'),
                'store_entrance_pic' => Request::param('store_entrance_pic/s'),
                'indoor_pic'         => Request::param('indoor_pic/s'),
                'id_card_name'       => Request::param('id_card_name/s'),
                'id_card_number'     => Request::param('id_card_number/s'),
                'id_card_copy'       => Request::param('id_card_copy/s'),
                'id_card_national'   => Request::param('id_card_national/s'),
                'account_bank'       => Request::param('account_bank/s'),
                'account_number'     => Request::param('account_number/s'),
                'bank_address_code'  => Request::param('bank_address_code/s'),
                'business_code'      => strtoupper(md5('MIC'.order_no())),
                'member_id'          => $this->user['id'],
            ];
            $validate = $this->validate($data,'MchId.reg');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $id_time['start_time'] = Request::param('start_time/s');
            $id_time['end_time']   = Request::param('end_time/s');
            $validate_time = Validate::make()->rule('start_time', 'require|date')->rule('end_time','date')->check($id_time);
            if(true !== $validate_time){
                return json(['code'=>0,'msg'=>'身份证有效期填写错误']);
            }
            if(!empty($id_time['end_time'])){
                if(strtotime($id_time['start_time']) > strtotime($id_time['end_time'])){
                    return json(['code'=>0,'msg'=>'身份证有效期开始日期不能大于结束日期']);
                }
            }
            $data['id_card_start_time'] = $id_time['start_time'];
            $data['id_card_end_time']   = $id_time['end_time'] ?:'';
            $result =  MchIdStore::reg($data);
            if($result){
                return json(['code'=>200,'url'=>url('mchid/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            return view();
        }
    }

    /**
     * 未通过审核待提交
     * @return void
     */
    public function rebuild(){
        if(!$this->allwinconfig->is_psp){
            $this->error('非服务商模式,禁止添加小微商户');
        }
        if(request()->isAjax()){
            $data = [
                'id'                 => Request::param('id/d'),
                'member_miniapp_id'  => $this->member_miniapp_id,
                'merchant_shortname' => Request::param('merchant_shortname/s'),
                'store_name'         => Request::param('store_name/s'),
                'store_street'       => Request::param('store_street/s'),
                'contact_phone'      => Request::param('contact_phone/s'),
                'product_desc'       => Request::param('product_desc/s'),
                'store_entrance_pic' => Request::param('store_entrance_pic/s'),
                'indoor_pic'         => Request::param('indoor_pic/s'),
                'id_card_name'       => Request::param('id_card_name/s'),
                'id_card_number'     => Request::param('id_card_number/s'),
                'id_card_copy'       => Request::param('id_card_copy/s'),
                'id_card_national'   => Request::param('id_card_national/s'),
                'account_bank'       => Request::param('account_bank/s'),
                'account_number'     => Request::param('account_number/s'),
                'bank_address_code'  => Request::param('bank_address_code/s'),
                'business_code'      => strtoupper(md5('MIC'.order_no())),
                'member_id'          => $this->user['id'],
            ];
            $validate = $this->validate($data,'MchId.reg');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $id_time['start_time'] = Request::param('start_time/s');
            $id_time['end_time']   = Request::param('end_time/s');
            $validate_time = Validate::make()->rule('start_time', 'require|date')->rule('end_time','date')->check($id_time);
            if(true !== $validate_time){
                return json(['code'=>0,'msg'=>'身份证有效期填写错误']);
            }
            if(!empty($id_time['end_time'])){
                if(strtotime($id_time['start_time']) > strtotime($id_time['end_time'])){
                    return json(['code'=>0,'msg'=>'身份证有效期开始日期不能大于结束日期']);
                }
            }
            $data['id_card_start_time'] = $id_time['start_time'];
            $data['id_card_end_time']   = $id_time['end_time'] ?:'';
            $result =  MchIdStore::reg($data);
            if($result){
                return json(['code'=>200,'url'=>url('mchid/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $id = Request::param('id');
            $info = MchIdStore::where(['id' => $id,'is_types' => 1])->where('is_pass','<=','0')->find();
            if(empty($info)){
                $this->error('未找到商家信息');
            }
            $info['start_time'] = $info->id_card_start_time ?:'';
            $info['end_time']   = $info->id_card_end_time ?:'';
            $view['info']       = $info;
            return view()->assign($view);
        }
    }
  
  
    /**
     * 商家关联
     * @return void
     */
    public function add(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'mchid'             => Request::param('mchid/d',0),
                'merchant_shortname'=> Request::param('merchant_shortname/s'),
                'store_name'        => Request::param('store_name/s'),
                'contact_phone'     => Request::param('contact_phone/s'),
                'store_street'      => Request::param('store_street/s'),
                'member_id'         => $this->user->id,
                'business_code'     => strtoupper(md5('MIC'.order_no())),
            ];
            $validate = $this->validate($data,'MchId.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $mchid = MchIdStore::where(['mchid' => $data['mchid']])->count();
            if($mchid){
                return json(['code'=>0,'msg'=>'商户号重复']);
            }
            $result =  MchIdStore::edit($data);
            if($result){
                return json(['code'=>200,'url'=>url('mchid/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            return view();
        }
    }

    /**
     * 商家关联
     * @return void
     */
    public function edit(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'id'                => Request::param('id/d',0),
                'original_mchid'    => Request::param('original_mchid/d',0),
                'mchid'             => Request::param('mchid/d',0),
                'store_name'        => Request::param('store_name/s'),
                'merchant_shortname'=> Request::param('merchant_shortname/s'),
                'contact_phone'     => Request::param('contact_phone/s'),
                'store_street'      => Request::param('store_street/s'),
            ];
            $validate = $this->validate($data,'MchId.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $mchid = MchIdStore::where(['mchid' => $data['mchid']])->where('id','<>',$data['id'])->count();
            if($mchid){
                return json(['code'=>0,'msg'=>'商户号重复']);
            }
            $result =  MchIdStore::edit($data);
            if($result){
                if($data['original_mchid'] != $data['mchid']){
                    MchIdUser::where($this->mini_program)->where(['store_id' => $data['id']])->delete(); //删除队列
                }
                return json(['code'=>200,'url'=>url('mchid/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $condition['id']       = Request::param('id');
            $condition['is_types'] = 0;
            $view['info'] = MchIdStore::where($this->mini_program)->where($condition)->find();
            if(empty($view['info'])){
                $this->error('未找到商家信息');
            }
            return view()->assign($view);
        }
    }

    //删除
    public function delStore(int $id){
        //判断是否有商家在使用
        $info = AllwinStore::where($this->mini_program)->where(['mch_id' => $id])->count();
        if($info){
            return json(['code'=>0,'msg'=>'有加盟商家正在使用当前商户号,禁止删除']);
        }
        //判断分账
        $info = MchIdQueen::where($this->mini_program)->where(['mch_id' => $id])->count();
        if($info){
            return json(['code'=>0,'msg'=>'有分账资源,禁止删除']);
        }
        //删除
        $condition = [];
        $result = MchIdStore::where($this->mini_program)->where($condition)->where(['id' => $id,'is_delete' => 0])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>0,'msg'=>'删除失败']);
        } 
    }

    /**
     * 判断商户是否重复
     * @return boolean
     */
    public function is_mchid(){
        $mchid = Request::param('param/d');
        if(empty($mchid)){
            return json(['status'=>'n','info'=>'未输入值']);
        }
        $result = MchIdStore::where(['mchid' => $mchid])->find();
        if(empty($result)){
            return json(['status'=>'y','info'=>'商户号可用']);
        }else{
            return json(['status'=>'n','info'=>'商户号重复']);
        }
    }
    
    /**
     * 设置平台默认帐号
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $result = MchIdStore::where(['id' => $id])->find();
        if(empty($result->is_pass)){
            return enjson(0,'未通过审核的商户,禁止设为默认商户');
        }
        if($result->is_default == 1){
            return enjson(0,'已是默认商户号,不用重复设置');
        }
        $rel = MchIdStore::where($this->mini_program)->where(['is_default' => 1])->find();
        if($rel){
            $rel->is_default = 0;
            $rel->save();  
        }
        $result->is_default = 1;
        $result = $result->save();
        if(!$result){
            MchIdUser::where($this->mini_program)->where(['mch_id' => $rel->id])->delete(); //删除队列
            return enjson(0,'操作失败');
        }else{
            return enjson(200,'操作成功');
        }
    } 

   /**
     * 查看城市编码
     * @param integer $id 用户ID
     */
    public function bankAddressCode(){
        $parms = [
            'province' => Request::param('province/s'),
            'city'     => Request::param('city/s'),
            'district' => Request::param('district/s')
        ];
        $validate = $this->validate($parms,'MchId.address_code');
        if (true !== $validate) {
            return json(['code'=>403,'msg'=>$validate]);
        }
        $jsonStr = file_get_contents(PATH_STATIC.'allwin/citycode.json');
        $arr = json_decode($jsonStr, true);
        if(empty($arr['中国'][$parms['province']])){
            return json(['code'=>403,'msg'=>'省份和地区不存在']);
        }
        if(empty($arr['中国'][$parms['province']][$parms['city']])){
            $code = $arr['中国'][$parms['province']][$parms['district']]['code'];
        }else{
            $code = $arr['中国'][$parms['province']][$parms['city']][$parms['district']]['code'];
        }
        return json(['code'=>200,'msg'=>'成功','data'=> $code]);
    }

    /**
     * 微信分账队列
     * @return void
     */
    public function queen(int $types = 0,string $order = ''){
        $condition = [];
        if(!empty($order)){
            $condition['out_order_no'] = Filter::filter_escape(trim($order));
        }
        $store_id  = Request::param('store_id',0);
        $store_name  = Request::param('store_name');
        if($store_id){
            $condition['store_id'] = $store_id;
        }
        $view['amount_quree'] = MchIdQueen::where($this->mini_program)->where($condition)->where(['is_finish' => 0])->sum('amount');
        $view['amount_success'] = MchIdQueen::where($this->mini_program)->where($condition)->where(['is_finish' => 2])->sum('amount');
        $view['amount_fail'] = MchIdQueen::where($this->mini_program)->where($condition)->where(['is_finish' => 1])->sum('amount');
        if($types){
            switch ($types) {
                case 2:
                    $is_finish = 2;
                    break;
                case 3:
                    $is_finish = 1;
                    break;
                default:
                    $is_finish = 0;
                    break;
            }
            $condition['is_finish'] = $is_finish;
        }
        $orderby = $types == 1 ? 'id asc':'id desc';
        $view['lists'] = MchIdQueen::where($this->mini_program)->where($condition)->order($orderby)->paginate(10,false,[
            'query' => ['types' => $types,'store_id' => $store_id,'store_name' => $store_name],
        ]);
        $view['types'] = $types;
        $view['order'] = $order;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['pathMaps'] = [['name'=>'结算队列','url'=>url("mchid/queen")]];
        return view()->assign($view);
    }

    /**
     * 重置分账队列
     * @return void
     */
    public function resetQueen(string $order){
        $condition = [];
        $condition['out_order_no'] = Filter::filter_escape(trim($order));
        $condition['is_finish']    = 1;
        $rueen = MchIdQueen::where($this->mini_program)->where($condition)->update(['is_finish' => 0]);
        if($rueen){
            return json(['code'=>200,'message'=>'成功']);
        }else{
            return json(['code'=>0,'message'=>'失败,只有分账失败的才允许重置队列']);
        }
    }

    /**
     * 锁定
     * @param integer $id 用户ID
     */
    public function islock(int $id){
        $result = MchIdStore::isLock($id,$this->member_miniapp_id);
        if($result){
            return enjson(200,'操作成功');
        }else{
            return enjson(0,'操作失败');
        }
    }
}