<?php
/**
 * Created by PhpStorm.
 * User: zzl
 * Date: 2016/11/4
 * Time: 14:54
 * @author:zzl(郑钟良) zzl@ourstu.com
 */

namespace Admin\Controller;


use Admin\Builder\AdminConfigBuilder;
use Admin\Builder\AdminListBuilder;

class AttestController extends AdminController
{

    protected $attestModel, $attestTypeModel;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->attestModel=D('Ucenter/Attest');
        $this->attestTypeModel=D('Ucenter/AttestType');
    }

    public function attestList($page = 1, $r = 20)
    {
        $aAttestTypeId = I('get.attest_type_id', 1, 'intval');
        $attest_type = $this->attestTypeModel->getData($aAttestTypeId, 1);
        if (!$attest_type) {
            $this->error('非法操作！');
        }
        $attest_type_list=$this->attestTypeModel->getTypeList();
        $type_options=array();
        foreach ($attest_type_list as $val){
            $type_options[]=array('id'=>$val['id'],'value'=>$val['title']);
        }
        unset($val);
        $aStatus = I('get.status', 0, 'intval');
        if(!$aStatus){
            $map['status'] = array('in', '1,2,0');
        }else{
            $map['status'] = $aStatus-1;
        }
        $map['attest_type_id'] = $attest_type['id'];
        list($list, $totalCount) = $this->attestModel->getListPage($map, $page, 'status desc,create_time desc', $r);
        foreach ($list as &$val) {
            $val['attest_type_title'] = $attest_type['title'];
        }
        unset($val);
        $builder = new AdminListBuilder();
        $builder->title('认证用户列表')
            ->select('','attest_type_id','select','','','',$type_options)
            ->setSelectPostUrl(U('Attest/attestList'))
            ->select('','status','select','','','',array(array('id'=>3,'value'=>'待审核'),array('id'=>2,'value'=>'已审核'),array('id'=>1,'value'=>'禁用'),array('id'=>0,'value'=>'全部')))
            ->setStatusUrl(U('Attest/setAttestStatus'))->buttonEnable('','通过审核')
            ->buttonModalPopup(U('Attest/setAuditReason'),'','审核失败/禁用',array('data-title'=>'设置审核失败或禁用原因','target-form'=>'ids'))->buttonDelete()
            ->keyId()
            ->keyUid()
            ->keyText('attest_type_title', '认证类型');
        if ($attest_type['fields']['child_type'] != 0) {
            $builder->keyText('child_type', '认证分类');
        }
        if ($attest_type['fields']['company_name'] != 0) {
            $builder->keyText('company_name', '公司名称');
        }
        if ($attest_type['fields']['name'] != 0) {
            $builder->keyText('name', '真实姓名');
        }
        if ($attest_type['fields']['id_num'] != 0) {
            $builder->keyText('id_num', '身份证编号');
        }
        if ($attest_type['fields']['phone'] != 0) {
            $builder->keyText('phone', '联系方式');
        }
        if ($attest_type['fields']['image_type'] != 0) {
            $builder->keyText('image_type', '证件类型');
        }
        if ($attest_type['fields']['prove_image'] != 0) {
            $builder->keyMultiImage('prove_image', '企业、组织证明材料');
        }
        if ($attest_type['fields']['image'] != 0) {
            $builder->keyMultiImage('image', '证件正反面照');
        }
        if ($attest_type['fields']['other_image'] != 0) {
            $builder->keyMultiImage('other_image', '其他证明材料');
        }
        if ($attest_type['fields']['info'] != 0) {
            $builder->keyText('info', '认证补充');
        }

        $builder->keyStatus()
            ->keyCreateTime()
            ->keyUpdateTime()
            ->data($list)
            ->pagination($totalCount, $r)
            ->display();
    }

    public function setAuditReason()
    {
        if(IS_POST){
            $aIds=I('post.ids','','text');
            $aReason=I('post.reason','','text');
            if(strlen($aReason)<10){
                $this->error('审核失败原因不能少于10个字');
            }
            $map['id']=array('in',$aIds);
            $map['status']=array('in','1,2');
            $attestList=$this->attestModel->where($map)->select();
            $res=$this->attestModel->where($map)->save(array('reason'=>$aReason,'status'=>0));
            if($res){
                $uids=array_column($attestList,'uid');
                foreach ($uids as $val){
                    clean_query_user_cache($val,array('avatars_html','attest'));
                }
                send_message($uids,'你的认证申请已被拒绝或禁用','系统拒绝或禁用了你的认证申请，如有疑问请联系系统管理员','Ucenter/Attest/process',array(),1);
                $this->success('操作成功！','refresh');
            }else{
                $this->error('操作失败，请检查所选认证是否是禁用状态。');
            }
        }else{
            $aIds=I('get.ids',0,'intval');
            !is_array($aIds)&&$aIds=explode(',',$aIds);
            $ids=implode(',',$aIds);
            $this->assign('audit_ids',$ids);
            $this->display('reason');
        }
    }

    public function setAttestStatus($ids,$status=1)
    {
        !is_array($ids)&&$ids=explode(',',$ids);
        $attest_list=$this->attestModel->getListByMap(array('id'=>array('in',$ids)));
        $uids=array_column($attest_list,'uid');
        if($status==1){
            foreach ($uids as $val){
                clean_query_user_cache($val,array('avatars_html','attest'));
            }
            send_message($uids,'你的认证申请已通过','系统通过了你的认证申请','Ucenter/Attest/process',array(),1);
        }else if($status==0){
            $this->error('请点击顶部‘审核失败/禁用’按钮，设置理由');
            return false;
        }
        $builder=new AdminListBuilder();
        $builder->doSetStatus('Attest',$ids,$status);
    }

    public function attestTypes()
    {
        $list = $this->attestTypeModel->getTypeList(array('gt', -1));
        foreach ($list as &$val) {
            $val['privilege'] = str_replace('1', '专属认证图标', $val['privilege']);
            $val['privilege'] = str_replace('2', '优先推荐', $val['privilege']);
            $val['privilege'] = str_replace('3', '各类特权', $val['privilege']);

            $val['condition'] = '<a href="' . U('setCondition', array('id' => $val['id'])) . '">设置</a>';
            $val['fields'] = '<a href="' . U('setFields', array('id' => $val['id'])) . '">设置</a>';
            if($val['logo']==0){
                $val['logo']=__ROOT__.'/Public/images/attest/'.$val['id'].'-logo.png';
            }
        }
        unset($val);
        $builder = new AdminListBuilder();
        $builder->title('认证类型列表')
            ->keyId()
            ->keyText('name', '标识')
            ->keyTitle()
            ->keyText('tips', '认证小提示')
            ->keyImage('logo', '图标')
            ->keyText('privilege', '特权')
            ->keyText('description', '认证说明')
            ->keyHtml('condition', '认证条件')
            ->keyHtml('fields', '认证字段')
            ->keyDoActionEdit('editType?id=###')
            ->data($list)
            ->display();
    }

    public function setCondition()
    {
        $aId = I('id', 0, 'intval');
        $attest_type = $this->_checkTypeExist($aId, 1);
        if (IS_POST) {
            $data['conditions'][] = 'avatar:' . I('post.avatar', 1, 'intval');
            $data['conditions'][] = 'phone:' . I('post.phone', 1, 'intval');
            $data['conditions'][] = 'follow:' . I('post.follow', 30, 'intval');
            $data['conditions'][] = 'fans:' . I('post.fans', 30, 'intval');
            $data['conditions'][] = 'friends:' . I('post.friends', 2, 'intval');
            $data['conditions'] = implode('|', $data['conditions']);
            $data['id'] = I('post.id', 0, 'intval');
            $res = $this->attestTypeModel->editData($data);
            if ($res !== false) {
                $this->success('编辑成功！', U('attestTypes'));
            } else {
                $this->error('编辑失败！');
            }
        } else {
            $conditions = $attest_type['conditions'];
            $conditions['id'] = $attest_type['id'];
            $builder = new AdminConfigBuilder();
            $builder->title($attest_type['title'] . '-认证条件配置')
                ->keyId()
                ->keyBool('avatar', '上传高清头像', '', array('0' => '非必须', '1' => '必须'))
                ->keyBool('phone', '绑定手机号', '', array('0' => '非必须', '1' => '必须'))
                ->keyInteger('follow', '关注人数大于', '0表示无限制')
                ->keyInteger('fans', '粉丝数大于', '0表示无限制')
                ->keyInteger('friends', '互粉认证用户大于', '相互关注即为好友')
                ->data($conditions)
                ->buttonSubmit()
                ->buttonBack()
                ->display();
        }
    }

    public function setFields()
    {
        $aId = I('id', 0, 'intval');
        $attest_type = $this->_checkTypeExist($aId, 1);
        if (IS_POST) {
            $aChildType = I('post.child_type', 1, 'intval');
            $aChildTypeOption = I('post.child_type_option', '', 'text');
            if ($aChildType != 0 && $aChildTypeOption == '') {
                $this->error('认证分类选择范围不能为空');
            }

            $aImageType = I('post.image_type', 1, 'intval');
            $aImageTypeOption = I('post.image_type_option', '', 'text');
            if ($aImageType != 0 && $aImageTypeOption == '') {
                $this->error('证件类型选择范围不能为空');
            }

            $fields[] = 'child_type:' . I('post.child_type', 1, 'intval');
            $fields[] = 'child_type_option:' . I('post.child_type_option', '', 'text');
            $fields[] = 'company_name:' . I('post.company_name', 1, 'intval');
            $fields[] = 'name:' . I('post.name', 1, 'intval');
            $fields[] = 'id_num:' . I('post.id_num', 1, 'intval');
            $fields[] = 'phone:' . I('post.phone', 1, 'intval');
            $fields[] = 'image_type:' . I('post.image_type', 1, 'intval');
            $fields[] = 'image_type_option:' . I('post.image_type_option', '', 'text');
            $fields[] = 'prove_image:' . I('post.prove_image', 1, 'intval');
            $fields[] = 'image:' . I('post.image', 1, 'intval');
            $fields[] = 'other_image:' . I('post.other_image', 1, 'intval');
            $fields[] = 'other_image_tip:' . I('post.other_image_tip', '', 'text');
            $fields[] = 'info:' . I('post.info', 1, 'intval');

            $data['fields'] = implode('|', $fields);
            $data['id'] = I('post.id', 0, 'intval');
            $res = $this->attestTypeModel->editData($data);
            if ($res !== false) {
                $this->success('编辑成功！', U('attestTypes'));
            } else {
                $this->error('编辑失败！');
            }
        } else {
            $fields = $attest_type['fields'];
            $fields['id'] = $attest_type['id'];
            $builder = new AdminConfigBuilder();
            $options = array(0 => '无', 1 => '必填', 2 => '非必填');
            $builder->title($attest_type['title'] . '认证类型资料要求设置')
                ->keyId()
                ->keyRadio('child_type', '认证分类', '是否要选择该信息', array(0 => '无', 1 => '有'))
                ->keyText('child_type_option', '认证分类选择范围', "以','分割，认证分类不为'无'时，需配置该项")
                ->keyRadio('company_name', '企业、组织名', '是否要填写该信息', $options)
                ->keyRadio('name', '真实姓名', '', $options)
                ->keyRadio('id_num', '身份证编号', '', $options)
                ->keyRadio('phone', '联系方式', '', $options)
                ->keyRadio('image_type', '证件类型', '', array(0 => '无', 1 => '有'))
                ->keyText('image_type_option', '证件类型选择范围', "身份证、残疾证等，以','分割，认证分类不为'无'时，需配置该项")
                ->keyRadio('prove_image', '企业、组织证明', '', $options)
                ->keyRadio('image', '个人证件正反面照', '', $options)
                ->keyRadio('other_image', '其他证明材料', '', $options)
                ->keyText('other_image_tip', '其他证明材料说明')
                ->keyRadio('info', '认证补充说明', '是否要填写该信息', $options)
                ->data($fields)
                ->buttonSubmit()
                ->buttonBack()
                ->display();
        }
    }

    public function editType()
    {
        $aId = I('id', 0, 'intval');
        $attest_type = $this->_checkTypeExist($aId);
        if (IS_POST) {
            $data = $this->attestTypeModel->create();
            $res = $this->attestTypeModel->editData($data);
            if ($res !== false) {
                $this->success('编辑成功！', U('attestTypes'));
            } else {
                $this->error('编辑失败！');
            }
        } else {
            $builder = new AdminConfigBuilder();
            $builder->title('编辑认证类型(认证条件和认证要输入的信息，在其它地方设置)')
                ->keyId()
                ->keyReadOnly('name', '标识', '由字母组成')
                ->keyTitle('title', '标题', '认证类型名称')
                ->keyText('tips', '认证小提示')
                ->keySingleImage('logo', '图标')
                ->keyCheckBox('privilege', '特权', '认证成功后拥有特权', array(1 => '专属认证图标', 2 => '优先推荐', 3 => '各类特权'))
                ->keyEditor('description', '认证说明')
                ->keyStatus()
                ->data($attest_type)
                ->buttonSubmit()
                ->buttonBack()
                ->display();
        }
    }

    private function _checkTypeExist($id, $init = 0)
    {
        $attest_type = $this->attestTypeModel->getData($id, $init);
        if (!$attest_type) {
            $this->error('该认证类型不存在！');
        }
        return $attest_type;
    }
}