<?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.fjhx.sale.mapper.sale.SaleQuotationMapper">
    <select id="getPage" resultType="com.fjhx.sale.entity.sale.vo.SaleQuotationVo">
        select
         *
        from sale_quotation sq
            ${ew.customSqlSegment}
    </select>

    <select id="getCount" resultType="java.lang.Integer">
        <!-- 查询报价次数（报价审批已通过的）-->
        SELECT
        COUNT(*)
        FROM
        sale_quotation
        WHERE
        buy_corporation_id = #{id} and `status` = 30 and del_flag = 0
        GROUP BY
        buy_corporation_id
    </select>

    <select id="getAmount" resultType="com.fjhx.sale.entity.sale.vo.SaleQuotationVo">
        SELECT
            SUM( amount ) amount,
            DATE_FORMAT(create_time,'%Y-%m') time
        FROM
            sale_quotation
        WHERE buy_corporation_id = #{id}
                and (DATE_FORMAT(create_time,'%Y-%m')>= #{beginTime} and #{endTime} >= DATE_FORMAT(create_time,'%Y-%m'))
        GROUP BY
            time
    </select>
    <select id="saleDetail" resultType="com.fjhx.sale.entity.sale.vo.SaleQuotationVo">
        SELECT
            create_time,
            create_user,
            IFNULL(advance_ratio,0) advanceRatio,
            amount,
            ifnull(ROUND((amount * advance_ratio/100),2),0) advanceCharge,
            buy_contact_name,
            10 as type
        FROM
            sale_quotation
        WHERE
            buy_corporation_id = #{dto.id}
        UNION
        SELECT
            create_time,
            create_user,
            IFNULL(advance_ratio,0) advanceRatio,
            amount,
            ifnull(ROUND((amount * advance_ratio/100),2),0) advanceCharge,
            buy_contact_name,
            20 as type
        FROM contract
        WHERE
            buy_corporation_id = #{dto.id}
    </select>

    <select id="latestFollowUp" resultType="com.fjhx.sale.entity.sale.vo.SaleQuotationVo">
        (SELECT
            id,
            amount,
            create_time,
            NULL AS contractCode,
            10 as type
        FROM
            sale_quotation
        ${ew.customSqlSegment})
        UNION
        (SELECT
            id,
            amount,
            create_time,
            code as contractCode,
            20 as type
        FROM
            contract
        ${ew.customSqlSegment})
    </select>

    <select id="saleStatistics" resultType="com.fjhx.sale.entity.sale.vo.SaleQuotationVo">
        SELECT
            COUNT(*) count,
            <!-- 防止出现null，代码报错-->
            ifnull(c.`status`,1000) status,
            ifnull(DATE_FORMAT(sq.create_time,'%Y-%m'),-1) time
        FROM
            bytesailing_customer.customer c
              left  JOIN  sale_quotation sq  ON sq.buy_corporation_id = c.id
            ${ew.customSqlSegment}
    </select>

</mapper>
