<?php
namespace app\index\logic;

use app\common\model\appointmentmodel;
use app\common\model\payordermodel;
use think\Db;
use think\facade\Log;

/**
 * 支付
 *
 * @author wj
 * @date 2022-07-22
 */
class paylogic extends baselogic
{
    /**
     * 设置请求数据规则
     * 20220107
     * wj
     */
    protected function setrules()
    {
        $list = [
            'getappointmentorderforxcx' => [
                ['name' => 'aid', 'title' => '申请单id', 'require' => true, 'type' => 'numeric'],
                ['name' => 'openid', 'title' => 'openid', 'require' => true, 'type' => 'string'],
                ['name' => 'total_fee', 'title' => '支付费用', 'require' => true, 'type' => 'numeric'], //以分为单位
            ],
            'handlefrontorder' => [
                ['name' => 'openid', 'title' => 'openid', 'require' => true, 'type' => 'string'],
                ['name' => 'orderstatus', 'title' => '订单状态', 'require' => true, 'type' => 'numeric'],
                ['name' => 'outorderno', 'title' => '商户订单号', 'require' => true, 'type' => 'numeric'],
                ['name' => 'ispay', 'title' => '已支付', 'require' => true, 'type' => 'numeric'],
            ],
        ];
        return $list;
    }
    /**
     * 创建小程序申请订单
     *
     * @return void
     * @author wj
     * @date 2022-07-22
     */
    public function getappointmentorderforxcx($arr)
    {
        $result = $this->checkparam(__FUNCTION__, $arr);
        if (1 != $result['status']) {
            return $result;
        }
        $data = $result['data'];
        $openid = $data['openid'];
        $aid = $data['aid'];
        $totalfee = bcmul($data['total_fee'], 1, 0);

        $m_a = new appointmentmodel();
        $where = [
            'id' => $aid,
            'openid' => $openid,
        ];
        $ainfo = $m_a->getInfo($where);
        if (empty($ainfo)) {
            return backarr(0, "无申请数据");
        }
        $body = "核酸检测费用";
        $out_trade_no = createOrderNo();
        $notify_url = getselfurl('dev') . "index/appointment/pay_call_back";
        $trade_type = 'JSAPI';
        $orderinfo = [
            'openid' => $openid,
            'total_fee' => $totalfee,
            'body' => $body,
            'out_trade_no' => $out_trade_no,
            'notify_url' => $notify_url,
            'trade_type' => $trade_type,
            'wid' => $ainfo['wid'],
            'appointent_id' => $aid,
        ];
        return backarr(1, "success", $orderinfo);
    }
    /**
     * 处理后端支付回调
     *
     * @return void
     * @author wj
     * @date 2022-07-23
     */
    public function handleorder($arr)
    {
        Db::startTrans();
        try {
            $orderstatus = 8;
            $ispay = 0;
            if (array_key_exists('trade_state', $arr)) {
                $paystatus = $arr['trade_state'];
            } else {
                $paystatus = $arr['result_code'];
            }
            if ("SUCCESS" == $paystatus) {
                $orderstatus = 3;
                $ispay = 1;
            }
            $l_p = new payordermodel();
            $outorderno = $arr['out_trade_no'];
            $orderInfo = $l_p->getorderinfobyoutorderno($outorderno);
            if (empty($orderInfo)) {
                $msg = "orderNo:[" . $outorderno . "]" . "无对应订单号";
                throw new \Exception($msg);
            }
            if (3 == $orderInfo['orderstatus'] && 1 == $orderInfo['ispay']) {
                Db::rollback();
                $msg = "orderNo:[" . $outorderno . "]" . "已缴费";
                return backarr(1, $msg);
            }
            $updateData = [
                'outorderno' => $orderInfo['outorderno'],
                'wid' => $orderInfo['wid'],
                'openid' => $orderInfo['openid'],
                'orderstatus' => $orderstatus,
                'ispay' => $ispay,
                'is_reat_back' => 1,
            ];
            if (isset($arr['transaction_id']) && !empty($arr['transaction_id'])) {
                $updateData['transaction_id'] = $arr['transaction_id'];
            }
            $row = $l_p->updateinfobyid($orderInfo['id'], $updateData);
            if (empty($row)) {
                $msg = "orderNo:[" . $outorderno . "]修改失败";
                throw new \Exception($msg);
            }
            $ordertype = $orderInfo['order_type'];
            switch ($ordertype) {
                case 1:
                    $appointentid = $orderInfo['appointent_id'];
                    if (1 === $ispay) {
                        $this->updateappointment($appointentid, $outorderno);
                    }
                    break;
            }
            Db::commit();
            Log::info("commit");
            return backarr(1, "处理完成", ['id' => $orderInfo['id']]);
        } catch (\Exception $e) {
            Db::rollback();
            log::info("rollback");
            return backarr(0, $e->getMessage());
        }
    }
    /**
     * 处理前端支付回调
     *
     * @return void
     * @author wj
     * @date 2022-07-29
     */
    public function handlefrontorder($arr)
    {
        $result = $this->checkparam(__FUNCTION__, $arr);
        if (1 != $result['status']) {
            return $result;
        }
        $data = $result['data'];
        $openid = $data['openid'];
        $ispay = $data['ispay'];
        $orderstatus = $data['orderstatus'];
        $outorderno = $data['outorderno'];
        Db::startTrans();
        try {
            $m_po = new payordermodel;
            $oupdateData = [
                'ispay' => $ispay,
                'orderstatus' => $orderstatus,
                'paytime' => date('Y-m-d H:i:s'),
                'is_front_back' => 1,
            ];
            $row = $m_po->updorederstatusbyorderno($outorderno, $openid, $oupdateData);
            if (empty($row)) {
                throw new \Exception("订单修改失败");
            }
            $orderInfo = $m_po->getorderinfobyoutorderno($outorderno);
            $ordertype = $orderInfo['order_type'];
            switch ($ordertype) {
                case 1:
                    $appointentid = $orderInfo['appointent_id'];
                    if (1 === $ispay) {
                        $this->updateappointment($appointentid, $outorderno);
                    }
                    break;
            }
            Db::commit();
            Log::info("commit");
            return backarr(1, "处理完成", ['id' => $orderInfo['id']]);
        } catch (\Exception $e) {
            Db::rollback();
            log::info("rollback");
            return backarr(0, $e->getMessage());
        }
    }
    /**
     * 改申请单
     *
     * @return void
     * @author wj
     * @date 2022-07-29
     */
    private function updateappointment($appointentid, $outorderno)
    {
        $m_a = new appointmentmodel();
        $ainfo = $m_a->getInfo(['id' => $appointentid, 'ispay' => 0]);
        if (empty($ainfo)) {
            $msg = "申请单id:[" . $appointentid . "]不存在";
            throw new \Exception($msg);
        }
        $code = $appointentid . "|" . date("YmdHis");
        $aupdateData = [
            'ispay' => 1,
            'payorderno' => $outorderno,
            'code' => $code,
        ];
        $row = $ainfo->updateinfo(['id' => $appointentid], $aupdateData);
        if (empty($row)) {
            $msg = "申请单id:[" . $appointentid . "]修改失败";
            throw new \Exception($msg);
        }
    }
}
