<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class StoresController extends BaseController
{
    /**
     * 入驻申请
     */
    public function enterList()
    {
        auth_check("stores_read");
        $where = 1;
        $order = "`create_time` DESC";
        $l = 10;//确定每页记录数
        $count = M("storesEnter")->where($where)->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("storesEnter")->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("enterList");die;
    }

    /**
     * 审核 入驻申请
     */
    public function enterAudit()
    {
        auth_check("stores_opt");
        $info = M("storesEnter")
            ->join("se LEFT JOIN `am_users_oa` uo ON se.`openid`=uo.`openid`")
            ->where("se.`id`={$_GET['id']}")
            ->field("se.*,uo.`nickname`,uo.`sex`,uo.`headimgurl`")
            ->find();
        // 省 市 区
        $region = M("regionCounty")
            ->join("county LEFT JOIN `am_region_city` city ON county.`city_id`=city.`id`")
            ->join("LEFT JOIN `am_region_province` p ON city.`province_id`=p.`id`")
            ->where("county.`id`={$info['county_id']}")
            ->field("p.`name` AS `province`,city.`name` AS `city`,county.`name` AS `county`")
            ->find();
        $info['province'] = $region['province'];
        $info['city'] = $region['city'];
        $info['county'] = $region['county'];
        $this->assign("info", $info);
        $this->display("enterAudit");die;
    }

    /**
     * 删除 入驻申请
     */
    public function enterDel()
    {
        auth_check("stores_opt");
        $id = $_GET['id'];
        $row = M("storesEnter")->where("`id`={$id}")->find();
        $logo = $row['logo'];
        $business_licence = $row['business_licence'];
        $fcc = $row['fcc'];
        $result = M("storesEnter")->where("`id`={$id}")->delete();
        if ($result) {
            unlink("./Uploads/{$logo}");
            unlink("./Uploads/{$business_licence}");
            unlink("./Uploads/{$fcc}");
            alertMsg("删除成功！", U("enterList"));
        } else {
            $this->redirect("enterList");die;
        }
    }

    /**
     * 审核操作 通过/不通过
     */
    public function auditResult()
    {
        auth_check("stores_opt");
        $this->assign("id", $_POST['id']);
        $info = M("storesEnter")
            ->join("se LEFT JOIN `am_users_oa` uo ON se.`openid`=uo.`openid`")
            ->where("se.`id`={$_POST['id']}")
            ->field("se.*,uo.`nickname`,uo.`sex`,uo.`headimgurl`")
            ->find();
        // 省 市 区
        $region = M("regionCounty")
            ->join("county LEFT JOIN `am_region_city` city ON county.`city_id`=city.`id`")
            ->join("LEFT JOIN `am_region_province` p ON city.`province_id`=p.`id`")
            ->where("county.`id`={$info['county_id']}")
            ->field("p.`name` AS `province`,city.`name` AS `city`,county.`name` AS `county`")
            ->find();
        $info['province'] = $region['province'];
        $info['city'] = $region['city'];
        $info['county'] = $region['county'];
        $this->assign("info", $info);
        if ($_POST['result'] == -1) {
            $this->display("auditFailed");die;
        } else {
            $this->display("auditSuccess");die;
        }
    }

    /**
     * 审核通过
     */
    public function auditSuccess()
    {
        auth_check("stores_opt");
        $id = $_POST['id'];
        $lat = I("lat");
        $lng = I("lng");
        $invalid_time = strtotime(I("invalid_time"));
        $enterInfo = M("storesEnter")->where("`id`={$id}")->find();
        $password = md5($enterInfo['mobile']);
        $data = array(
            "enter_id" => $id,
            "lat" => $lat,
            "lng" => $lng,
            "invalid_time" => $invalid_time,
            "password" => $password,
            "openid" => $enterInfo['openid'],
            "logo" => $enterInfo['logo'],
            "mobile" => $enterInfo['mobile'],
            "county_id" => $enterInfo['county_id'],
            "name" => $enterInfo['name'],
            "contact" => $enterInfo['contact'],
            "address" => $enterInfo['address'],
            "create_time" => $_SERVER['REQUEST_TIME']
        );
        $existNum = M("stores")->where("`name`='{$enterInfo['name']}'")->count();
        if ($existNum > 0) {
            alertMsg("已存在同名商家", U("enterList"));
        } else {
            $insert_id = M("stores")->add($data);
            if ($insert_id) {
                M("storesEnter")->where("`id`={$id}")->setField("status", 2);
                // 发送模板消息  这里需要修正 模板ID，在配置文件修改 APPID & APP_SERECT ！！！
                vendor("WxPayPubHelperMp.WxPlugin");
                $WxPlugin = new \WxPlugin();
                $openid = $enterInfo['openid'];
                $template_id = "lBihnLXdOYUgheqcOVQNSgcjDq4oFsXGka7gApk7K_s";
                $url = "http://" . $_SERVER['HTTP_HOST'] . U("Wechat/Store/storeCenter");
                $data = array(
                    'first' => array('value' => urlencode(""), 'color' => "#000000"),
                    'keyword1' => array('value' => urlencode($enterInfo['contact']), 'color' => '#000000'),
                    'keyword2' => array('value' => urlencode(date("Y年m月d日")), 'color' => '#000000'),
                    'remark' => array('value' => urlencode('恭喜您成功入驻阿僈商城商家平台，默认密码为手机号，请在电脑登录“' . "http://" . $_SERVER['HTTP_HOST'] . U("MpSmi/Index/index") . '”修改您的密码'), 'color' => '#000000')
                );
                $result = $WxPlugin->doSend($openid, $template_id, $url, $data);
                if ($result['status'] == -1) {
                    file_put_contents("./Logs/auditSuccess.log", JSON($result), FILE_APPEND);
                }
                alertMsg("审核通过！", U("enterList"));
            } else {
                $this->redirect("enterList");die;
            }
        }
    }

    /**
     * 审核不通过
     */
    public function auditFailing()
    {
        auth_check("stores_opt");
        $id = $_POST['id'];    // 申请记录ID
        $reason = I("reason");    // 不通过原因
        $data = array(
            "status" => -1,
            "reason" => $reason
        );
        $result = M("storesEnter")->where("`id`={$id}")->save($data);
        if ($result) {
            // 发送模板消息  这里需要修正 模板ID，在配置文件修改 APPID & APP_SERECT ！！！
            // vendor("WxPayPubHelperMp.WxPlugin");
            // $WxPlugin = new \WxPlugin();
            // $openid = $enterInfo['openid'];
            // $template_id = "example_template_id";
            // $url = "http://";
            // $data = array(
            //     'first' => array('value' => urlencode(""), 'color' => "#000000"),
            //     'keyword1' => array('value' => urlencode("入驻申请未通过"), 'color' => '#000000'),
            //     'keyword2' => array('value' => urlencode(date("Y年m月d日")), 'color' => '#000000'),
            //     'remark' => array('value' => urlencode("拒绝原因：{$reason}"), 'color' => '#000000'),
            // );
            // $result = $WxPlugin->doSend($openid, $template_id, $url, $data);
            file_put_contents("./Logs/auditFailing.log", date("Y-m-d H:i:s ") . serialize($result) . "\r\n\r\n", FILE_APPEND);
        }
        $this->redirect("enterList");die;
    }

    /**
     * 商家列表
     */
    public function storeList()
    {
        auth_check("stores_read");
        $where = 1;
        $order = "`create_time` DESC";
        $l = 10;//确定每页记录数
        $count = M("stores")->where($where)->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("stores")->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("storeList");die;
    }

    /**
     * 商家详情
     */
    public function storeDetail()
    {
        auth_check("stores_read");
        $info = M("stores")
            ->join("s LEFT JOIN `am_users_oa` uo ON s.`openid`=uo.`openid`")
            ->join("LEFT JOIN `am_stores_enter` se ON s.`openid`=se.`openid`")
            ->field("s.*,uo.`nickname`,uo.`sex`,uo.`headimgurl`,se.`business_licence`,se.`fcc`")
            ->where("s.`id`={$_GET['id']}")
            ->find();
        // 省 市 区
        $region = M("regionCounty")
            ->join("county LEFT JOIN `am_region_city` city ON county.`city_id`=city.`id`")
            ->join("LEFT JOIN `am_region_province` p ON city.`province_id`=p.`id`")
            ->where("county.`id`={$info['county_id']}")
            ->field("p.`name` AS `province`,city.`name` AS `city`,county.`name` AS `county`")
            ->find();
        $info['province'] = $region['province'];
        $info['city'] = $region['city'];
        $info['county'] = $region['county'];
        $this->assign("info", $info);
        $this->display("storeDetail");die;
    }

    /**
     * 商家设置
     */
    public function setStore()
    {
        auth_check("stores_opt");
        if (!IS_POST) {
            $info = M("setStore")->find();
            $info['fee'] = unserialize($info['fee']);
            $this->assign("info", $info);
            $this->display("setStore");die;
        } else {
            $result = D("SetStore")->saveForm();
            if (!$result) {
                $this->redirect("setStore");die;
            } else {
                alertMsg("设置成功", U("setStore"));
            }
        }
    }
}