<?php
namespace Admin\Controller;

use Common\Controller\AdminController;
use Niaoyun\Admin\AdminLog;
use Niaoyun\BasePage;
use EB\Api\EpowerTrademarkFile;
use EB\Services\EmailMessage;
use EB\Services\SmsMessage;
use Home\Service\TmService;
use Home\Service\PricesService;
use Home\Service\PointsService;
/**
 * create by ZHG
 *
 * 商标文件
 * Class TmOrderController
 * @package Admin\Controller
 */
class TmfilesController extends AdminController
{
	public function __construct()
	{
		parent::__construct();
	}

	///商标列表
	public function index()
	{
		$pagesize = I('pagesize', 20, 'intval');
		$page = I('get.page',1,'intval');

		$userid = I('user_id');

		$where=array();
		if(!empty($userid)){
			$where['tm_files.userid'] = $userid;
		}
		$keyword = I('get.keyword');
		$status = I('get.status');
		if(!empty($keyword)){
			$where[] = [
				'tm_files.applyno'=>$keyword,
				'tm_orders.name'=>$keyword,
				'_logic' => 'OR'
			];
		}
		if(!empty($status)){
			$where['tm_files.status'] = $status;
		}
		$start_time_reg = I('get.start_time_reg');
		$end_time_reg = I('get.end_time_reg');
		if(!empty($start_time_reg) && !empty($end_time_reg)){
  		   $where['tm_files.uploadtime'] = array('between', array($start_time_reg,$end_time_reg . ' 23:59:59'));
  	   }

		$count = M("tm_files")->where($where)->count();
		$page = new BasePage($count, $pagesize,array(),false);
        $page->setFormID('search_form');
		$show = $page->pagination();

		$files = M("tm_files")->field('tm_files.*,tm_orders.name as name,tm_services.tmname as tmname')->join('left join tm_orders on tm_orders.applynumber = tm_files.applyno')->join('left join tm_services on tm_services.applyno = tm_files.applyno')->where($where)->limit($page->firstRow . ',' . $page->listRows)->order('id desc')->select();

		$this->assign('files', $files);
		$this->assign('products', M('tm_products')->getField('remindinfo,type'));
		$this->assign('page', $show);

		$this->assign('user_id', $userid);
		$this->assign('pagesize', $pagesize);
		$this->assign('keyword', $keyword);
		$this->assign('status', empty($status) ? '-1' : status);
		$this->assign('start_time_reg', $start_time_reg);
		$this->assign('end_time_reg', $end_time_reg);

		$this->display();
	}

	///商标列表
	public function fetch()
	{
		$pagesize = I('pagesize', 20, 'intval');
		$page = I('get.page',1,'intval');

		$userid = I('user_id');

		$where=array();
		if(!empty($userid)){
			$where['userid'] = $userid;
		}
		$keyword = I('get.keyword');
		if(!empty($keyword)){
			$where[] = [
				'receiver'=>$keyword,
				'phone'=>['like', '%' . $keyword . '%'],
				'address'=>['like', '%' . $keyword . '%'],
				'memo'=>['like', '%' . $keyword . '%'],
				'_logic' => 'OR'
			];
		}
		$status = I('get.status');
		if(!empty($status)){
			$where['status'] = $status;
		}
		$start_time_reg = I('start_time_reg');
		$end_time_reg = I('end_time_reg');
		$start_time_exp = I('start_time_exp');
		$end_time_exp = I('end_time_exp');
		if(!empty($start_time_reg) && !empty($end_time_reg)){
 		   $where['fetchtime'] = array('between', array($start_time_reg,$end_time_reg . ' 23:59:59'));
 	   }
 	   if(!empty($start_time_exp) && !empty($end_time_exp)){
 		   $where['posttime'] = array('between', array($start_time_exp,$end_time_exp . ' 23:59:59'));
 	   }
		$count = M("tm_files_fetch")->where($where)->count();
		$page = new BasePage($count, $pagesize,array(),false);
        $page->setFormID('search_form');
		$show = $page->pagination();

		$files = M("tm_files_fetch")->where($where)->limit($page->firstRow . ',' . $page->listRows)->order('id desc')->select();

		$this->assign('files', $files);
		$this->assign('page', $show);

		$this->assign('user_id', $userid);
		$this->assign('keyword', $keyword);
		$this->assign('pagesize', $pagesize);
		$this->assign('status', empty($status) ? '-1' : status);
		$this->assign('start_time_reg', $start_time_reg);
		$this->assign('end_time_reg', $end_time_reg);
		$this->assign('start_time_exp', $start_time_exp);
		$this->assign('end_time_exp', $end_time_exp);
		$this->assign('status_enum', ['待审核','审核不通过','审核通过','已邮寄','已放弃']);

		$this->display();
	}
    public function fetchshow()
    {
        if (IS_POST) {
            $id = I('post.id', 0, 'intval');
            $api = M('tm_files_fetch')->where(array('id' => $id))->find();
            if (!$api) {
                $this->ajaxError('参数错误', $returnURL, C('TIPS_TIMEOUT'));
            }
            $returnURL = U('admin/tmfiles/fetch', array('id' => $id));
            $model = M('tm_files_fetch');
            $data = $model->create(I('post.'));
            if (!$data) {
                $this->ajaxError($model->getError(), $returnURL, C('TIPS_TIMEOUT'));
                return;
            }
            if ($id == 0) {
                $this->ajaxError('参数错误', $returnURL, C('TIPS_TIMEOUT'));
            }
            if (isset($data['posttime']) && empty($data['posttime'])) {
                unset($data['posttime']);
            }
            $result = $model->where(array('id' => $id))->save($data);
            if ($result !== false) {
                AdminLog::SaveLog(AdminLog::tmfiles_fetch_edit, $id, null, $data, UID); //存log
                $this->ajaxSuccess('编辑成功', $returnURL, C('TIPS_TIMEOUT'));
                return true;
            }
            $this->ajaxError($model->getError(), $returnURL, C('TIPS_TIMEOUT'));
            return;
        }
        $id = I('id');
        $api = M('tm_files_fetch')->where(array('id' => $id))->find();
        $this->assign('products', M('tm_products')->getField('remindinfo,type'));
        $this->assign('api', $api);
        $this->assign('files', M('tm_files')->where(['fetchid' => $id])->field('filetype,bisnisstype,applyno,id,file')->select());
        $this->display();
    }

    public function showpic(){
        $id = I('get.id', 0, 'intval');
        $file = M('tm_files')->where(['id'=>$id])->find();
        if(!$file || empty($file['guid'])){
            $this->error('发文不存在');
        }
        if(!is_dir(ROOT_PATH . 'Uploads/tmfiles')){
            mkdir(ROOT_PATH . 'Uploads/tmfiles');
        }
        $filename = ROOT_PATH . 'Uploads/tmfiles/'. $file['guid'] . 'jpg';
        if(is_file($filename)){
            $str = file_get_contents($filename);
        }else{
            $api = new EpowerTrademarkFile();
            $str = $api->getpic($file['guid']);
            if(substr($str, 0,1)=='{'){
                $result = json_decode($str, true);
                $this->error($result['message']);
            }
            file_put_contents($filename, $str);
        }
        $ext = substr($str, 0, 4);
        if($ext == '%PDF'){
            header('Content-Type: application/pdf');
        }else{
            header('Content-Type: image/png');
        }
		echo $str;
    }

    //修改发文
    public function edit()
    {
        if (IS_POST) {
            $id = I('post.id', 0, 'intval');
            $returnURL = U('admin/tmfiles/index', array('id' => $id));
            $model = M('tm_files');
            $data = $model->create(I('post.'));
            if (!$data) {
                $this->ajaxError($model->getError(), $returnURL, C('TIPS_TIMEOUT'));
                return;
            }
            //根据bisnisstype查询用户id
            if (in_array($data['bisnisstype'], ['zhuce', 'zhucebm', 'zhucedb'])) {
                $info = M('tm_orders')->where(['applynumber' => $data['applyno']])->find();
                $data['userid'] = $info['userid'];
                $data['bisnisstype'] = $info['producttype'];
                $data['producttype'] = $info['producttype'];
            } else {
                $info = M('tm_services')->where(['applyno' => $data['applyno']])->find();
                $data['userid'] = $info['userid'];
                $data['bisnisstype'] = $info['type'];
            }
            if (!$info) {
                $this->ajaxError('业务未找到', $returnURL, C('TIPS_TIMEOUT'));
            }
            $data['sync_status'] = I('post.sync_status', '');
            M()->startTrans();
            if ($id == 0) {
                unset($data['id']);
                $data['uploadtime'] = date('Y-m-d H:i:s');
                $result = $model->add($data);
                if ($result !== false) {
                    $res = true;
                    $time = date('Y-m-d H:i:s', time());
                    if (!empty($data['sync_status'])) {
                        if (in_array($data['bisnisstype'], ['zhuce', 'zhucebm', 'zhucedb'])) {
                            $res = M('tm_orders')->where(['id' => $info['id']])->save(['status' => $data['sync_status'], 'audittime' => $time]);
                        } else {
                            $res = M('tm_services')->where(['id' => $info['id']])->save(['status' => $data['sync_status']]);
                        }
                        AdminLog::SaveLog(AdminLog::tmeditorder, $info['id'], $data['sync_status'], $data, UID); //存log
                    }
                    $result = $res;
                }
            } else {
                $result = $model->where(array('id' => $id))->save($data);
                if ($result !== false) {
                    $res = true;
                    $time = date('Y-m-d H:i:s', time());
                    if (!empty($data['sync_status'])) {
                        if (in_array($data['bisnisstype'], ['zhuce', 'zhucebm', 'zhucedb'])) {
                            $res = M('tm_orders')->where(['id' => $info['id']])->save(['status' => $data['sync_status'], 'audittime' => $time]);
                        } else {
                            $res = M('tm_services')->where(['id' => $info['id']])->save(['status' => $data['sync_status']]);
                        }
                        AdminLog::SaveLog(AdminLog::tmeditorder, $info['id'], $data['sync_status'], $data, UID); //存log
                    }
                    $result = $res;
                }
            }
            if ($result !== false) {
                if($data['sync_status'] == '已发受理通知'){
                    $user = M('users')->find($info['userid']);
                    $pid = TmService::get_productid($info['producttype']);
                    $basemoney = PricesService::getMoney('tm', $pid, $user['id'],$user['groupid'], 1);
                    $addmoney = PricesService::getMoney('tm', $pid, $user['id'],$user['groupid'], 1,1);
                    $goods = $this->get_goods($info['goodsnamearray']);
                    $goods_count = count($goods);
                    if($goods_count <= 10){
                        $money = $basemoney;
                    }else{
                        $money = $basemoney + ($goods_count - 10)*$addmoney;
                    }
                    //获取佣金
                    $coupon_val = PointsService::getPoints('tm', $info['productid'],$money);
                    if($coupon_val>0){
                        // 添加佣金记录
                        PointsService::addPoints($info['userid'],'tm',$info['productid'],$info['id'],$coupon_val);
                    }
                }
                $data['name'] = $info['name'];
                if (empty($data['sync_status'])) {
                    $data['status'] = $info['status'];
                } else {
                    $data['status'] = $data['sync_status'];
                }
                $this->check_status($info, $data);
            }
            if ($result !== false) {
                M()->commit();
                AdminLog::SaveLog(AdminLog::tmfiles_edit, $id, null, $data, UID); //存log
                $this->ajaxSuccess('编辑成功', $returnURL, C('TIPS_TIMEOUT'));
                return true;
            }
            M()->rollback();
            $this->ajaxError($model->getError(), $returnURL, C('TIPS_TIMEOUT'));
            return;
        }

        $id = I('id');
        $api = M('tm_files')->where(array('id' => $id))->find();
        if (!$api) {
            $api = array('id' => 0);
        }
        $this->assign('products', M('tm_products')->getField('remindinfo,type'));
        $this->assign('api', $api);
        $this->display();
    }

    private function get_goods($goods){
        if(empty($goods)){
            return [];
        }
        $goods = base64_decode($goods);
        if(!$goods){
            return [];
        }
        return explode('&nbsp;', $goods);
    }

    private function send_notify($old, $template, $data, $user, $wx)
    {
        if (in_array($old['producttype'], ['zhuce', 'zhucebm', 'zhucedb'])) {
            $email = new EmailMessage(4);
            $email->PostUser($user['id'], $template, $data, $user['email']);
            $applyer = M("tm_applyer")->where(['id' => $old['applyerid']])->find();
            if (!$applyer) {
                return;
            }
            if ($applyer['email'] != $user['email']) {
                $email->PostUser($user['id'], $template, $data, $applyer['email']);
            }
            $sms = new SmsMessage(2);
            $res = $sms->PostUser($user['id'], $template, $data, $applyer['receivephone']);
        }else{
            $sms = new SmsMessage(2);
            $res = $sms->PostUser($user['id'], $template, $data, $old['contact']);
        }

    }

    private function check_status($old, $new)
    {
//        if($old['status'] != $new['status']){
        $userModel = D('Users');
        $user = $userModel->find($old['userid']);
        if (!$user) {
            return;
        }
        if (in_array($new['producttype'], ['zhuce', 'zhucebm', 'zhucedb'])) {
            $data['cls'] = $old['cls'];
            $data['tm'] = $new['name'];
            $template = 'tm_status_change';
            if ($new['status'] == '待确认') {
                $template = 'tm_status_confirm';
                $data['reason'] = $new['auditmemo'];
            } else if ($new['status'] == '审核不通过') {
                $template = 'tm_status_no';
                $data['reason'] = $new['auditmemo'];
            } else if ($new['status'] == '商标被驳回') {
                $template = 'tm_status_back';
            } else if ($new['status'] == '商标部分驳回') {
                $template = 'tm_status_partback';
            } else {
                $data['status_old'] = $old['status'];
                $data['status_new'] = $new['status'];
            }
            $this->send_notify($old, $template, $data, $user, [
                'userid' => $user['id'],
                'title' => '商标名称：' . $new['name'],
                'type' => '商标注册状态变更',
                'new_status' => $new['status']
            ]);
        }else{
            $tms_name = M('tm_products')->where(array('remindinfo'=>$old['type'],'product_type'=>'service'))->getField('type');
            if(!$tms_name){
                return;
            }
            $data['tms'] = $tms_name;
            $template = 'tms_status_change';
            $data['status_old'] = $old['status'];
            $data['status_new'] = $new['status'];
            $this->send_notify($old, $template, $data, $user, [
                'userid' => $user['id'],
                'title' => '商标服务名称：' . $new['type'],
                'type' => '商标服务状态变更',
                'new_status' => $new['status']
            ]);
        }

//        }
    }
}
