<?php


namespace app\api\controller;


use app\api\model\PaymentLogModel;
use app\api\model\RechargeModel;
use app\common\controller\Api;
use app\common\library\Redis\RedisMaster;
use app\lib\model\FamilyModel;
use app\lib\model\FamilyPeopleModel;
use app\lib\model\FamilyTreeMateModel;
use app\lib\model\FamilyTreeModel;
use app\lib\model\SurnameModel;
use app\lib\service\FamilyTreeService;
use fast\Tree;
use think\Db;
use think\Exception;

class FamilyTree extends Api
{

    protected $noNeedLogin = ['familytreeview','searchtree','familytreelist'];


    /**
     * 查询族谱树状图
     */
    public function familyTreeList(){
        $family_id=$this->request->param("family_id");//族谱id
        $keywords=$this->request->param("keywords","");//搜索关键词
        $people_id=$this->request->param("people_id",0);

        if(empty($family_id)){
            $this->error("该参数有误！");
        }

        $family=FamilyModel::dataInfo(['id'=>$family_id]);

        $family_tree_id=$this->request->param("family_tree_id");//查看某个人节点上一代，下三代含自己（4带）

        if(empty($family_tree_id)){
            $map['ft.family_id']=$family_id;
            if($keywords){
                $map['ft.name']=['like',"%$keywords%"];
            }else if($people_id){
                $map['fp.id']= $people_id;
            }else{
                $map['fp.user_id']= $this->auth->id;
            }
            $familyTreePeople=FamilyTreeModel::myFamilyTreePeople($map);
            if($familyTreePeople){
                $family_tree_id=$familyTreePeople['id'];
            }

            ///查看是否有权限
            $myFamily=FamilyTreeModel::myFamilyTreePeople(["ft.family_id"=>$family_id,'fp.user_id'=>$this->auth->id]);
            if(!in_array($this->auth->id,explode(",",$family['rw_user_id'])) && $family['type'] != 1 && empty($myFamily) ){
                $this->error("暂未查到您加入族谱信息");
            }

            ////////////////管理员默认查看祖先代数
            if(empty($family_tree_id)) $family_tree_id=FamilyTreeModel::where(['family_id'=>$family_id,'parent_id'=>0])->order("id asc")->value("id");
        }
        if($family_tree_id){//根据接单查询某三代
            
            $parentFamily=FamilyTreeModel::parentFamilyTree($family_tree_id);
            if(isset($parentFamily[2])){$ids = $parentFamily[2]['_id'];
            }else if(isset($parentFamily[1])){$ids = $parentFamily[1]['_id'];}else{$ids = $parentFamily[0]['_id'];}

            $data=FamilyTreeModel::recursionFamilyTreePeopleList($ids);
            foreach ($data as $key=>$val){
                $data[$key]["mate"]=FamilyTreeMateModel::familyTreeMatePeopleList("FIND_IN_SET(".$val['id'].",ftm.family_tree_id)");
                $data[$key]["num"]= $val['parent_id']==0?1:FamilyTreeModel::where(['family_id'=>$family_id,'parent_id'=>$val['parent_id']])->count();
            }
            $parentFamily=FamilyTreeModel::dataInfo(['family_id'=>$family_id,'id'=>$ids]);
            $data=getRecursion($data,isset($parentFamily['parent_id'])?$parentFamily['parent_id']:$ids);
        }else{
            $data=FamilyTreeModel::familyTreePeopleList(['ft.family_id'=>$family_id]);
            foreach ($data as $key=>$val){
                $data[$key]["mate"]=FamilyTreeMateModel::familyTreeMatePeopleList("FIND_IN_SET(".$val['id'].",ftm.family_tree_id)");
                $data[$key]["num"]= $val['parent_id']==0?1:FamilyTreeModel::where(['family_id'=>$family_id,'parent_id'=>$val['parent_id']])->count();
            }
            $data=getRecursion($data);
        }
        $this->success("",$data);
    }

    /**
     * 树谱搜索人名
     */
    public function searchTree()
    {
        $family_id=$this->request->param("family_id");//族谱id
        $keywords=$this->request->param("keywords","");//搜索关键词
        $field = "ft.parent_id,fp.user_id as people_user_id,fp.name as people_name,fp.ext0,fp.ext1,fp.ext2,fp.ext5,fp.id as people_id,FROM_UNIXTIME(fp.createtime,'%Y年%m月%d日') as createtime";
        $people_list=FamilyTreeModel::myFamilyTreePeopleList(["ft.family_id"=>$family_id,'ft.name'=>['like',"%$keywords%"]],$field);
        if(!$people_list){
            $this->error("暂无数据");
        }
        foreach ($people_list as $key => $val){
            $parent = FamilyTreeModel::where(['id' =>$val['parent_id']])->value('name');
            $people_list[$key]['parent_name'] = $parent;
        }
        $this->success("获取成功",$people_list);
    }

    /**
     * 查看静态树状图
     */
    public function familyTreeView()
    {

        $family_id = $this->request->post('family_id',0);//家谱id
      /*  $id_arr = FamilyTreeModel::where(['family_id'=>$family_id,'level' =>['neq',10]])->column('id');//
        $arr_1111=['赵埠村','石山村','荆陵村','北坑村','钟家村','大岭村','艾家村','藕塘村','三阳村'];
        $arr = FamilyTreeMateModel::where(['family_tree_id' =>['in',$id_arr]])->select();
        foreach ($arr as $k=>$v){
            $sleep_place_key = array_rand($arr_1111);
            FamilyPeopleModel::where(['id' =>$v['people_id']])->update(['sleep_place' =>'江西省南昌市进贤县赵埠乡凤凰村']);
        }
        dump(11111);die;
        $redis = RedisMaster::gi();
        $redis->select(6);
        $prefix = 'family:' . $family_id;*/
        $list = FamilyTreeModel::where(['family_id'=>$family_id])->field('id,name,parent_id')->order('id','asc')->select();
        $data = [];
        foreach ($list as $key=>$val){
            $list[$key]["mate"] = FamilyTreeMateModel::where("FIND_IN_SET(".$val['id'].",family_tree_id)")->field('name')->select();
            if($key == 0){
                $data[] = $val;
            }
        }
        $list = Tree::instance()->init($list, 'parent_id')->getTreeArr($list[0]['id']);
        foreach ($data as $k=>$v){
            $data[$k]['childlist'] = $list;
        }
        $this->success("获取成功",$data);
    }

    /**
     * 点击族员查看个人信息
     */
    public function familyPeopleInfo(){
        $people_id=$this->request->param("people_id");
        $data=FamilyPeopleModel::dataInfo(['id'=>$people_id]);
        $this->success("",$data);
    }

    //模糊查询族员个人信息
    public function  dimFamilyPeople(){
        $where['type'] = 1;
        $province_id=$this->request->param("province_id");
        if(!empty($province_id)) $where['province_id']=$province_id;
        $city_id=$this->request->param("city_id");
        if(!empty($city_id)) $where['city_id']=$city_id;
        $area_id=$this->request->param("area_id");
        if(!empty($area_id)) $where['area_id']=$area_id;
        $town_id=$this->request->param("town_id");
        if(!empty($town_id)) $where['town_id']=$town_id;
        $village_id=$this->request->param("village_id");
        if(!empty($village_id)) $where['village_id']=$village_id;

        $skeyword=$this->request->param("skeyword",'');
        if(!empty($skeyword)){
            $where['name|identity_card|ext3|ext4|address'] = ['like',"%".$skeyword."%"];
        }
        $data=FamilyPeopleModel::dataList($where);
        $this->success("",$data);
    }

    /**
     * 字辈列表
     */
    public function genealogyList(){
        $family_id=$this->request->param("family_id");
        $people_id=$this->request->param("people_id");
        $type=$this->request->param("type","0"); //0自己，1父辈，2子辈

        if(empty($family_id)){
            $this->error("参数错误");
        }

        $data=FamilyTreeService::genealogyList($family_id,$people_id,$type);

        $this->success("",$data);
    }

    /**
     * 添加初始化成员
     */
    public function addCreateFamily(){

        $params=self::verifyFamily();

        $family=FamilyModel::dataInfo(['id'=>$params['family_id']]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id'])) && $family['type'] != 1 ){
            $this->error("该账户无权限！");
        }

        $people=FamilyTreeService::addFamilyPeople($this->request->param());

        $params['people_id']=$people['id'];

        $res=FamilyTreeModel::dataAdd($params);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id'])) && $people['ext0'] == 0){

            $this->success("添加成功！",$people);

        }

        $this->success("添加成功！",[]);
    }

    /**
     * 添加父辈成员
     */
    public function addParentFamily(){
        $child_id=$this->request->param("child_id");//子辈id

        $params=self::verifyFamily();

        $family=FamilyModel::dataInfo(['id'=>$params['family_id']]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))  && $family['type'] != 1){
            $this->error("该账户无权限！");
        }

        $people=FamilyTreeService::addFamilyPeople($this->request->param());

        FamilyTreeModel::where(['family_id'=>$params['family_id']])->setInc("level");//修改代系

        $params['people_id']=$people['id'];

        $res=FamilyTreeModel::dataAdd($params);

        //将父辈绑定关系
        FamilyTreeModel::dataUpdate(['id'=>$child_id],['parent_id'=>$res->getLastInsID()]);


        if(!in_array($this->auth->id,explode(",",$family['rw_user_id'])) && $people['ext0'] == 0){

            $this->success("添加成功！",$people);

        }

        $this->success("添加成功！",[]);
    }


    /**
     * 添加子辈成员
     */
    public function addChildFamily(){

        $params=self::verifyFamily();

        $params['parent_id']=$this->request->param("parent_id");//父亲id

        if(empty($params['parent_id'])){
            $this->error("请选择上级成员");
        }

        $family=FamilyModel::dataInfo(['id'=>$params['family_id']]);

        $parentTree =FamilyTreeModel::dataInfo(['id'=>$params['parent_id']]);//节点父id

        $parentPeople=FamilyPeopleModel::dataInfo(['id'=>$parentTree['people_id']]);//节点父id信息

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))  && $family['type'] != 1
          && ($parentTree['create_user_id'] == $this->auth->id || $parentPeople['user_id'] == $this->auth->id )){
            $this->error("该账户无权限！");
        }

        $people=FamilyTreeService::addFamilyPeople($this->request->param());

        $params['people_id']=$people['id'];

        $res=FamilyTreeModel::dataAdd($params);

        $familyTree=FamilyTreeMateModel::dataInfo(['people_id'=>$params['people_id']]);//查询配偶是否已上族谱
        if($familyTree && !$familyTree['mother_tree_id']){
            FamilyTreeMateModel::dataUpdate(['id'=>$familyTree['id']],['mother_tree_id'=>$res->getLastInsID()]);
        }

        $people['family_tree_id'] = isset($res['id'])?$res['id']:$res->getLastInsID();//生成假数据特给的
        if(!in_array($this->auth->id,explode(",",$family['rw_user_id'])) && $people['ext0'] == 0){

            $this->success("添加成功！",$people);

        }

        $this->success("添加成功！",$people);
    }


    /**
     * 添加配偶成员
     */
    public function addMateFamily(){

        $params=self::verifyFamily();

        $params['family_tree_id']= $family_tree_id=$this->request->param("family_tree_id");//配偶id

        unset($params['level']);

        $hubbyFamilyTree=FamilyTreeModel::myFamilyTreePeople(['ft.id'=>$family_tree_id]);//配偶(丈夫)

        $family=FamilyModel::dataInfo(['id'=>$params['family_id']]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))  && $family['type'] != 1
            && ($hubbyFamilyTree['create_user_id'] == $this->auth->id || $hubbyFamilyTree['people_user_id'] == $this->auth->id)){
            $this->error("该账户无权限！");
        }

        if(isset($params['family_id']))   unset($params['family_id']);

        $people=FamilyTreeService::addFamilyPeople($this->request->param());

        $params['people_id']=$people['id'];

        $familyMate=FamilyTreeMateModel::dataInfo(['people_id'=>$params['people_id']]);//查询配偶是否重婚

        $familyTree=FamilyTreeModel::dataInfo(['people_id'=>$params['people_id']]);//查询配偶是否已上族谱
        if($familyTree && !$familyMate['mother_tree_id']){
            $params['mother_tree_id']=$familyTree['id'];
        }

        if($familyMate){//验证配偶是否重婚
            if(!in_array($family_tree_id,explode(",",$familyMate['family_tree_id']))){
                $params['family_tree_id']=$familyMate['family_tree_id'].",".$family_tree_id;
            }else if(in_array($family_tree_id,explode(",",$familyMate['family_tree_id']))){
                $params['family_tree_id']=$familyMate['family_tree_id'];
            }
            $res=FamilyTreeMateModel::dataUpdate(['id'=>$familyMate['id']],$params);

        }else{

            $res=FamilyTreeMateModel::dataAdd($params);

        }


        if(!in_array($this->auth->id,explode(",",$family['rw_user_id'])) && $people['ext0'] == 0){

            $this->success("添加成功！",$people);

        }

        $this->success("添加成功！",[]);
    }


    /**验证基本
     * @return mixed
     */
    protected function verifyFamily(){

        $params['family_id']=$this->request->param("family_id");//族谱id

        $params['create_user_id']= $this->auth->id;

        $surname=$this->request->param("surname");

        $firstname=$this->request->param("firstname");

        $params['name']=$surname.$firstname;

        $params['sex']=$this->request->param("sex");

        $params['identity_card']=$this->request->param("identity_card");

        $params['photo']=$this->request->param("photo");

        $params['level']=$this->request->param("level");

        if(empty($params['family_id'])){
            $this->error("请选择族谱");
        }

        if(empty($surname)){
            $this->error("请输入姓");
        }

        if(empty($firstname)){
            $this->error("请输入名");
        }

        $family=FamilyModel::dataInfo(['id'=>$params['family_id']]);

        if(empty($family)){
            $this->error("该族谱不存在");
        }

        return $params;
    }


    /**
     * 修改族谱成员
     */
    public function updateFamilyPeople(){

        $family_id=$this->request->param("family_id");//族谱id

        $surname=$this->request->param("surname");

        $firstname=$this->request->param("firstname");

        $params['name']=$surname.$firstname;

        $params['sex']=$this->request->param("sex");

        $params['identity_card']=$this->request->param("identity_card");

        $params['photo']=$this->request->param("photo");

        $params['level']=$this->request->param("level");

        $people_id=$this->request->param("people_id");//成员
        if(empty($people_id)){
            $this->error("请选择成员");
        }

        $people=FamilyPeopleModel::dataInfo(['id'=>$people_id]);
        if(empty($people)){
            $this->error("该成员不存在！");
        }

        if(empty($surname)){
            $this->error("请输入姓");
        }

        if(empty($firstname)){
            $this->error("请输入名");
        }

        $familyTree=FamilyTreeModel::dataInfo(['people_id'=>$people_id]);

        $familyTreeMate=FamilyTreeMateModel::dataInfo(['people_id'=>$people_id]);


        $family=FamilyModel::dataInfo(['id'=>$family_id]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))  && $family['type'] != 1
            && ($people['user_id'] == $this->auth->id || ($familyTree && $familyTree['create_user_id'] == $this->auth->id)
            || ($familyTreeMate && $familyTreeMate['create_user_id'] == $this->auth->id ))){

            $this->error("该账户无权限！");

        }

        
        if($familyTree && ($familyTree['create_user_id'] == $this->auth->id || $people['user_id'] == $this->auth->id)){
            FamilyTreeModel::dataUpdate(['people_id'=>$people_id],$params);
            $res=FamilyTreeService::addFamilyPeople($this->request->param());
        }


        if($familyTreeMate && ($familyTreeMate['create_user_id'] == $this->auth->id || $people['user_id'] == $this->auth->id)){
            unset($params['level']);
            FamilyTreeMateModel::dataUpdate(['people_id'=>$people_id],$params);
            $res=FamilyTreeService::addFamilyPeople($this->request->param());
        }

        $this->success("修改成功");
    }

    /**
     * 删除族谱成员
     */
    public function deleteFamilyTree(){

        $family_tree_id=$this->request->param("family_tree_id");//族谱

        $family_id=$this->request->param("family_id");//族谱id

        $family=FamilyModel::dataInfo(['id'=>$family_id]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))){

            $this->error("该账户无权限！");

        }

        if(empty($family_tree_id)){
            $this->error("参数错误！");
        }

        $familyTree=FamilyTreeModel::dataInfo(['id'=>$family_tree_id]);

        if(FamilyTreeModel::dataInfo(['parent_id'=>$family_tree_id])){
            $this->error("该成员已绑定子女");
        }

        if(FamilyTreeMateModel::dataInfo("FIND_IN_SET(".$family_tree_id.",family_tree_id)")){
            $this->error("该成员已绑定配偶");
        }

        $people=FamilyPeopleModel::dataInfo(['id'=>$familyTree['people_id']]);
        if(empty($people)){
            $this->error("该成员不存在！");
        }

        if($familyTree['create_user_id'] != $this->auth->id || $people['user_id'] != $this->auth->id ||
            !in_array($this->auth->id,explode(",",$family['rw_user_id']))){
            $this->error("该账户无权限！");
        }


        FamilyTreeModel::dataDel(['id'=>$family_tree_id]);

        FamilyTreeMateModel::dataUpdate(['mother_tree_id'=>$family_tree_id],['mother_tree_id'=>null]);

        $this->success("删除成功！");
    }

    /**
     * 删除配偶
     */
    public function deleteFamilyTreeMate(){

        $family_tree_id=$this->request->param("family_tree_id");//族谱

        $mate_tree_id=$this->request->param("mate_tree_id");//配偶

        $family_id=$this->request->param("family_id");//族谱id

        $family=FamilyModel::dataInfo(['id'=>$family_id]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))){

            $this->error("该账户无权限！");

        }

        if(empty($family_tree_id) || empty($mate_tree_id)){
            $this->error("参数错误！");
        }


        $familyTreeMate= FamilyTreeMateModel::dataInfo(['id'=>$mate_tree_id]);

        $people=FamilyPeopleModel::dataInfo(['id'=>$familyTreeMate['people_id']]);
        if(empty($people)){
            $this->error("该成员不存在！");
        }


        if($familyTreeMate['create_user_id'] != $this->auth->id || $people['user_id'] != $this->auth->id ||
            !in_array($this->auth->id,explode(",",$family['rw_user_id']))){
            $this->error("该账户无权限！");
        }


        $ids=explode(",",$familyTreeMate['family_tree_id']);
        if(count($ids) >1){
            $key=array_search($family_tree_id,$ids);
            array_splice($ids,$key,1);
            FamilyTreeMateModel::dataUpdate(['id'=>$mate_tree_id],['family_tree_id'=>implode(",",$ids)]);
        }else{
            FamilyTreeMateModel::dataDel(['id'=>$mate_tree_id]);
        }

        $this->success("删除成功！");
    }

    /**
     * 加入族谱
     */
    public function joinFamilyOrder(){
        $number=$this->request->post("number",'');//用户编号
        $pay_way = $this->request->post('pay_way', 'weixin');//支付方式:weixin=微信,money=钱包,alipay=支付宝
        $amount = $this->request->post('amount', 0);//下单金额
        $peopleinfo = FamilyPeopleModel::dataInfo(['number' =>$number]);
        if($peopleinfo && $peopleinfo['is_pay'] >0){
            $this->error("该成员已支付过认证费");
        }
        if(!$peopleinfo){
            $this->error("该成员不存在");
        }
        if($peopleinfo['ext0'] == 1){
            $this->error("该成员不需缴纳费用");
        }
        if($peopleinfo['sex'] == 1){
            $treeinfo = FamilyTreeModel::dataInfo(['people_id' =>$peopleinfo['id']]);
        }else{
            $treeinfo = FamilyTreeMateModel::dataInfo(['people_id' =>$peopleinfo['id']]);
        }
        $uid = $this->auth->id;
        try{
            Db::startTrans();
            $recharge_data = [
                'tree_id' =>$treeinfo['id'],
                'people_id' =>$peopleinfo['id'],
                'user_id' =>$uid,
                'amount' =>$amount,
                'payamount' =>$amount,
                'ip' =>$this->request->ip(),
                'createtime' =>time(),
                'memo' =>'加入族谱认证费用',
                'is_certification' =>1
            ];
            $res = RechargeModel::create($recharge_data);//创建订单
            $pay_data = [
                'user_id' =>$uid,
                'order_sn' =>getOrdersn('recharge'),
                'order_id' =>$res->id,
                'need_pay' =>$amount,
                'order_type' =>'recharge',
                'pay_way' =>$pay_way,
                'createtime' =>time(),
            ];
            $pay_info = PaymentLogModel::create($pay_data);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('加入失败',$e->getMessage());
        }

        $this->success("加入成功,去支付",['info' =>$pay_info->toArray()]);
    }

    /**
     * 名人堂列表
     */
    public function celebrityList(){
        $page = $this->request->param('page',1);
        $type = $this->request->param('type',1);
        $map['type'] = 2;
        $map['status'] = 1;
        if($type == 2){//同姓
            $Surname=SurnameModel::where(["ID"=>$this->auth->surname_id])->value("Surname");
            $map['surname'] = $Surname;
        }else if($type == 3){//同省
            $map['province_id'] = $this->auth->province_id;
        }else if($type == 4){//同城
            $map['city_id'] = $this->auth->city_id;
        }
        $data=FamilyPeopleModel::where(['type'=>2,'status'=>1])->field("*")->page($page)->limit(10)->order("ranking desc,id desc")->select();
        $this->success("",$data);
    }

    /**
     * 审核列表
     */
    public function auditPeopleList(){
        $family_id=$this->request->param("family_id");//族谱id

        $FamilyTree=FamilyTreeModel::myFamilyTreePeople(["ft.family_id" =>$family_id,'fp.audit'=>0]);

        $this->success("",$FamilyTree);
    }

    public function auditPeople(){
        $family_id=$this->request->param("family_id");//族谱id

        $people_id=$this->request->param("people_id");

        $audit=$this->request->param("audit",1);

        $family=FamilyModel::dataInfo(['id'=>$family_id]);

        if(!in_array($this->auth->id,explode(",",$family['rw_user_id']))){

            $this->error("该账户无权限！");

        }
        $status= $audit==1?1:0;

        FamilyPeopleModel::dataUpdate(['id'=>$people_id],['status'=>$status,'audit'=>$audit]);
        
        $this->success("审核成功");
    }





}