<?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.lframework.xingyun.sc.mappers.PurchaseOrderMapper">

    <resultMap id="PurchaseOrder" type="com.lframework.xingyun.sc.entity.PurchaseOrder">
        <id column="id" property="id"/>
        <result column="code" property="code"/>
        <result column="sc_id" property="scId"/>
        <result column="supplier_id" property="supplierId"/>
        <result column="purchaser_id" property="purchaserId"/>
        <result column="expect_arrive_date" property="expectArriveDate"/>
        <result column="total_num" property="totalNum"/>
        <result column="total_gift_num" property="totalGiftNum"/>
        <result column="total_amount" property="totalAmount"/>
        <result column="description" property="description"/>
        <result column="create_by" property="createBy"/>
        <result column="create_time" property="createTime"/>
        <result column="update_by" property="updateBy"/>
        <result column="update_time" property="updateTime"/>
        <result column="approve_by" property="approveBy"/>
        <result column="approve_time" property="approveTime"/>
        <result column="status" property="status"/>
        <result column="refuse_reason" property="refuseReason"/>
        <result column="link_number" property="linkNumber"/>
    </resultMap>

    <resultMap id="PurchaseOrderFullDto" type="com.lframework.xingyun.sc.dto.purchase.PurchaseOrderFullDto">
        <id column="id" property="id"/>
        <result column="code" property="code"/>
        <result column="sc_id" property="scId"/>
        <result column="supplier_id" property="supplierId"/>
        <result column="purchaser_id" property="purchaserId"/>
        <result column="expect_arrive_date" property="expectArriveDate"/>
        <result column="total_num" property="totalNum"/>
        <result column="total_gift_num" property="totalGiftNum"/>
        <result column="total_amount" property="totalAmount"/>
        <result column="description" property="description"/>
        <result column="create_by" property="createBy"/>
        <result column="create_time" property="createTime"/>
        <result column="update_by" property="updateBy"/>
        <result column="update_time" property="updateTime"/>
        <result column="approve_by" property="approveBy"/>
        <result column="approve_time" property="approveTime"/>
        <result column="status" property="status"/>
        <result column="refuse_reason" property="refuseReason"/>
        <result column="link_number" property="linkNumber"/>
        <collection property="details" javaType="java.util.ArrayList" ofType="com.lframework.xingyun.sc.dto.purchase.PurchaseOrderFullDto$OrderDetailDto">
            <id column="detail_id" property="id"/>
            <result column="detail_product_id" property="productId"/>
            <result column="detail_order_num" property="orderNum"/>
            <result column="detail_tax_price" property="taxPrice"/>
            <result column="detail_is_gift" property="isGift"/>
            <result column="detail_tax_rate" property="taxRate"/>
            <result column="detail_description" property="description"/>
            <result column="detail_order_no" property="orderNo"/>
        </collection>
    </resultMap>

    <resultMap id="PurchaseOrderWithReceiveDto" type="com.lframework.xingyun.sc.dto.purchase.PurchaseOrderWithReceiveDto">
        <id column="id" property="id"/>
        <result column="sc_id" property="scId"/>
        <result column="supplier_id" property="supplierId"/>
        <result column="purchaser_id" property="purchaserId"/>
        <collection property="details" ofType="com.lframework.xingyun.sc.dto.purchase.PurchaseOrderWithReceiveDto$DetailDto" javaType="java.util.ArrayList">
            <id column="detail_id" property="id"/>
            <result column="detail_product_id" property="productId"/>
            <result column="detail_order_num" property="orderNum"/>
            <result column="detail_tax_price" property="taxPrice"/>
            <result column="detail_is_gift" property="isGift"/>
            <result column="detail_tax_rate" property="taxRate"/>
            <result column="detail_description" property="description"/>
            <result column="detail_order_no" property="orderNo"/>
            <result column="detail_receive_num" property="receiveNum"/>
        </collection>
    </resultMap>

    <resultMap id="PurchaseProductDto" type="com.lframework.xingyun.sc.dto.purchase.PurchaseProductDto">
        <id column="id" property="id"/>
        <result column="code" property="code"/>
        <result column="name" property="name"/>
        <result column="category_id" property="categoryId"/>
        <result column="category_name" property="categoryName"/>
        <result column="brand_id" property="brandId"/>
        <result column="brand_name" property="brandName"/>
        <result column="sku_code" property="skuCode"/>
        <result column="external_code" property="externalCode"/>
        <result column="spec" property="spec"/>
        <result column="unit" property="unit"/>
        <result column="purchase_price" property="purchasePrice"/>
        <result column="tax_rate" property="taxRate"/>
        <result column="available" property="available"/>
    </resultMap>

    <sql id="PurchaseOrderDto_sql">
        SELECT
            o.id,
            o.code,
            o.sc_id,
            o.supplier_id,
            o.purchaser_id,
            o.expect_arrive_date,
            o.total_num,
            o.total_gift_num,
            o.total_amount,
            o.description,
            o.create_by,
            o.create_time,
            o.update_by,
            o.update_time,
            o.approve_by,
            o.approve_time,
            o.status,
            o.refuse_reason,
            o.link_number
        FROM tbl_purchase_order AS o
    </sql>

    <sql id="PurchaseOrderFullDto_sql">
        SELECT
            o.id,
            o.code,
            o.sc_id,
            o.supplier_id,
            o.purchaser_id,
            o.expect_arrive_date,
            o.total_num,
            o.total_gift_num,
            o.total_amount,
            o.description,
            o.create_by,
            o.create_time,
            o.update_by,
            o.update_time,
            o.approve_by,
            o.approve_time,
            o.status,
            o.refuse_reason,
            o.link_number,
            d.id AS detail_id,
            d.product_id AS detail_product_id,
            d.order_num AS detail_order_num,
            d.tax_price AS detail_tax_price,
            d.is_gift AS detail_is_gift,
            d.tax_rate AS detail_tax_rate,
            d.description AS detail_description,
            d.order_no AS detail_order_no
        FROM tbl_purchase_order AS o
        LEFT JOIN tbl_purchase_order_detail AS d ON d.order_id = o.id
    </sql>

    <sql id="PurchaseProductDto_sql">
        SELECT
            g.id,
            g.code,
            g.name,
            c.id AS category_id,
            c.name AS category_name,
            b.id AS brand_id,
            b.name AS brand_name,
            g.sku_code,
            g.external_code,
            g.spec,
            g.unit,
            purchase.price AS purchase_price,
            g.tax_rate,
            g.available
        FROM base_data_product AS g
        INNER JOIN base_data_product_purchase AS purchase ON purchase.id = g.id
        LEFT JOIN base_data_product_category AS c ON c.id = g.category_id
        LEFT JOIN base_data_product_brand AS b ON b.id = g.brand_id
        LEFT JOIN recursion_mapping AS rm ON rm.node_id = c.id and rm.node_type = 2
    </sql>

    <select id="query" resultMap="PurchaseOrder">
        <include refid="PurchaseOrderDto_sql"/>
        <where>
            <if test="vo != null">
                <if test="vo.code != null and vo.code != ''">
                    AND o.code = #{vo.code}
                </if>
                <if test="vo.supplierId != null and vo.supplierId != ''">
                    AND o.supplier_id = #{vo.supplierId}
                </if>
                <if test="vo.scId != null and vo.scId != ''">
                    AND o.sc_id = #{vo.scId}
                </if>
                <if test="vo.purchaserId != null and vo.purchaserId != ''">
                    AND o.purchaser_id = #{vo.purchaserId}
                </if>
                <if test="vo.status != null">
                    AND o.status = #{vo.status}
                </if>
                <if test="vo.createBy != null and vo.createBy != ''">
                    AND o.create_by_id = #{vo.createBy}
                </if>
                <if test="vo.approveBy != null and vo.approveBy != ''">
                    AND o.approve_by = #{vo.approveBy}
                </if>
                <if test="vo.createStartTime != null">
                    AND o.create_time >= #{vo.createStartTime}
                </if>
                <if test="vo.createEndTime != null">
                    <![CDATA[
                    AND o.create_time <= #{vo.createEndTime}
                    ]]>
                </if>
                <if test="vo.approveStartTime != null">
                    AND o.approve_time >= #{vo.approveStartTime}
                </if>
                <if test="vo.approveEndTime != null">
                    <![CDATA[
                    AND o.approve_time <= #{vo.approveEndTime}
                    ]]>
                </if>
            </if>

            <if test="orderIds != null and !orderIds.isEmpty()">
                AND o.id IN
                <foreach item="id" collection="orderIds" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
        </where>
        ORDER BY o.create_time DESC
    </select>
    <select id="getDetail" resultMap="PurchaseOrderFullDto">
        <include refid="PurchaseOrderFullDto_sql"/>
        WHERE o.id = #{id}
        ORDER BY d.order_no
    </select>
    <select id="selector" resultMap="PurchaseOrder">
        <include refid="PurchaseOrderDto_sql"/>
        <where>
            <if test="vo != null">
                <if test="vo.code != null and vo.code != ''">
                    AND o.code = #{vo.code}
                </if>
                <if test="vo.supplierId != null and vo.supplierId != ''">
                    AND o.supplier_id = #{vo.supplierId}
                </if>
                <if test="vo.scId != null and vo.scId != ''">
                    AND o.sc_id = #{vo.scId}
                </if>
                <if test="vo.status != null">
                    AND o.status = #{vo.status}
                </if>
                <if test="vo.createBy != null and vo.createBy != ''">
                    AND o.create_by_id = #{vo.createBy}
                </if>
                <if test="vo.createStartTime != null">
                    AND o.create_time >= #{vo.createStartTime}
                </if>
                <if test="vo.createEndTime != null">
                    <![CDATA[
                    AND o.create_time <= #{vo.createEndTime}
                    ]]>
                </if>
            </if>
        </where>
        ORDER BY o.create_time DESC
    </select>

    <select id="getWithReceive" resultMap="PurchaseOrderWithReceiveDto">
        SELECT
        o.id, o.sc_id, o.supplier_id, o.purchaser_id, d.id AS detail_id, d.product_id AS detail_product_id,
        d.order_num AS detail_order_num, d.tax_price AS detail_tax_price, d.is_gift AS detail_is_gift,
        d.tax_rate AS detail_tax_rate, d.description AS detail_description, d.order_no AS detail_order_no,
        d.receive_num AS detail_receive_num
        FROM tbl_purchase_order AS o
        LEFT JOIN tbl_purchase_order_detail AS d ON d.order_id = o.id
        <if test="requirePurchase">AND d.order_num > d.receive_num</if>
        WHERE o.id = #{id}
    </select>
    <select id="queryWithReceive" resultMap="PurchaseOrder">
        <include refid="PurchaseOrderDto_sql"/>
        <if test="!multipleRelate">LEFT JOIN tbl_receive_sheet AS s ON s.purchase_order_id = o.id</if>
        <where>
            <if test="vo != null">
                <if test="vo.code != null and vo.code != ''">
                    AND o.code = #{vo.code}
                </if>
                <if test="vo.supplierId != null and vo.supplierId != ''">
                    AND o.supplier_id = #{vo.supplierId}
                </if>
                <if test="vo.scId != null and vo.scId != ''">
                    AND o.sc_id = #{vo.scId}
                </if>
                AND o.status = 3
                <if test="vo.createBy != null and vo.createBy != ''">
                    AND o.create_by_id = #{vo.createBy}
                </if>
                <if test="vo.createStartTime != null">
                    AND o.create_time >= #{vo.createStartTime}
                </if>
                <if test="vo.createEndTime != null">
                    <![CDATA[
                    AND o.create_time <= #{vo.createEndTime}
                    ]]>
                </if>
            </if>
            <if test="!multipleRelate">AND s.id IS NULL</if>
        </where>
        <if test="!multipleRelate">GROUP BY o.id</if>
        ORDER BY o.create_time DESC
    </select>
    <select id="queryPurchaseByCondition" resultMap="PurchaseProductDto">
        <include refid="PurchaseProductDto_sql"/>
        <where>
            AND (
            g.code LIKE CONCAT('%', #{condition}, '%')
            OR g.name LIKE CONCAT('%', #{condition}, '%')
            OR g.sku_code LIKE CONCAT('%', #{condition}, '%')
            OR g.external_code LIKE CONCAT('%', #{condition}, '%')
            )
            AND g.product_type = 1
            AND g.available = TRUE
        </where>
        ORDER BY g.code
    </select>
    <select id="queryPurchaseList" resultMap="PurchaseProductDto">
        <include refid="PurchaseProductDto_sql"/>
        <where>
            <if test="vo != null">
                <if test="vo.condition != null and vo.condition != ''">
                    AND (
                    g.code LIKE CONCAT('%', #{vo.condition}, '%')
                    OR g.name LIKE CONCAT('%', #{vo.condition}, '%')
                    OR g.sku_code LIKE CONCAT('%', #{vo.condition}, '%')
                    OR g.external_code LIKE CONCAT('%', #{vo.condition}, '%')
                    )
                </if>
                <if test="vo.brandId != null and vo.brandId != ''">
                    AND b.id = #{vo.brandId}
                </if>
                <if test="vo.categoryId != null and vo.categoryId != ''">
                    AND (c.id = #{vo.categoryId} OR FIND_IN_SET(#{vo.categoryId}, rm.path))
                </if>
            </if>
            AND g.product_type = 1
            AND g.available = TRUE
        </where>
        ORDER BY g.code
    </select>
    <select id="getPurchaseById" resultMap="PurchaseProductDto">
        <include refid="PurchaseProductDto_sql"/>
        WHERE g.id = #{id}
    </select>

    <select id="TodaysPurchaseOrder" resultType="com.lframework.xingyun.sc.vo.chart.PurchaseOrderVo">
         SELECT * FROM tbl_purchase_order tp WHERE DATE(tp.create_time) = CURDATE() AND status=3
    </select>

    <select id="thisMonthPurchaseOrder" resultType="com.lframework.xingyun.sc.vo.chart.PurchaseOrderVo">
        SELECT * FROM tbl_purchase_order tp
        WHERE DATE_FORMAT(tp.create_time, '%Y-%m') = DATE_FORMAT(CURDATE(), '%Y-%m')
        AND status=3
    </select>

    <select id="orderMonthContrastPurchaseOrder" resultType="map">
        SELECT
        DATE_FORMAT(create_time, '%Y-%m') AS month,
        SUM(total_amount) AS purchase_amount
        FROM tbl_purchase_order
        WHERE
        create_time >= DATE_SUB(NOW(), INTERVAL 11 MONTH)
        AND create_time &lt; DATE_ADD(NOW(), INTERVAL 1 MONTH)
        AND status = 3
        GROUP BY DATE_FORMAT(create_time, '%Y-%m')
        ORDER BY month
    </select>

    <select id="orderTodaysContrastPurchaseOrder" resultType="map">
        SELECT DATE_FORMAT(create_time, '%Y-%m-%d') AS date,
        SUM(total_amount) AS purchase_amount
        FROM tbl_purchase_order
        WHERE create_time >= DATE_SUB(NOW(), INTERVAL 29 DAY)
            AND status = 3
        GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')  -- 与 SELECT 表达式一致
        ORDER BY date ASC
    </select>

    <select id="getPurchaseAmountByMonth" resultType="BigDecimal">
    SELECT
        COALESCE(SUM(total_amount), 0) AS purchase_amount
    FROM tbl_purchase_order
    WHERE
        YEAR(create_time) = #{year}
        AND MONTH(create_time) = #{month}
        AND status = 3
    </select>

</mapper>
