<?php

namespace app\common\model\project;

use app\common\model\project\ProjectDonationInfo;
use app\common\model\project\ProjectDonationOrderInfo;
use app\common\model\project\ProjectDonationRocord;
use app\common\model\project\ProjectDonationUser;
use liuniu\BaseModel;
use think\Exception;



class ProjectDonationOrder extends BaseModel
{

    // 表名
    protected $name = 'project_donation_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'order_status_text',
        'add_time_text',
        'delivery_time_text',
        'verify_time_text',
        'receiving_time_text',
        'feedback_time_text',
        'out_delivery_time_text'
    ];
    

    
    public function getOrderStatusList()
    {
        return ['0' => __('Order_status 0'), '1' => __('Order_status 1'), '-1' => __('Order_status -1'), '2' => __('Order_status 2'), '3' => __('Order_status 3')];
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAddTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['add_time']) ? $data['add_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeliveryTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivery_time']) ? $data['delivery_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getVerifyTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['verify_time']) ? $data['verify_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getReceivingTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['receiving_time']) ? $data['receiving_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFeedbackTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['feedback_time']) ? $data['feedback_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOutDeliveryTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['out_delivery_time']) ? $data['out_delivery_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setAddTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeliveryTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setVerifyTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setReceivingTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFeedbackTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setOutDeliveryTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    /**
     * 获取订单信息
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function lst($where)
    {
        $model = new self;
        $xwhere = null;
        if($where['all'] == 0)
        {
            if (isset($where['status']) && $where['status']>-2) $xwhere['order_status'] = $where['status'];
        }
        else
        {
            if($where['status']==1)
            {
                $xwhere['order_status'] = ['>',0];

            }
            elseif($where['status']==-1)
            {
                $xwhere['order_status'] = -1;
            }
        }

        if (isset($where['uid']) && $where['uid']>0) $xwhere['uid'] = $where['uid'];
        if (isset($where['cid']) && $where['cid']>0) $xwhere['cid'] = $where['cid'];
        if (isset($where['project_id']) && $where['project_id']>0) $xwhere['project_id'] = $where['project_id'];
        $count = $model->where($xwhere)->count();
        $list = $model->where($xwhere)->page($where['page'],$where['limit'])->order('id desc')->select();
        foreach ($list as &$v)
        {
            $v['item'] = ProjectDonationOrderInfo::where('order_id',$v['id'])->select();
            $v['user'] = ProjectDonationUser::where('id',$v['project_user_id'])->find();
            $v['matter'] = explode(",",$v['matter']);
            $v['qc'] = explode(",",$v['qc']);
            $v['worth'] = explode(",",$v['worth']);
            switch ($v['order_status'])
            {
                case 0:
                    $v['status_txt'] = '待审核';
                    break;
                case 1:
                    $v['status_txt'] = '审核通过';
                    break;
                case 2:
                    $v['status_txt'] = '已发货';
                    break;
                case 3:
                    $v['status_txt'] = '捐赠品入库';
                    break;
                case 4:
                    $v['status_txt'] = '捐赠品出库';
                    break;
                case 5:
                    $v['status_txt'] = '发受捐者';
                    break;
                case 6:
                    $v['status_txt'] = '受捐者反馈';
                    break;
                case -1:
                    $v['status_txt'] = '拒绝';
                    break;
            }
        }
        return compact('count','list');
    }
    /**
     * 生成订单唯一id
     * @param $uid 用户uid
     * @return string
     */
    public static function getNewOrderId()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
        if (self::where(['order_sn' => $orderId])->find()) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
        return $orderId;
    }

    /**
     * 创建订单
     * @param $where
     */
    public static  function create_order($where)
    {
        self::beginTrans();
        try {
            $donation = [];
            foreach ($where['item'] as $v)
            {
                $donation[] = $v['project_donation_id'];
            }
            if($where['project_id']>0 &&sizeof($where['item'])!=ProjectDonationInfo::where('pro_id',$where['project_id'])->where('project_donation_id','in',join(",",$donation))->count())
            {
                return self::setErrorInfo('物资参数不对');
            }
            $where['order_sn'] = self::getNewOrderId();
            $where['add_time'] = time();
            $where1 = $where;
            unset($where1['item']);
            unset($where1['item']);
            unset($where1['item']);
            $rs = self::create($where1);
            if($rs)
            {
                $data['project_id'] = $where['project_id'];
                $data['project_user_id'] = $where['project_user_id'];
                $data['order_id'] = $rs['id'];
                $data['uid'] = $rs['uid'];
                $data['cid'] = $rs['cid'];
                $num = 0;
                foreach ($where['item'] as $v)
                {
                    $data['project_donation_id'] = $v['project_donation_id'];
                    $data['project_donation_num'] = $v['project_donation_num'];
                    $num += $v['project_donation_num'];
                    $data['add_time'] = time();
                    ProjectDonationOrderInfo::create($data);
                }
                self::where('id',$rs['id'])->update(['total_num'=>$num]);
                ProjectDonationRocord::bill($rs['cid'],'caeate_order',0,$where['project_id'],$rs['id'],$where['name']);
                self::commitTrans();
                return $rs;
            }
            self::rollbackTrans();
            return self::setErrorInfo('订单创建失败');
        }catch (Exception $e)
        {

            return self::setErrorInfo('生成订单时系统错误错误原因：' .$e->getFile().$e->getLine().$e->getMessage(),true);
        }

    }
    public static function  info($id)
    {
        $info = self::find($id);
        $info['item'] = ProjectDonationOrderInfo::where('order_id',$id)->select();
        return $info;
    }


}
