<?php
/**
 *
 * @author min晓天
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');
global $_GPC, $_W;
$tmpl="doweb/";
// var_dump($tmpl);die();
$settings = $this->module['config'];
load()->func('tpl');
$operation = ! empty($_GPC['op']) ? $_GPC['op'] : 'display';
$sid = $_SESSION['sid'];
mload()->model('sms');
//判断是否登录,如果没有登录，请重新登录
if (empty($sid)){
    message("您的登录出错！请重新登录。",$this->createMobileUrl('doweblogin'),'error');
}
if ($operation == 'display') {
        $status = intval($_GPC['status']);
        if(!empty($status)){
            $ids = $_GPC['id'];
            $id = intval($ids);

            if (!is_array($ids)) {
                $ids = array(
                    $id
                );
            }
            foreach ($ids as $id) {
                $order = pdo_fetch("SELECT * FROM " . tablename('evzg_express_order') . " WHERE id = '$id'");
                $express = pdo_fetch("SELECT * FROM" . tablename("evzg_express_expres") . "WHERE id='{$order['eid']}'");
               if ($_GPC['status'] == 1) {
                 $template = array(
                    "touser" => $order['openid'],
                    "template_id" => $settings['msg']['order_yysu_id'],
                    "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
                    "topcolor" => "#FF0000",
                    "data" => array(
                        'first' => array(
                            'value' => urlencode("您好，你的快递{$express['expresssn']}预约上门成功" . "\\n"),
                            'color' => "#743A3A"
                        ),
                        'keyword2' => array(
                            'value' => urlencode(date('Y年m月d日 H:i', time())),
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => urlencode("上门取件"),
                            'color' => '#EF4F4F'
                        ),
                        'remark' => array(
                            'value' => urlencode("{$_GPC['description']}"),
                            'color' => "#01579b"
                        )
                    )
                );
             $result =  sendMsg(urldecode(json_encode($template)));

            }
            if ($_GPC['status'] == 2) {
                $template = array(
                    "touser" => $order['openid'],
                    "template_id" => $settings['msg']['order_yyerr_id'],
                    "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
                    "topcolor" => "#FF0000",
                    "data" => array(
                        'first' => array(
                            'value' => urlencode("您好，你的快递{$express['expresssn']}预约上门失败" . "\\n"),
                            'color' => "#743A3A"
                        ),
                        'keyword3' => array(
                            'value' => urlencode($order['address']),
                            'color' => '#000000'
                        ),
                        'keyword2' => array(
                            'value' => urlencode(date('Y年m月d日 H:i', time())),
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => urlencode("上门取件"),
                            'color' => '#EF4F4F'
                        ),
                        'remark' => array(
                            'value' => urlencode("{$_GPC['description']}"),
                            'color' => "#01579b"
                        )
                    )
                );
               $result= sendMsg(urldecode(json_encode($template)));
            }
                $data['status'] =$_GPC['status'];
                $result = pdo_update("evzg_express_order",$data,array('id'=>$id));
            }
            if($result){
                message('更新状态成功', referer(), 'success');
            }else{
                message('更新状态失败', referer(), 'error');
            }
        }
    if (empty($sid)) {
        message('抱歉，非法请求');
    }
    $shop = pdo_fetch("SELECT * FROM " . tablename('evzg_express_shop') . " WHERE uniacid = '{$_W['uniacid']}' AND id = '{$sid}' ");
    if (empty($shop)) {
        message('抱歉，店铺不存在');
    }

    $condition = ' WHERE uniacid = :aid AND sid = :sid';
    $params[':aid'] = $_W['uniacid'];
    $params[':sid'] = $sid;
    $ordersn = trim($_GPC['ordersn']);
    if (! empty($ordersn)) {
        $condition .= " AND orderno = :orderno";
        $params[':orderno'] = $ordersn;
    }
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('evzg_express_order') . $condition, $params);
    $list = pdo_fetchall('SELECT * FROM ' . tablename('evzg_express_order') . $condition . ' ORDER BY id DESC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize, $params);
    $yytotal = pdo_fetchcolumn('SELECT COUNT(*) FROM' . tablename('evzg_express_order') . "WHERE sid='{$sid}'"); // 预约取件
    $dtotal = pdo_fetchcolumn('SELECT COUNT(*) FROM' . tablename('evzg_express_expres') . "WHERE sid='{$sid}' AND status=0"); // 待取件
    $ytotal = pdo_fetchcolumn('SELECT COUNT(*) FROM' . tablename('evzg_express_expres') . "WHERE sid='{$sid}' AND status=1"); // 已取件
    foreach ($list as &$v) {
        $member = pdo_fetch("SELECT * FROM" . tablename("evzg_express_member") . "WHERE openid='{$v['openid']}'");
        $expres = pdo_fetch("SELECT * FROM" . tablename("evzg_express_expres") . "WHERE id='{$v['eid']}'");
        $v['mobile'] = $member['mobile'];
        $v['nickname'] = $member['nickname'];
        $v['expresssn'] = $expres['expresssn'];
        unset($v);
    }
    // 分页
    $pager = pagination($total, $pindex, $psize);
    include $this->template($tmpl.'shop');
} elseif ($operation == 'post') {
    $sid = intval($_GPC['sid']);
    $id = intval($_GPC['id']);
    if (! empty($id)) {
        $express = pdo_fetch("SELECT * FROM " . tablename('evzg_express_expres') . " WHERE id = '$id'");
    } else {
        $shops = array(
            'displayorder' => 0
        );
    }
    if (checksubmit('submit')) {
        if (empty($_GPC['expresssn'])) {
            message('抱歉，请输入快件码名称！');
        }
        if (empty($_GPC['mobile'])) {
            message('抱歉，请输入手机号名称！');
        }
        $expresssn = $_GPC['expresssn'];
        $x =$_GPC['x'];
        $orderno =  $x.substr($expresssn,-2).build_order_no();
       // var_dump($orderno);die();
        $isorderno = pdo_fetch("SELECT * FROM".tablename("evzg_express_expres")."WHERE orderno='{$orderno}'");
        if(!empty($isorderno)){
            $orderno = $orderno.rand(0,9);
        }
        $data = array(
            'uniacid' => $_W['uniacid'],
            'orderno' => $orderno,
            'expresssn' => $_GPC['expresssn'],
            'enabled' => intval($_GPC['enabled']),
            'displayorder' => intval($_GPC['displayorder']),
            'sid' => intval($_GPC['sid']),
            'description' => $_GPC['description'],
            'mobile' => $_GPC['mobile'],
            'status' => $_GPC['status'],
            'weight' => floatval($_GPC['weight']),
            'thumb' => $_GPC['thumb'],
            'createtime' => time()
        );
        $evgShop = getEvgShop($expresssn);
        if ($evgShop) {
            $data['shipperCode'] = $evgShop['shippercode'];
            $data['expressshop'] = $evgShop['shippername'];
        }
        if (! empty($id)) {
            unset($data['parentid']);
            pdo_update('evzg_express_expres', $data, array(
                'id' => $id
            ));
            load()->func('file');
            file_delete($_GPC['thumb_old']);
        } else {
            $settings = $this->module['config'];
            $result = pdo_insert('evzg_express_expres', $data);
            $id = pdo_insertid();
            $member = pdo_fetch("SELECT * FROM" . tablename("evzg_express_member") . "WHERE mobile='{$_GPC['mobile']}'");
            $shop = pdo_fetch("SELECT * FROM" . tablename("evzg_express_shop") . "WHERE id='{$_GPC['sid']}'");
            if(!empty($member['openid'])){
                if($shop['msgtype']==1||$shop['msgtype']==3){
                    $template = array(
                        "touser" => $member['openid'],
                        "template_id" => $settings['msg']['order_dz_id'],
                        "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
                        "topcolor" => "#FF0000",
                        "data" => array(
                            'first' => array(
                                'value' => urlencode("您好，你的快递{$data['expresssn']}已经到达{$shop['name']}门店" . "\\n"),
                                'color' => "#743A3A"
                            ),
                            'keyword1' => array(
                                'value' => urlencode($data['orderno']),
                                'color' => '#000000'
                            ),
                            'keyword2' => array(
                                'value' => urlencode($data['expresssn']),
                                'color' => '#EF4F4F'
                            ),
                            'keyword3' => array(
                                'value' => urlencode($shop['name']),
                                'color' => '#EF4F4F'
                            ),
                            'keyword4' => array(
                                'value' => urlencode($shop['mobile']),
                                'color' => '#EF4F4F'
                            ),
                            'remark' => array(
                                'value' => urlencode("\\n感谢您的使用"),
                                'color' => "#01579b"
                            )
                        )
                    );
                   sendMsg(urldecode(json_encode($template)));
                }
            }
            if($shop['msgtype']==1||$shop['msgtype']==2){
                if ($settings['enabled']==1){
                   sms_send_dayu($id);
                }else{
                    $key =$settings['juhe']['juhe_appkey'];
                    $tpl_value ='#shop#='.$shop['name'].'&#ordersn#='.$data['orderno'];
                    $tpl_id = $settings['juhe']['juhe_temp2'];
                    juHeSms($key, $_GPC['mobile'], $tpl_id, $tpl_value);
                }
            }
        }

        message('更新快件信息成功！', mweb('shop', array(
            'op' => 'list',
            'sid' => $sid
        )), 'success');
    }
    include $this->template($tmpl.'shop');
}elseif ($operation == 'plpost') {
    if ($_GPC['ops']=='submit'){
       $settings = $this->module['config'];
        $shop = pdo_fetch("SELECT * FROM" . tablename("evzg_express_shop") . "WHERE id='{$_GPC['sid']}'");
        foreach ($_GPC['mobile'] as $k=>$v){
            $x =$_GPC['x'][$k];
            $expresssn = $_GPC['expres'][$k];
            $orderno =  $x.substr($expresssn,-2).build_order_no();
            // var_dump($orderno);die();
            $isorderno = pdo_fetch("SELECT * FROM".tablename("evzg_express_expres")."WHERE orderno='{$orderno}'");
            if(!empty($isorderno)){
                $orderno = $orderno.rand(0,9);
            }
            $data = array(
                'uniacid' => $_W['uniacid'],
                'orderno' => $orderno,
                'expresssn' => $_GPC['expres'][$k],
                'enabled' =>1,
                'sid' => intval($_GPC['sid']),
                'mobile' => $_GPC['mobile'][$k],
                'createtime' => time()
            );
            $result = pdo_insert('evzg_express_expres', $data);
            if ($settings['enabled']==1){
                sendSms($_GPC['mobile'][$k], $settings['dayu']['dayu_temp2'], array(
                    'shop' => $shop['name'],
                    'ordersn' => $data['orderno']
                ), $settings);
            }else{
                $key =$settings['juhe']['juhe_appkey'];
                $tpl_value ='#shop#='.$shop['name'].'&#ordersn#='.$data['orderno'];
                $tpl_id = $settings['juhe']['juhe_temp2'];
                juHeSms($key, $_GPC['mobile'][$k], $tpl_id, $tpl_value);
            }
        }
        message('批量添加快件成功！', mweb('shop', array(
            'op' => 'plpost',
            'sid' => $sid
        )), 'success');
     }
     include $this->template($tmpl.'shop');
} elseif ($operation == 'delete') {
    $id = intval($_GPC['id']);
    $expres = pdo_fetch("SELECT id FROM " . tablename('evzg_express_expres') . " WHERE id = '$id'");
    if (empty($expres)) {
        message('抱歉，快件不存在或是已经被删除！', mweb('shop', array(
            'op' => 'display',
            'sid' => $sid
        )), 'error');
    }
    pdo_delete('evzg_express_expres', array(
        'id' => $id
    ));
    message('快件删除成功！', mweb('shop', array(
        'op' => 'list',
        'sid' => $sid
    )), 'success');
} elseif ($operation == 'list') {
    if (empty($sid)) {
        message('抱歉，非法请求');
    }
    // var_dump($condition);die();
    $condition = ' WHERE uniacid = :aid AND sid = :sid';
    $params[':aid'] = $_W['uniacid'];
    $params[':sid'] = $sid;
    $ordersn = trim($_GPC['ordersn']);
    if (! empty($ordersn)) {
        $condition .= " AND orderno = :orderno";
        $params[':orderno'] = $ordersn;
    }
    $status = $_GPC['status'];
    if ($status!==null) {
        $condition .= " AND status = :status";
        $params[':status'] = $status;
    }
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('evzg_express_expres') . $condition, $params);
    $lists = pdo_fetchall('SELECT * FROM ' . tablename('evzg_express_expres') . $condition . ' ORDER BY displayorder DESC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize, $params);
    // 分页
    $pager = pagination($total, $pindex, $psize);
    include $this->template($tmpl.'shop');
} elseif ($operation == 'yypost') {
    $sid = intval($_GPC['sid']);
    $id = intval($_GPC['id']);
    $order = pdo_fetch("SELECT * FROM " . tablename('evzg_express_order') . " WHERE id = '$id'");
    $express = pdo_fetch("SELECT * FROM" . tablename("evzg_express_expres") . "WHERE id='{$order['eid']}'");
    if (checksubmit('submit')) {

        if ($order['status'] < $_GPC['status']) {
            if ($_GPC['status'] == 1) {
                $template = array(
                    "touser" => $order['openid'],
                    "template_id" => $settings['msg']['order_yysu_id'],
                    "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
                    "topcolor" => "#FF0000",
                    "data" => array(
                        'first' => array(
                            'value' => urlencode("您好，你的快递{$express['expresssn']}预约上门成功" . "\\n"),
                            'color' => "#743A3A"
                        ),
                        'keyword2' => array(
                            'value' => urlencode(date('Y年m月d日 H:i', time())),
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => urlencode("上门取件"),
                            'color' => '#EF4F4F'
                        ),
                        'remark' => array(
                            'value' => urlencode("{$_GPC['note']}"),
                            'color' => "#01579b"
                        )
                    )
                );
                $resu =  pdo_update('evzg_express_order', array('status' => intval($_GPC['status']),'note'=>$_GPC['note']), array(
                    'id' => $id
                ));
             $result =  sendMsg(urldecode(json_encode($template)));

            }
            if ($_GPC['status'] == 2) {
                $template = array(
                    "touser" => $order['openid'],
                    "template_id" => $settings['msg']['order_yyerr_id'],
                    "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
                    "topcolor" => "#FF0000",
                    "data" => array(
                        'first' => array(
                            'value' => urlencode("您好，你的快递{$express['expresssn']}预约上门失败" . "\\n"),
                            'color' => "#743A3A"
                        ),
                        'keyword3' => array(
                            'value' => urlencode($order['address']),
                            'color' => '#000000'
                        ),
                        'keyword2' => array(
                            'value' => urlencode(date('Y年m月d日 H:i', time())),
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => urlencode("上门取件"),
                            'color' => '#EF4F4F'
                        ),
                        'remark' => array(
                            'value' => urlencode("{$_GPC['note']}"),
                            'color' => "#01579b"
                        )
                    )
                );
                $resu =  pdo_update('evzg_express_order', array('status' => intval($_GPC['status']),'note'=>$_GPC['note']), array(
                    'id' => $id
                ));
               $result= sendMsg(urldecode(json_encode($template)));

            }
        }
        if ($order['status'] == $_GPC['status']) {
            $resu =  pdo_update('evzg_express_order', array('status' => intval($_GPC['status']),'note'=>$_GPC['note']), array(
                    'id' => $id
                ));
        }
        message('更新预约状态成功！', mweb('shop', array('op' => 'display','sid' => $sid)), 'success');

    }
    include $this->template($tmpl.'shop');
} elseif ($operation == 'yydelete') {
    $id = intval($_GPC['id']);
    $expres = pdo_fetch("SELECT id FROM " . tablename('evzg_express_order') . " WHERE id = '$id'");
    if (empty($expres)) {
        message('抱歉，预约不存在或是已经被删除！', $this->createMobileUrl('dowebshop', array(
            'op' => 'display',
            'sid' => $sid
        )), 'error');
    }
    pdo_delete('evzg_express_order', array(
        'id' => $id
    ));
    message('预约删除成功！', mweb('shop', array(
        'op' => 'display',
        'sid' => $sid
    )), 'success');
}elseif($operation == 'nextmsg'){
    $log =array();
	 $settings = $this->module['config'];
	 $id = $_GPC['id'];
	 if(empty($id)){
		 message('再次通知失败', mweb('list', array(
        'op' => 'display',
        'sid' => $sid
         )), 'error');
	 }
	$data = pdo_get('evzg_express_expres', array('id'=>$id));
	$member = pdo_fetch("SELECT * FROM" . tablename("evzg_express_member") . "WHERE mobile='{$data['mobile']}'");
	$shop = pdo_fetch("SELECT * FROM" . tablename("evzg_express_shop") . "WHERE id='{$_GPC['sid']}'");
	$log['oid'] = $data['id'];
	$log['sid'] = $data['sid'];
	$log['operator'] = "店铺：".$shop['name'];
	if(!empty($member['openid'])){

		if($shop['msgtype']==1||$shop['msgtype']==3){
			$tpl = array(
			'openid'=>$member['openid'],
			"template_id" => $settings['msg']['order_dz_id'],
			"url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
			"data" => array(
				'first' => "您好，你的快递{$data['expresssn']}已经到达{$shop['name']}门店",
				'keyword1' => $shop['name'],
				'keyword2' => $data['expresssn'],
				'keyword3' => $data['orderno'],
				'keyword4' => $shop['province'].$shop['city'].$shop['district'].$shop['address'],
				'remark' => "{$_GPC['description']}"
			)
		 );
			$tplLog = sendMsgTpl($tpl,$log);
		}

	}
	if($shop['msgtype']==1||$shop['msgtype']==2){
		if ($settings['enabled']==1){
		  $smsRult = sendSms($data['mobile'], $settings['dayu']['dayu_temp2'], array(
				'shop' => $shop['name'],
				'ordersn' => $data['orderno']
			), $settings,$log);
		}else{
			$key =$settings['juhe']['juhe_appkey'];
			$tpl_value ='#shop#='.$shop['name'].'&#ordersn#='.$data['orderno'];
			$tpl_id = $settings['juhe']['juhe_temp2'];
			juHeSms($key, $data['mobile'], $tpl_id, $tpl_value,$log);
		}
	}
	message('再次通知成功', mweb('shop', array(
        'op' => 'list',
        'sid' => $sid
         )), 'success');

}

