<?php

namespace app\admin\controller\family;

use app\admin\model\User;
use app\common\controller\Backend;
use app\lib\model\FamilyTreeMateModel;
use app\lib\model\FamilyTreeModel;
use app\lib\service\FamilyTreeService;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class FamilyTree extends Backend
{
    
    /**
     * FamilyTree模型对象
     * @var \app\admin\model\family\FamilyTree
     */
    protected $model = null;
    protected $mate_model = null;
    protected $searchFields = 'id,name,identity_card';
    protected $selectpageFields = "id,name";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\family\FamilyTree;
        $this->mate_model = new \app\admin\model\family\FamilyTreeMate;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with("users,family,parent")
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','create_user_id','family_id','name','sex','identity_card','photo','status','createtime','people_id','users','family','parent']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }





    /**
     * 添加
     */
    public function add($type=0,$parent_id=null)//type（1添加父辈,2添加子辈,3添加配偶
    {
        if ($this->request->isPost()) {
            $params = $this->request->param("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $people=FamilyTreeService::addFamilyPeople($params);
                    if(empty($people)){
                        $this->error("创建成员失败");
                    }
                    $param['people_id']=$people['id'];

                    $param['family_id']=$params['family_id'];//族谱id

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

                    $param['sex']=$params['sex'];

                    $param['identity_card']=$params['identity_card'];

                    $param['photo']=$params['photo'];

                    $param['level']=$params['level'];

                    if($type==1){
                        $param['parent_id'] = 0;
                        $result = $this->model->allowField(true)->save($param);
                        //将父辈绑定关系
                        FamilyTreeModel::dataUpdate(['id'=>$params['parent_id']],['parent_id'=>$this->model->getLastInsID()]);
                    }else if($type==2){//添加子辈
                        $param['parent_id']=$params['parent_id'];
                        $result = $this->model->allowField(true)->save($param);
                        $familyTree=FamilyTreeMateModel::dataInfo(['people_id'=>$param['people_id']]);//查询配偶是否已上族谱
                        if($familyTree && !$familyTree['mother_tree_id']){
                            FamilyTreeMateModel::dataUpdate(['id'=>$familyTree['id']],['mother_tree_id'=>$this->model->getLastInsID()]);
                        }
                    }else if($type==3){//添加配偶
                        unset($param['family_id']);
                        unset($param['level']);
                        $family_tree_id=$param['family_tree_id']=$params['parent_id'];

                        //关联母族
                        $familyTree =FamilyTreeModel::dataInfo(['people_id'=>$param['people_id']]);
                        $familyMate=FamilyTreeMateModel::dataInfo(['people_id'=>$param['people_id']]);//查询配偶是否重婚
                        if($familyTree && empty($familyMate['mother_tree_id'])){
                            $param['mother_tree_id']=$familyTree['id'];
                        }
                        if($familyMate){//验证配偶是否重婚
                            if(!in_array($param['family_tree_id'],explode(",",$familyMate['family_tree_id']))){
                                $param['family_tree_id']=$familyMate['family_tree_id'].",".$family_tree_id;
                            }else if(in_array($family_tree_id,explode(",",$familyMate['family_tree_id']))){
                                $param['family_tree_id']=$familyMate['family_tree_id'];
                            }
                            $result=FamilyTreeMateModel::dataUpdate(['id'=>$familyMate['id']],$param);
                        }else{
                            $result=FamilyTreeMateModel::dataAdd($param);
                        }
                    }else{

                        $result = $this->model->allowField(true)->save($param);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = $this->model->where(['id'=>$parent_id])->find();
        $this->view->assign("row", $row);
        $this->view->assign("type", $type);
        $this->view->assign("parent_id", $parent_id);
        if($row){
            $data=FamilyTreeService::genealogyList($row['family_id'],$row['people_id'],$type);
        }
        $this->view->assign("ext5", isset($data)?$data['val']:'');
        $level = 1;
        if($row && $type==1){
            $level = $row['level'] > 1 ? $row['level']-1 : 1 ;
        } else if($row && $type==2){
            $level = $row['level'] + 1 ;
        }
        $this->view->assign("level", $level);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null,$type=0)
    {
        if($type==3){
            $row = $this->mate_model->get($ids);
        }else{
            $row = $this->model->get($ids);
        }

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->param("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $people=FamilyTreeService::addFamilyPeople($params);
                    if(empty($people)){
                        $this->error("创建成员失败");
                    }
                    $param['people_id']=$people['id'];

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

                    $param['sex']=$params['sex'];

                    $param['identity_card']=$params['identity_card'];

                    $param['photo']=$params['photo'];

                    if($type==3){//添加配偶
                        //关联母族
                        $familyTree =FamilyTreeModel::dataInfo(['people_id'=>$param['people_id']]);
                        $familyMate=FamilyTreeMateModel::dataInfo(['people_id'=>$param['people_id']]);//查询配偶是否重婚
                        if($familyTree && empty($familyMate['mother_tree_id'])){
                            $param['mother_tree_id']=$familyTree['id'];
                        }

                        $param['family_tree_id'] = $params['family_tree_id'];
                        $result=FamilyTreeMateModel::dataUpdate(['id'=>$ids],$param);
                    }else{
                        if(!empty($params['family_id'])) $param['family_id']=$params['family_id'];//族谱id
                        $result = $row->allowField(true)->save($param);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", $type);
        $this->view->assign("people", \app\admin\model\family\FamilyPeople::where(['id'=>$row['people_id']])->find());
        return $this->view->fetch();
    }


    public function details($people_id = null)
    {
        $row=\app\admin\model\family\FamilyPeople::where(['id'=>$people_id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row['village_id']){
            $village = Db::name('addr_village')->where(['village_code' => $row['village_id']])->find();
            $row['MergerName']=$village['province'].",".$village['city'].",".$village['county'].",".$village['town'].",".$village['village'];
        }else if($row['town_id']){
            $town = Db::name('addr_village')->where(['town_code' => $row['town_id']])->find();
            $row['MergerName'] = $town['province'].",".$town['city'].",".$town['county'].",".$town['town'];
        }else if($row['area_id']){
            $area = Db::name('addr')->where(['ID' => $row['area_id']])->find();
            $row['MergerName'] = $area['MergerName'];
        }else{
            $row['MergerName']='';
        }
        $this->view->assign("people", $row);
        return $this->view->fetch();
    }


    /**
     * 字辈列表
     */
    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);
    }

}
