<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.his.api.db.dao.OrderDao">

    <resultMap id="BaseResultMap" type="com.example.his.api.db.pojo.OrderEntity">
        <id property="id" column="id" jdbcType="INTEGER"/>
        <result property="customerId" column="customer_id" jdbcType="INTEGER"/>
        <result property="goodsId" column="goods_id" jdbcType="INTEGER"/>
        <result property="snapshotId" column="snapshot_id" jdbcType="VARCHAR"/>
        <result property="goodsTitle" column="goods_title" jdbcType="VARCHAR"/>
        <result property="goodsPrice" column="goods_price" jdbcType="DECIMAL"/>
        <result property="number" column="number" jdbcType="INTEGER"/>
        <result property="amount" column="amount" jdbcType="DECIMAL"/>
        <result property="goodsImage" column="goods_image" jdbcType="VARCHAR"/>
        <result property="goodsDescription" column="goods_description" jdbcType="VARCHAR"/>
        <result property="outTradeNo" column="out_trade_no" jdbcType="CHAR"/>
        <result property="transactionId" column="transaction_id" jdbcType="CHAR"/>
        <result property="outRefundNo" column="out_refund_no" jdbcType="CHAR"/>
        <result property="status" column="status" jdbcType="TINYINT"/>
        <result property="createDate" column="create_date" jdbcType="DATE"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <result property="refundDate" column="refund_date" jdbcType="DATE"/>
        <result property="refundTime" column="refund_time" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!--    <sql id="Base_Column_List">-->
    <!--        id,customer_id,goods_id,-->
    <!--        snapshot_id,goods_title,goods_price,-->
    <!--        number,amount,goods_image,-->
    <!--        goods_description,out_trade_no,transaction_id,-->
    <!--        out_refund_no,status,create_date,-->
    <!--        create_time,refund_date,refund_time-->
    <!--    </sql>-->

    <!-- 订单统计数据 -->
    <select id="searchSummary" resultType="HashMap">
        select count(*)    as count,
               sum(amount) as amount,
               sum(number) as number
        from tb_order
        where customer_id = #{customerId}
          and `status` IN (3, 5, 6)
    </select>

    <!--  查询该用户当天未付款订单数量和退款订单数量  -->
    <select id="searchIllegalCountInDay" parameterType="int" resultType="boolean">
        SELECT (
                   (SELECT COUNT(*)
                    FROM tb_order
                    WHERE customer_id = #{customerId}
                      AND create_date = CURRENT_DATE()
                      AND status &lt; 3) >= 10
                       OR
                   (SELECT COUNT(*)
                    FROM tb_order
                    WHERE customer_id = #{customerId}
                      AND refund_date = CURRENT_DATE()
                      AND status = 4) >= 5
                   ) AS illegal
    </select>

    <!--  关闭超过30分钟未付款的订单  -->
    <update id="closeOrder">
        UPDATE tb_order
        SET status = 2
        WHERE status = 1
          AND TIMESTAMPDIFF(MINUTE, create_time, NOW()) > 30
    </update>

    <!--  微信支付单创建成功之后，应该创建商品快照  -->
    <insert id="orderInsert">
        INSERT INTO tb_order
        SET customer_id       = #{customerId},
            goods_id          = #{goodsId},
            snapshot_id       = #{snapshotId},
            goods_title       = #{goodsTitle},
            goods_price       = #{goodsPrice},
            number            = #{number},
            amount            = #{amount},
            goods_image       = #{goodsImage},
            goods_description = #{goodsDescription},
            out_trade_no      = #{outTradeNo},
            status            = 1,
            create_date       = CURRENT_DATE()
    </insert>

    <!--  缓存的WebSocket连接，然后推送消息给前端页面  -->
    <select id="searchCustomerId" parameterType="String" resultType="Integer">
        SELECT customer_id
        FROM tb_order
        WHERE out_trade_no = #{outTradeNo}
    </select>

    <!--  查询订单列表  -->
    <select id="searchFrontOrderByPage" parameterType="Map" resultType="HashMap">
        SELECT o.id,
        o.out_trade_no AS outTradeNo,
        o.goods_id AS goodsId,
        o.snapshot_id AS snapshotId,
        o.goods_title AS goodsTitle,
        o.goods_price AS goodsPrice,
        o.number,
        o.amount,
        o.goods_image AS goodsImage,
        o.goods_description AS goodsDescription,
        o.`status`,
        IF(o.`status` = 1 AND TIMESTAMPDIFF(MINUTE,o.create_time,NOW()) > 20, true, false) AS disabled,
        DATE_FORMAT(o.create_date,"%Y-%m-%d") AS createDate,
        DATE_FORMAT(o.create_time,"%Y-%m-%d %H:%i:%s") AS createTime,
        COUNT(a.id) AS appointCount
        FROM tb_order o
        LEFT JOIN tb_appointment a ON o.id = a.order_id
        WHERE o.customer_id = #{customerId}
        <if test="status!=null">
            AND o.`status` = #{status}
        </if>
        <if test="keyword!=null">
            AND ( o.out_trade_no = #{keyword} OR o.goods_title LIKE CONCAT( "%", #{keyword}, "%" ) )
        </if>
        GROUP BY o.id
        ORDER BY o.id DESC
    </select>
    <select id="searchMisOrderByPage" parameterType="Map" resultType="HashMap">
        SELECT o.id,
        o.goods_title AS goodsTitle,
        FORMAT(o.goods_price,0) AS goodsPrice,
        o.snapshot_id AS snapshotId,
        o.number,
        FORMAT(o.amount,0) AS amount,
        c.photo,
        c.name,
        c.sex,
        c.tel,
        DATE_FORMAT(c.create_time,"%Y-%m-%d") AS registerTime,
        o.`status`,
        o.out_trade_no AS outTradeNo,
        o.transaction_id AS transactionId,
        o.out_refund_no AS outRefundNo,
        o.create_date AS createDate,
        DATE_FORMAT(o.create_time,"%Y-%m-%d %H:%i") AS createTime,
        o.refund_date AS refundDate,
        DATE_FORMAT(o.refund_time,"%Y-%m-%d %H:%i") AS refundTime,
        COUNT(a.id) AS num
        FROM tb_order o
        JOIN tb_customer c ON o.customer_id = c.id
        JOIN tb_goods g ON o.goods_id = g.id
        LEFT JOIN tb_appointment a ON a.order_id = o.id
        <where>
            <if test="tel!=null">
                AND c.tel = #{tel}
            </if>
            <if test="code!=null">
                AND g.`code` = #{code}
            </if>
            <if test="status!=null">
                AND o.status = #{status}
            </if>
            <if test="startDate!=null and endDate!=null">
                AND o.create_date BETWEEN #{startDate} AND #{endDate}
            </if>
            <if test="keyword!=null">
                AND o.goods_title LIKE CONCAT("%",#{keyword},"%")
            </if>
            <if test="customerId!=null">
                AND c.id = #{customerId}
            </if>
        </where>
        GROUP BY o.id
        ORDER BY o.id DESC
    </select>
    <select id="searchMisCustomerOrderByPage" parameterType="Map" resultType="HashMap">
        SELECT o.id,
               o.goods_title                                AS goodsTitle,
               FORMAT(o.goods_price, 0)                     AS goodsPrice,
               o.snapshot_id                                AS snapshotId,
               o.number,
               FORMAT(o.amount, 0)                          AS amount,
               c.photo,
               c.name,
               c.sex,
               c.tel,
               DATE_FORMAT(c.create_time, "%Y-%m-%d")       AS registerTime,
               o.`status`,
               o.out_trade_no                               AS outTradeNo,
               o.transaction_id                             AS transactionId,
               o.out_refund_no                              AS outRefundNo,
               o.create_date                                AS createDate,
               DATE_FORMAT(o.create_time, "%Y-%m-%d %H:%i") AS createTime,
               o.refund_date                                AS refundDate,
               DATE_FORMAT(o.refund_time, "%Y-%m-%d %H:%i") AS refundTime,
               COUNT(a.id)                                  AS num
        FROM tb_order o
                 JOIN tb_customer c ON o.customer_id = c.id
                 JOIN tb_goods g ON o.goods_id = g.id
                 LEFT JOIN tb_appointment a ON a.order_id = o.id
        where c.id = #{customerId}
        GROUP BY o.id
        ORDER BY o.id DESC
    </select>

    <!--  查询退款流水号  -->
    <select id="searchOutRefundNo" parameterType="int" resultType="String">
        SELECT out_refund_no AS outRefundNo
        FROM tb_order
        WHERE id = #{id}
    </select>

    <!-- 更新退款流水号   -->
    <update id="updateOutRefundNo" parameterType="Map">
        UPDATE tb_order
        SET out_refund_no = #{outRefundNo},
            refund_date   = CURRENT_DATE(),
            refund_time   = NOW()
        WHERE id = #{id}
          AND status = 3
    </update>

    <!--  申请退款  -->
    <select id="applyRefund" parameterType="Map" resultType="HashMap">
        SELECT transaction_id AS transactionId,
               amount         AS amount
        FROM tb_order
        WHERE id = #{id}
          AND status = 3
          AND customer_id = #{customerId}
    </select>

    <!--  更新订单为已退款状态  -->
    <update id="updateRefundStatus" parameterType="String">
        UPDATE tb_order
        SET status = 4
        WHERE out_refund_no = #{outRefundNo}
          AND status = 3
    </update>

    <!--  更新线下退款订单状态  -->
    <update id="updateOnlineRefundStatus" parameterType="String">
        UPDATE tb_order
        SET status = 4
        WHERE out_trade_no = #{outTradeNo}
          AND status = 3
    </update>

    <!--  更新订单为已付款状态  -->
    <update id="updatePaymentStatus" parameterType="Map">
        UPDATE tb_order
        SET transaction_id= #{transactionId},
            status        = 3
        WHERE out_trade_no = #{outTradeNo}
          AND status IN (1, 2)
    </update>

    <!--  更新订单预约状态  -->
    <update id="updateAppointmentStatus" parameterType="Map">
        UPDATE tb_order
        SET status = #{status}
        WHERE id = #{id}
    </update>

    <!--  关闭未支付的订单  -->
    <update id="closeOrderById" parameterType="Map">
        UPDATE tb_order
        SET status = 2
        WHERE id = #{id}
          AND customer_id = #{customerId}
          AND status = 1
    </update>

    <!-- 删除已关闭的订单  -->
    <delete id="deleteOrderById">
        delete
        from tb_order
        where id = #{id}
          and status = 2
    </delete>

    <!-- 判断客户是否拥有某个订单 -->
    <select id="hasOwnOrder" parameterType="Map" resultType="integer">
        select id from tb_order where id = #{id} and customer_id = #{customerId}
    </select>

    <!-- 查询该订单的体检预约已完成的数量是否等于体检套餐数量 -->
    <select id="searchOrderIsFinished" parameterType="String" resultType="HashMap">
        SELECT o.id,
               o.number AS n1,
               (SELECT COUNT(*) FROM tb_appointment WHERE order_id=o.id AND status=3) AS n2
        FROM tb_order o JOIN tb_appointment a ON o.id=a.order_id
        WHERE a.uuid = #{uuid}
    </select>
</mapper>
