<?php


namespace app\api\controller;



use app\api\model\Addr;
use app\api\model\PaymentLogModel;
use app\api\model\RechargeModel;
use app\api\model\UsersModel;
use app\common\controller\Api;
use app\lib\model\FamilyModel;
use app\lib\model\FamilyPeopleModel;
use app\lib\model\FamilyTreeModel;
use app\lib\model\SurnameModel;
use app\lib\service\AddressService;
use think\addons\Service;
use think\Db;
use think\Exception;

class Family extends Api
{

    protected $noNeedLogin = ['surnamelist'];

    /**
     * 姓氏列表
     */
    public function surnameList(){
        $data=SurnameModel::dataList([],1000);
        $this->success('',$data['data']);
    }


    /**
     * 个人中心认领族谱
     */
    public function claimFamilyPeople(){
        $grandpa_name=$this->request->param("grandpa_name");//爷爷名字
        $parent_name=$this->request->param("parent_name");//父亲名字
        $name=$this->request->param("name");//自己名字
        $fastim_id = $this->request->param("fastim_id");//IMid

        $people_id=$this->request->param("people_id");//选择自己id

        if(!empty($people_id)){
            $people=FamilyPeopleModel::dataInfo(['id'=>$people_id]);
            if(empty($people)){
                $this->error("改成员不存在");
            }else if($people && $people['user_id']){
                $this->error("该成员已被账户关联");
            }
            $res=FamilyPeopleModel::dataUpdate(['id'=>$people_id],['user_id'=>$this->auth->id,'fastim_id' =>$fastim_id]);
            $this->success("该用户认领成功",$res);
        }else{
            $data=FamilyTreeModel::claimFamilyPeople(['ft1.name'=>$name,'ft2.name'=>$parent_name,'ft3.name'=>$grandpa_name]);
            $this->success("",$data);
        }
    }




    /**
     * 查看所创建的族谱
     */
    public function familyList(){
        $source=$this->request->param("source",2);//0首页，1我的族谱，2创建族谱，
       /* if($source == 2 && $this->auth->is_shaikh==0){
            $this->error("您还未申请为族长");
        }*/
        if($source == 2){
            $data=FamilyModel::dataList(['create_user_id'=>$this->auth->id]);
        }else {
            $FamilyPeople = FamilyPeopleModel::dataList(['user_id'=>$this->auth->id]);
            $arr = [];
            foreach ($FamilyPeople as $key=>$val){
                $FamilyTree=FamilyModel::myFamilyTreeList("ft.people_id = " . $val['id']);
                $FamilyTreeMate=FamilyModel::myFamilyTreeMateList("ftm.people_id = " . $val['id']);
                array_push($arr,$FamilyTree,$FamilyTreeMate);
            }
            $data =call_user_func_array("array_merge",$arr);
        }
        $arr = [];
        foreach ($data as $key=>$val){
            if($val['village_id']){
                $addr=Db::name('addr_village')->where(['village_code'=>$val['village_id']])->find();
                $data[$key]['addr']=$addr?$addr['province'].$addr['city'].$addr['county'].$addr['town'].$addr['village']:'';
            }else if($val['town_id']){
                $addr=Db::name('addr_village')->where(['town_code'=>$val['town_id']])->find();
                $data[$key]['addr']=$addr?$addr['province'].$addr['city'].$addr['county'].$addr['town']:'';
            }else if($val['area_id']){
                $addr=Db::name("addr")->where(['ID'=>$val['area_id']])->field('ID as value,Name as name, ParentId,MergerName')->find();
                $data[$key]['addr']= $addr['MergerName'];
            }
            if($val['type'] == 2){//有族谱就显示族谱
                $arr[]=$val;
            }
            if(!$arr && $val['type'] == 1){
                $arr[] = $val;
            }
        }

        $this->success("",$source==0?$arr:$data);
    }


    /**
     * 创建族谱
     */
    public function addFamily(){
        $params['surname_id']=$this->request->param("surname_id");
        $params['type']=$this->request->param("type");//类型:1=家谱,2=族谱,3=宗谱
        if($params['type'] > 2){//只有家谱可以随意创建
            if($this->auth->is_shaikh==0){
                $this->error("您还未申请为族长！");
            }
        }
        if(empty($params['surname_id'])){
            $this->error("请选择姓氏");
        }
        $params['realname']=$this->request->param("realname");
        $params['family_name']=Db::name("surname")->where(['ID'=>$params['surname_id']])->value("Surname");
        $params['province_id']=$this->request->param("province_id");
        $params['city_id']=$this->request->param("city_id");
        $params['area_id']=$this->request->param("area_id");
        $params['town_id']=$this->request->param("town_id");
        $params['village_id']=$this->request->param("village_id");
        $params['address']=$this->request->param("address");
        $params['create_user_id']=$this->auth->id;
        $params['rw_user_id']=$this->auth->id;
        $params['fastim_id']=$this->request->param("fastim_id");
        $params['genealogy']=$this->request->param("genealogy");
        if(empty($params['genealogy'])){
            $this->error("请输入族谱字辈");
        }
        if(empty($params['province_id']) || empty($params['city_id']) || empty($params['area_id']) || empty($params['town_id'])){
            $this->error("请选择地址");
        }
        $res=FamilyModel::dataAdd($params);
        $this->success("创建谱成功",$res);
    }


    /**
     * 查询某个族谱
     */
    public function familyInfo(){
        $id=$this->request->param("id");
        if(empty($id)){
            $this->error("该参数有误");
        }

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

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



    /**
     * 修改族谱
     */
    public function updateFamily(){
        $id=$this->request->param("id");
        if(empty($id)){
            $this->error("该参数有误");
        }
        $params['province_id']=$this->request->param("province_id");
        $params['city_id']=$this->request->param("city_id");
        $params['area_id']=$this->request->param("area_id");
        $params['town_id']=$this->request->param("town_id");
        $params['village_id']=$this->request->param("village_id");
        $params['address']=$this->request->param("address");
        if(empty($params['province_id']) || empty($params['city_id']) || empty($params['area_id']) || empty($params['town_id'])){
            $this->error("请选择地址");
        }
        $data=FamilyModel::dataUpdate(['id'=>$id],$params);

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

    /**
     * 加入族谱
     */
   /* public function joinFamily(){
        $name=$this->request->post("name",'');
        $sex=$this->request->post("sex",1);//性别:0=未知,1=男,2=女
        $identity_card=$this->request->post("identity_card",'');//身份证号
        $photo=$this->request->post("photo",'');
        $level=$this->request->post("level",null);
        $type=$this->request->post("type",'');
        $parent_id=$this->request->post("parent_id",0);
        $people_id=$this->request->post("people_id",0);
        $pay_way = $this->request->post('pay_way', 'weixin');//支付方式:weixin=微信,money=钱包,alipay=支付宝
        $amount = $this->request->post('amount', 0);//下单金额
        $uid = $this->auth->id;
        $data=[
            'create_user_id' =>$uid,
            'family_id' =>$uid,
            'name' =>$name,
            'sex' =>$sex,
            'identity_card' =>$identity_card,
            'photo' =>$photo,
            'level' =>$level,
            'type' =>$type,
            'parent_id' =>$parent_id,
            'status' =>0,
            'createtime' =>time(),
            'people_id' =>$people_id,

        ];
        try{
            Db::startTrans();
            $ret = FamilyTreeModel::create($data);
            if($ret->id){
                $recharge_data = [
                    'tree_id' =>$ret->id,
                    'user_id' =>$uid,
                    'amount' =>$amount,
                    'payamount' =>$amount,
                    'ip' =>$this->request->ip(),
                    'createtime' =>time(),
                    'memo' =>'加入族谱认证费用',
                ];
                $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 getFamilyList()
    {
        $page = $this->request->param('page',1);
        $keywords = $this->request->param('keywords','');
        $where['status'] = 1;
        $where['type'] = ['in',[2,3]];
        if($this->auth->surname_id) $where['surname_id'] = $this->auth->surname_id;
        if($keywords){
            $where['family_name|realname|address'] = ['like','%'.$keywords.'%'];
        }
        $list = FamilyModel::dataList($where,"*,FROM_UNIXTIME(createtime,'%Y年%m月%d日') as createtime","id DESC",$page,$this->pageSize);
        foreach ($list as $key=>$val){
            if($val['village_id']){
                $addr=Db::name('addr_village')->where(['village_code'=>$val['village_id']])->find();
                $list[$key]['addr']=$addr?$addr['province'].$addr['city'].$addr['county'].$addr['town'].$addr['village']:'';
            }else if($val['town_id']){
                $addr=Db::name('addr_village')->where(['town_code'=>$val['town_id']])->find();
                $list[$key]['addr']=$addr?$addr['province'].$addr['city'].$addr['county'].$addr['town']:'';
            }else if($val['area_id']){
                $addr=Db::name("addr")->where(['ID'=>$val['area_id']])->field('ID as value,Name as name, ParentId,MergerName')->find();
                $list[$key]['addr']= $addr['MergerName'];
            }
        }
        $this->success("获取成功",['list' =>$list]);
    }

    /**
     * 获取公开的族谱详情
     */
    public function getFamilyDetail()
    {
        $family_id = $this->request->param('family_id',0);
        if(!$family_id){
            $this->error('此家谱已不存在');
        }
        $info = FamilyModel::datainfo(['id' =>$family_id]);
        $avatar = $this->auth->getUserinfo()['avatar'];
        $res = Db::name('family_record')->where(['user_id' =>$this->auth->id,'family_id' =>$family_id])->find();
        if(!$res){
            $data = [
                'user_id' =>$this->auth->id,
                'family_id' =>$family_id,
                'createtime' =>time(),
                'avatar' =>$avatar
            ];
            Db::name('family_record')->insert($data);
            FamilyModel::where(['id' =>$family_id])->setInc('read_records',1);
        }
        $info['rw_user_id'] = explode(",",$info['rw_user_id']);

        $info['is_show'] = false;

        $familyTreePeople=FamilyTreeModel::myFamilyTreePeople(["ft.family_id"=>$family_id,'fp.user_id'=>$this->auth->id]);

        if(in_array($this->auth->id,$info['rw_user_id']) || $familyTreePeople ){
            $info['is_show'] = true;
        }


        $this->success("获取成功",['info' =>$info]);

    }

}