<?php
namespace Smi\Controller;

use Think\Controller;

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

    /**
     * 添加省
     */
    public function provinceAdd()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $insert_id = D("RegionProvince")->saveForm();
            if ($insert_id) {
                alertMsg("添加成功", U("provinceList"));
            } else {
                $this->redirect("provinceList");die;
            }
        } else {
            $this->assign("small", "添加省");
            $this->display("provinceAdd");die;
        }
    }

    /**
     * 编辑省
     */
    public function provinceEdit()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $result = D("RegionProvince")->saveForm();
            if ($result) {
                alertMsg("编辑成功", U("provinceList"));
            } else {
                $this->redirect("provinceList");die;
            }
        } else {
            $info = M("regionProvince")->where("`id`={$_GET['id']}")->find();
            $this->assign("info", $info);
            $this->assign("small", "编辑省");
            $this->display("provinceAdd");die;
        }
    }

    /**
     * 删除省
     */
    public function provinceDel()
    {
        auth_check("region_opt");
        //接收 ID
        $id = I("id");
        if (!$id) alertMsg("系统故障，无法接收 ID");
        $bool = M("regionProvince")->delete($id);
        $this->redirect("provinceList");die;
    }

    /**
     * 市 列表
     */
    public function cityList()
    {
        auth_check("region_read");
        $where = "1";
        if ($_GET['province_id']) {
            $where .= " AND c.`province_id` = {$_GET['province_id']}";
            $province = M("regionProvince")->where("`id`={$_GET['province_id']}")->find();
            $this->assign("province", $province);
        }
        $order = "c.`sort`,c.`province_id` ASC";
        $l = 10;//确定每页记录数
        $count = M("regionCity")
            ->join(" c LEFT JOIN `am_region_province` p ON c.`province_id`=p.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("regionCity")
            ->join(" c LEFT JOIN `am_region_province` p ON c.`province_id`=p.`id`")
            ->field("c.*, p.`name` AS `province_name`")
            ->order($order)
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("cityList");die;
    }

    /**
     * 添加市
     */
    public function cityAdd()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $insert_id = D("RegionCity")->saveForm();
            if ($insert_id) {
                alertMsg("添加成功", U("cityList", array("province_id" => cookie("province_id"))));
            } else {
                $this->redirect("cityList");die;
            }
        } else {
            $province = M("regionProvince")->find();
            $this->assign("province", $province);
            $this->assign("small", "添加市");
            $this->display("cityAdd");die;
        }
    }

    /**
     * 编辑市
     */
    public function cityEdit()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $result = D("RegionCity")->saveForm();
            if ($result) {
                alertMsg("编辑成功", U("cityList", array("province_id" => cookie("province_id"))));
            } else {
                $this->redirect("cityList");die;
            }
        } else {
            cookie("province_id", $_GET['province_id'], 7200);
            $info = M("regionCity")->where("`id`={$_GET['id']}")->find();
            $this->assign("info", $info);
            $this->assign("small", "编辑市");
            $this->display("cityAdd");die;
        }
    }

    /**
     * 删除市
     */
    public function cityDel()
    {
        auth_check("region_opt");
        //接收 ID
        $id = I("id");
        if (!$id) alertMsg("系统故障，无法接收 ID");
        $bool = M("regionCity")->delete($id);
        $this->redirect("cityList");die;
    }

    /**
     * 县/区 列表
     */
    public function countyList()
    {
        auth_check("region_read");
        $where = "1";
        if ($_GET['city_id']) {
            $where .= " AND county.`city_id` = {$_GET['city_id']}";
            $city = M("regionCity")->where("`id`={$_GET['city_id']}")->find();
            $this->assign("city", $city);
        }
        $order = "county.`sort`,county.`city_id` ASC";
        $l = 10;//确定每页记录数
        $count = M("regionCounty")
            ->join(" county LEFT JOIN `am_region_city` c ON county.`city_id`=c.`id`")
            ->join("LEFT JOIN `am_region_province` p ON c.`province_id`=p.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("regionCounty")
            ->join(" county LEFT JOIN `am_region_city` c ON county.`city_id`=c.`id`")
            ->join("LEFT JOIN `am_region_province` p ON c.`province_id`=p.`id`")
            ->field("county.*, c.`name` AS `city_name`, p.`name` AS `province_name`")
            ->order($order)
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("countyList");die;
    }

    /**
     * 添加县/区
     */
    public function countyAdd()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $insert_id = D("RegionCounty")->saveForm();
            if ($insert_id) {
                alertMsg("添加成功", U("countyList", array("city_id" => cookie("city_id"))));
            } else {
                $this->redirect("countyList");die;
            }
        } else {
            cookie("city_id", $_GET['city_id'], 7200);
            $city = M("regionCity")->where("`id`={$_GET['city_id']}")->find();
            $this->assign("city", $city);
            $this->assign("small", "添加县/区");
            $this->display("countyAdd");die;
        }
    }

    /**
     * 编辑县/区
     */
    public function countyEdit()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $result = D("RegionCounty")->saveForm();
            if ($result) {
                alertMsg("编辑成功", U("countyList"));
            } else {
                $this->redirect("countyList");die;
            }
        } else {
            cookie("city_id", $_GET['city_id'], 7200);
            $info = M("regionCounty")->where("`id`={$_GET['id']}")->find();
            $this->assign("info", $info);
            $this->assign("small", "编辑县/区");
            $this->display("countyAdd");die;
        }
    }

    /**
     * 删除县/区
     */
    public function countyDel()
    {
        auth_check("region_opt");
        //接收 ID
        $id = I("id");
        if (!$id) alertMsg("系统故障，无法接收 ID");
        $bool = M("regionCounty")->delete($id);
        $this->redirect("countyList");die;
    }

    /**
     * 村/小区 列表
     */
    public function villageList()
    {
        auth_check("region_read");
        $where = "1";
        if ($_GET['county_id']) {
            $where .= " AND r.`county_id` = {$_GET['county_id']}";
            $county = M("regionCounty")->where("`id`={$_GET['county_id']}")->find();
            $this->assign("county", $county);
        }
        $order = "r.`county_id` ASC";
        $l = 10;//确定每页记录数
        $count = M("regionVillage")
            ->join(" r LEFT JOIN `am_region_county` c ON r.`county_id`=c.`id`")
            ->join("LEFT JOIN `am_region_city` city ON c.`city_id`=city.`id`")
            ->join("LEFT JOIN `am_region_province` p ON city.`province_id`=p.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("regionVillage")
            ->join(" r LEFT JOIN `am_region_county` c ON r.`county_id`=c.`id`")
            ->join("LEFT JOIN `am_region_city` city ON c.`city_id`=city.`id`")
            ->join("LEFT JOIN `am_region_province` p ON city.`province_id`=p.`id`")
            ->field("r.*, c.`name` AS `county_name`, city.`name` AS `city_name`, p.`name` AS `province_name`")
            ->order($order)
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("villageList");die;
    }

    /**
     * 添加村/小区
     */
    public function villageAdd()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $insert_id = D("RegionVillage")->saveForm();
            if ($insert_id && $_POST['type'] == 1) {
                // am_goods 锁表
                $goodsArr = M("goods")->lock()->getField("id", true);
                $len = count($goodsArr);
                if ($goodsArr && $len > 0) {
                    $data = array();
                    for ($i=0; $i < $len; $i++) {
                        // 分仓库库存记录 (新建村不需要生成总仓库库存记录)
                        array_push($data, array(
                            "good_id" => $goodsArr[$i],
                            "village_id" => $insert_id
                        ));
                    }
                    // am_goods_storage 锁表、每件商品生成对应该村的记录
                    M("goodsStorage")->lock()->addAll($data);
                }
                alertMsg("添加成功", U("villageList", array("county_id" => cookie("county_id"))));
            } else {
                $this->redirect("villageList", array("county_id" => cookie("county_id")));die;
            }
        } else {
            cookie("county_id", $_GET['county_id'], 7200);
            $county = M("regionCounty")->where("`id`={$_GET['county_id']}")->find();
            $this->assign("county", $county);
            $this->assign("small", "添加村/小区");
            $this->display("villageAdd");die;
        }
    }

    /**
     * 编辑村/小区
     */
    public function villageEdit()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $oldType = M("regionVillage")->where("`id`={$_POST['id']}")->getField("type");
            $result = D("RegionVillage")->saveForm();
            if ($result) {
                if ($result && $oldType == 2 && $_POST['type'] == 1) {
                    // 小区变为村, 增设分仓库
                    // am_goods 锁表
                    $goodsArr = M("goods")->lock()->getField("id", true);
                    $len = count($goodsArr);
                    if ($goodsArr && $len > 0) {
                        $data = array();
                        for ($i=0; $i < $len; $i++) {
                            // 分仓库库存记录 (新建村不需要生成总仓库库存记录)
                            array_push($data, array(
                                "good_id" => $goodsArr[$i],
                                "village_id" => $_POST['id']
                            ));
                        }
                        // am_goods_storage 锁表、每件商品生成对应该村的记录
                        M("goodsStorage")->lock()->addAll($data);
                    }
                } elseif ($result && $oldType == 1 && $_POST['type'] == 2) {
                    // 村变为小区, 去除分仓库
                    M("goodsStorage")->where("`village_id`={$_POST['id']}")->delete();
                }
                alertMsg("编辑成功", U("villageList"));
            } else {
                $this->redirect("villageList");die;
            }
        } else {
            cookie("county_id", $_GET['county_id'], 7200);
            $info = M("regionVillage")->where("`id`={$_GET['id']}")->find();
            $this->assign("info", $info);
            $this->assign("small", "编辑村/小区");
            $this->display("villageAdd");die;
        }
    }

    /**
     * 删除村/小区
     */
    public function villageDel()
    {
        auth_check("region_opt");
        //接收 ID
        $id = I("id");
        if (!$id) alertMsg("系统故障，无法接收 ID");
        $result = M("regionVillage")->delete($id);
        if ($result) {
            M("goodsStorage")->where("`village_id`={$id}")->delete();    // 删除库存信息
            M("storageVillage")->where("`village_id`={$id}")->delete();    // 删除分仓库出入库信息
            M("goodsVillageSet")->where("`village_id`={$id}")->delete();    // 删除商品的村独立设置记录
        }
        $this->redirect("villageList");die;
    }

    /**
     * 分仓库库存
     */
    public function goodsStorage()
    {
        auth_check("region_read");
        $village = M("regionVillage")->where("`id`={$_GET['id']}")->find();
        $this->assign("village", $village);
        $l = 10;//确定每页记录数
        $count = M("goodsStorage")
            ->join("gs LEFT JOIN `am_goods` g ON gs.`good_id`=g.`id`")
            ->field("gs.*,g.`goods_name`,g.`thumb`")
            ->where("gs.`village_id`={$_GET['id']}")
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("goodsStorage")
            ->join("gs LEFT JOIN `am_goods` g ON gs.`good_id`=g.`id`")
            ->field("gs.*,g.`goods_name`,g.`thumb`")
            ->where("gs.`village_id`={$_GET['id']} AND g.`deleted`=-1")
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->display("goodsStorage");die;
    }

    /**
     * 分仓库出入库记录
     */
    public function storageChange()
    {
        auth_check("region_read");
        $village = M("regionVillage")->where("`id`={$_GET['id']}")->find();
        $this->assign("village", $village);
        $l = 10;//确定每页记录数
        $count = M("storageVillage")
            ->where("`village_id`={$_GET['id']}")
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("storageVillage")
            ->where("`village_id`={$_GET['id']}")
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign("list", $list);
        $this->display("storageChange");die;
    }

    /**
     * 设置收购商品(村)
     */
    public function purchaseGoods()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $result = D("RegionVillage")->purchaseGoods();
            if ($result) {
                alertMsg("设置成功", U("villageList", array("county_id" => cookie("county_id"))));
            } else {
                $this->redirect("villageList");die;
            }
        } else {
            cookie("county_id", $_GET['county_id'], 7200);
            $info = M("regionVillage")->where("`id`={$_GET['id']}")->find();
            $info['purchase_goods'] = explode(",", $info['purchase_goods']);
            $this->assign("info", $info);
            // 商品数组
            $goods = M("goods")->where("`is_sale`=2")->field("`id`,`goods_name`")->order("`sort` ASC")->select();
            $this->assign("goods", $goods);
            $this->assign("small", "设置收购商品");
            $this->display("purchaseGoods");die;
        }
    }

    /**
     * 轮播图(村/小区)
     */
    public function carouselList()
    {
        auth_check("region_read");
        $village = M("regionVillage")->where("`id`={$_GET['id']}")->find();
        $this->assign("village", $village);
        if ($village['type'] == 1) {
            $list = M("carousel")
                ->join(" c LEFT JOIN `am_goods` g ON c.`good_id`=g.`id`")
                ->field("c.*,g.`goods_name` AS `good_name`")
                ->where("c.`village_id`={$_GET['id']}")
                ->select();
        } elseif ($village['type'] == 2) {
            $list = M("carouselCity")
                ->where("`village_id`={$_GET['id']}")
                ->select();
        }
        $this->assign("list", $list);
        $this->display("carouselList");die;
    }

    /**
     * 添加轮播图(村)
     */
    public function carouselAdd()
    {
        auth_check("region_opt");
        if (IS_POST) {
            if (!$_POST['good_id'] && $_POST['type'] == 1) {
                // 农村地区
                alertMsg("请选择商品");
            }
            //文件上传
            if ($_FILES['img']['error'] != 4) {
                $upload = new \Think\Upload();    // 实例化上传类    
                // $upload->maxSize = 3145728 ;    // 设置附件上传大小 
                // 设置附件上传类型       
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './Uploads/';    // 设置附件上传根目录 
                $upload->savePath = 'carousel/img/';    // 设置附件上传目录  
                $upload->autoSub = false;    //不要子文件夹
                // 上传文件
                $info = $upload->upload();
                if(!$info) {
                // 上传错误提示错误信息
                    $this->error($upload->getError());die;
                }else{
                // 上传成功 获取上传文件信息
                    $pic = $info['img']["savepath"] . $info['img']["savename"];
                    $data['img'] = $pic;    // 修改数据对象
                }
            } else {
                alertMsg("请上传图片");
            }
            $data['village_id'] = $_POST['village_id'];
            if ($_POST['sort']) $data['sort'] = $_POST['sort'];
            if ($_POST['type'] == 1) {
                // 农村地区
                $data['good_id'] = $_POST['good_id'];
                M("carousel")->add($data);
            } elseif ($_POST['type'] == 2) {
                // 城市地区
                M("carouselCity")->add($data);
            }
            $this->redirect("carouselList?id=" . $_POST['village_id']);die;
        } else {
            $village = M("regionVillage")->where("`id`={$_GET['village_id']}")->find();
            $this->assign("village", $village);
            if ($village['type'] == 1) {
                // 商品数组
                $goods = M("goods")->where("`is_sale`=2")->field("`id`,`goods_name`")->order("`sort` ASC")->select();
                $this->assign("goods", $goods);
            }
            $this->display("carouselAdd");die;
        }
    }

    /**
     * 修改轮播图(村)
     */
    public function villageCarouselEdit()
    {
        auth_check("region_opt");
        if (IS_POST) {
            if (!$_POST['good_id'] && $_POST['type'] == 1) {
                alertMsg("请选择商品");
            }
            //文件上传
            if ($_FILES['img']['error'] != 4) {
                $upload = new \Think\Upload();    // 实例化上传类    
                // $upload->maxSize = 3145728 ;    // 设置附件上传大小 
                // 设置附件上传类型       
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './Uploads/';    // 设置附件上传根目录 
                $upload->savePath = 'carousel/img/';    // 设置附件上传目录  
                $upload->autoSub = false;    //不要子文件夹
                // 上传文件
                $info = $upload->upload();
                if(!$info) {
                // 上传错误提示错误信息
                    $this->error($upload->getError());die;
                }else{
                // 上传成功 获取上传文件信息
                    $pic = $info['img']["savepath"] . $info['img']["savename"];
                    $data['img'] = $pic;    // 修改数据对象
                }
            }
            $data['village_id'] = $_POST['village_id'];
            if ($_POST['sort']) $data['sort'] = $_POST['sort'];
            if ($_POST['type'] == 1) {
                // 农村地区
                $data['good_id'] = $_POST['good_id'];
                M("carousel")->where("`id`={$_POST['id']}")->save($data);
            } elseif ($_POST['type'] == 2) {
                // 城市地区
                M("carouselCity")->where("`id`={$_POST['id']}")->save($data);
            }
            $this->redirect("carouselList?id=" . $_POST['village_id']);die;
        } else {
            $village = M("regionVillage")->where("`id`={$_GET['village_id']}")->find();
            $this->assign("village", $village);
            if ($village['type'] == 1) {
                $info = M("carousel")->where("`id`={$_GET['id']}")->find();
                // 商品数组
                $goods = M("goods")->where("`is_sale`=2")->field("`id`,`goods_name`")->order("`sort` ASC")->select();
                $this->assign("goods", $goods);
            } else {
                $info = M("carouselCity")->where("`id`={$_GET['id']}")->find();
            }
            $this->assign("info", $info);
            $this->display("carouselAdd");die;
        }
    }

    /**
     * 删除轮播图(村)
     */
    public function villageCarouselDel()
    {
        auth_check("region_opt");
        //接收 ID
        $id = I("id");
        if (!$id) {$this->error("系统故障，无法接收 ID");die;}
        //定义待删除图片
        $del_img = M("carousel")->where("`id`={$id}")->getField("img");
        $bool = M("carousel")->delete($id);
        if ($bool) {
            //删除成功，删除原图
            @unlink("./Uploads/{$del_img}");
        }
        $this->redirect("carouselList?id=" . $_GET['village_id']);die;
    }

    /**
     * 设置 村佣金比例
     */
    public function villagePercent()
    {
        auth_check("region_opt");
        if (IS_POST) {
            $id = $_POST['id'];
            $county_id = $_POST['county_id'];    // 县ID不保存, 作为回跳村列表的参数
            $is_self = $_POST['is_self'];
            $village_percent = I("village_percent");
            $group_percent = I("group_percent");
            $cook_percent = I("cook_percent");
            if (!$id) alertMsg("ID异常");
            if (!$is_self) alertMsg("佣金独立选项异常");
            if (!is_numeric($village_percent) || $village_percent < 0 || $village_percent > 100) alertMsg("村管理员佣金比例异常");
            if (!is_numeric($group_percent) || $group_percent < 0 || $group_percent > 100) alertMsg("组管理员佣金比例");
            if (!is_numeric($cook_percent) || $cook_percent < 0 || $cook_percent > 100) alertMsg("厨师佣金比例");
            $data = array(
                "is_self" => $is_self,
                "village_percent" => $village_percent,
                "group_percent" => $group_percent,
                "cook_percent" => $cook_percent
            );
            $insert_id = M("regionVillage")->where("`id`={$id}")->save($data);
            if ($insert_id) {
                alertMsg("设置成功！", U("villageList", array("county_id" => $county_id)));
            } else {
                $this->redirect("villageList", array("county_id" => $county_id));die;
            }
        }
        $id = $_GET['id'];    // 村ID
        $county_id = $_GET['county_id'];    // 县ID
        $info = M("regionVillage")->where("`id`={$id}")->find();
        $this->assign("info", $info);
        $this->display("villagePercent");die;
    }

    /**
     * 修正库存
     */
    public function setStorage()
    {
        auth_check("region_opt");
        $id = $_POST['id'];
        $village_id = $_POST['village_id'];
        $storage = I("storage");
        $result = M("goodsStorage")->where("`id`={$id}")->setField("storage", $storage);
        if ($result) {
            alertMsg("操作成功", U("goodsStorage", array("id" => $village_id)));
        } else {
            $this->redirect("goodsStorage", array("id" => $village_id));die;
        }
    }
}