<?php
/*
 * @Author: taowj 965042433@qq.com
 * @Date: 2023-07-13 17:24:44
 * @LastEditors: taowj 965042433@qq.com
 * @LastEditTime: 2023-07-21 18:17:33
 * @FilePath: \zhupu\application\api\controller\Worship.php
 * @Description: 祭祀相关接口
 */


namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\worship\Worshipgoodsmodel;
use app\admin\model\worship\Worshiphallmodel;
use app\admin\model\worship\Worshiplogmodel;
use app\api\model\OrderModel;
use app\api\model\PaymentLogModel;
use app\api\model\UsersModel;
use app\lib\model\FamilyPeopleModel;
use app\lib\model\FamilyTreeModel;
use app\lib\model\FamilyModel;
use think\Db;
use think\Exception;

class Worship extends Api
{
    /**
     * 查询本宗族的已过世的人
     */
    public function deadpeople()
    {
        //获取当前创建人
        $user_id = $this->auth->id;
        //姓名,查询条件
        $name = $this->request->post('name', '');
        //获取创建人的宗族id
        $familyTreeInfo = FamilyTreeModel::dataInfo(['people_id' => $user_id]);
        $page = $this->request->post('page', 1);
        //查询获取同宗族的已过世的人
        $where['ft.family_id'] = $familyTreeInfo['family_id'];
        $where['fp.ext0'] = 1;
        $where['fp.status'] = 1;
        $where['fp.name'] = ['like', '%' . $name . '%'];
        $deadPeople = FamilyPeopleModel::alias('fp')
            ->join('family_tree as ft', 'fp.id=ft.people_id')
            ->where($where)
            ->field('fp.id,ft.family_id,fp.name,')
            ->page($page)
            ->limit($this->pageSize)
            ->order('fp.id asc')
            ->select();
        $this->success('查询成功', ['deadPeople' => $deadPeople]);
    }
    /**
     * 创建灵堂
     */
    public function createWorshipHall()
    {
        //选择的需要创建灵堂的人
        $people_id = $this->request->post('people_id', 0);
        //遗像
        $photo = $this->request->post('photo', '');
        //灵堂背景图
        $background = $this->request->post('background', '');
        //姓名
        $name = $this->request->post('name', '');
        //挽联或者悼词
        $elegiac = $this->request->post('elegiac', '');
        //生日
        $birthday = $this->request->post('birthday', '');
        //忌日
        $deathday = $this->request->post('deathday', '');
        //当前创建人
        $creator = $this->auth->id;
        if (!$people_id) {
            $this->error('请选择灵堂被祭拜人');
        }
        try {
            Db::startTrans();
            $data = [
                'user_id' => $people_id,
                'photo' => $photo,
                'background' => $background,
                'name' => $name,
                'elegiac' => $elegiac,
                'birthday' => $birthday,
                'deathday' => $deathday,
                'creator' => $creator,
                'createtime' => time(),
                'manager' => $creator,
                'updatetime' => time()
            ];
            $Worshiphall = Worshiphallmodel::create($data);
            $log = [
                'worship_hall_id' => $Worshiphall['id'],
                'user_id' => $creator,
                'type' => 1,
                'intro' => $name . '的灵堂创建成功',
                'createtime' => time()
            ];
            $Worshiplog = Worshiplogmodel::create($log);
            Db::commit();
            $this->success('灵堂创建成功', ['Worshiphall' => $Worshiphall]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('灵堂创建失败', $e->getMessage());
        }
    }
    /**
     * 编辑灵堂
     */
    public function editWorshipHall()
    {
        //灵堂id
        $id = $this->request->post('id', 0);
        //选择的需要创建灵堂的人
        $people_id = $this->request->post('people_id', 0);
        //遗像
        $photo = $this->request->post('photo', '');
        //灵堂背景图
        $background = $this->request->post('background', '');
        //姓名
        $name = $this->request->post('name', '');
        //挽联或者悼词
        $elegiac = $this->request->post('elegiac', '');
        //生日
        $birthday = $this->request->post('birthday', '');
        //忌日
        $deathday = $this->request->post('deathday', '');
        //当前创建人
        $updator = $this->auth->id;
        if (!$people_id) {
            $this->error('请选择灵堂被祭拜人');
        }
        try {
            Db::startTrans();
            $data = [
                'user_id' => $people_id,
                'photo' => $photo,
                'background' => $background,
                'name' => $name,
                'elegiac' => $elegiac,
                'birthday' => $birthday,
                'deathday' => $deathday,
                'creator' => $updator,
                'updatetime' => time()
            ];
            $Worshiphall = Worshiphallmodel::where(['id' => $id])->update($data);
            $log = [
                'worship_hall_id' => $id,
                'user_id' => $updator,
                'type' => 1,
                'intro' => $name . '的灵堂编辑成功',
                'createtime' => time()
            ];
            $Worshiplog = Worshiplogmodel::create($log);
            Db::commit();
            $this->success('灵堂编辑成功', ['Worshiphall' => $Worshiphall]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('灵堂编辑失败', $e->getMessage());
        }
    }
    /**
     * 关闭灵堂
     */
    public function closeWorshipHall()
    {
        //灵堂id
        $id = $this->request->post('id', 0);
        //操作人
        $updator = $this->auth->id;
        $data = [
            'is_closed' => 1,
            'updatetime' => time()
        ];
        Worshiphallmodel::where(['id' => $id])->update($data);
        $log = [
            'worship_hall_id' => $id,
            'user_id' => $updator,
            'type' => 1,
            'intro' => '灵堂关闭成功',
            'createtime' => time()
        ];
        Worshiplogmodel::create($log);
        $this->success('灵堂关闭成功');
    }
    /**
     * 查看可用的贡品列表
     */
    public function displayWorshipGoods()
    {
        $page = $this->request->post('page', 1);
        $worshipGoods = Worshipgoodsmodel::dataList(['closed' => 0], $page, $this->pageSize);
        $this->success('贡品查询成功', ['worshipGoods' => $worshipGoods]);
    }
    /**
     * 根据贡品创建订单，调起支付
     */
    public function createOrder()
    {
        //商品id
        $goods_id = $this->request->post('goods_id', 0);
        //灵堂id
        $worship_hall_id = $this->request->post('worship_hall_id', 0);
        //订单价格
        $total_price = $this->request->post('total_price', 0);
        //实际支付金额
        $need_pay = $this->request->post('need_pay', 0);
        //查找灵堂
        $worshipHallInfo = Worshiphallmodel::dataInfo(['id' => $worship_hall_id]);
        if (!$worshipHallInfo) {
            $this->error('该灵堂不存在');
        }
        //被祭拜的人
        $consignee_id = $worshipHallInfo['user_id'];
        //支付方式
        $pay_way = $this->request->post('pay_way', 'weixin');
        //优惠券
        $coupon_id = $this->request->post('coupons_id', 0);
        //商品信息
        $worshipGoods = Worshipgoodsmodel::dataInfo(['id' => $goods_id]);
        try {
            Db::startTrans();
            //创建待支付订单
            $orderData = [
                'goods_id' => $goods_id,
                'user_id' => $this->auth->id,
                'consignee_id' => $consignee_id,
                'total_price' => $total_price,
                'need_pay' => $need_pay,
                'createtime' => time(),
                'create_ip' => $this->request->ip(),
                'goods_original_price' => $worshipGoods['price'],
                'status' => 0
            ];
            $orderInfo = OrderModel::create($orderData);
            //创建待支付记录
            $payLog = [
                'user_id' => $this->auth->id,
                'order_sn' => getOrdersn('goods'),
                'order_id' => $orderInfo['id'],
                'need_pay' => $need_pay,
                'order_type' => 'goods',
                'pay_way' => $pay_way,
                'status' => 1,
                'createtime' => time()
            ];
            $payment_log = PaymentLogModel::create($payLog);
            Db::commit();
            $this->success('订单创建成功', ['orderInfo' => $orderInfo,'payLog'=>$payment_log]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('订单创建失败', $e->getMessage());
        }
    }
    /**
     * 祭拜记录
     */
    public function worshipLog()
    {
        //商品id
        $goods_id = $this->request->post('goods_id', 0);
        //灵堂id
        $worship_hall_id = $this->request->post('worship_hall_id', 0);
        //页数
        $page = $this->request->post('page', 1);
        //查询条件
        if ($goods_id) {
            $where['goods_id'] = $goods_id;
        }
        $where['worship_hall_id'] = $worship_hall_id;
        $where['type'] = 2;
        //查找祭拜记录
        $worshipLog = Worshiplogmodel::dataList($where, $page, $this->pageSize, "createtime desc", "*,FROM_UNIXTIME(createtime,'%Y-%m-%d %T') as createtime");
        $this->success('查询成功', ['worshipLog' => $worshipLog]);
    }
    /**
     * 灵堂信息查询
     */
    public function worshipHallInfo()
    {
        //查询当前用户是否是族长
        $userInfo = UsersModel::where(['id' => $this->auth->id])->find();
        if(!$userInfo){
            $this->error("当前用户没有权限查看！");
        }
        //灵堂的主人
        $people_id = $this->request->post('people_id', 0);
        //判断该主人是否已过世
        $peopleInfo = FamilyPeopleModel::dataInfo(['id' => $people_id]);
        if ($peopleInfo['ext0'] != 1) {
            $this->error("该用户还在世，不允许创建灵堂！", null, -1);
        }
        //查询灵堂信息
        $worshipHallInfo = Worshiphallmodel::dataInfo(['user_id' => $people_id], "*,FROM_UNIXTIME(createtime,'%Y-%m-%d %T') as createtime,FROM_UNIXTIME(updatetime,'%Y-%m-%d %T') as updatetime");
        if (!$worshipHallInfo) {
            if($userInfo['is_shaikh']==1){
                $this->error("该用户暂时没有创建灵堂！", null, 0);
            }else{
                $this->error("非族长不允许创建灵堂！", null, -1);
            }
        }
        //查询灵堂相关的贡品记录
        $worshipGoodsList = Worshiplogmodel::field("goods_id,goods_name,count(1) as amount")->where(['worship_hall_id' => $worshipHallInfo['id'],'type'=>2])->group('goods_id')->select();
        if($worshipGoodsList){
            foreach($worshipGoodsList as $k=>$v){
                $worshipGoodsInfo=Worshipgoodsmodel::dataInfo(['id'=>$v['goods_id']]);
                $worshipGoodsList[$k]['photo']=$worshipGoodsInfo['photo'];
            }
        }
        $this->success('查询成功', ['worshipHallInfo' => $worshipHallInfo, 'worshipGoodsList' => $worshipGoodsList, 'is_shaikh' => $userInfo['is_shaikh']]);
    }
}
