<?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.contract.ContractMapper">
    <select id="getPage" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT *
        FROM (SELECT t1.*,
                     IFNULL(t1.amount, 0) * IFNULL(t1.rate, 0) AS amountCNY,
                     CASE
                         WHEN (IFNULL(t1.amount, 0) * IFNULL(t1.rate, 0) - t1.sumClaimMoney) &lt;= 0 THEN
                             20
                         WHEN t1.sumClaimMoney = 0 THEN
                             0
                         ELSE 10
                         END                                   AS refundStatusNew
              FROM (SELECT t1.*,
                           c.name                            customerName,
                           us.nick_name                      salesmanName,
                           us.user_id                        salesmanId,
                           (SELECT IFNULL(SUM(IFNULL(cc.money_cny, IFNULL(cc.money, 0) * IFNULL(arw.rate, 1))), 0)
                            FROM claim_contract cc
                                     left join claim c on cc.claim_id = c.id
                                     LEFT JOIN bytesailing_account.account_running_water arw on c.business_id = arw.id
                            WHERE cc.contract_id = t1.id) AS sumClaimMoney
                    FROM contract t1
                             left join bytesailing_customer.customer c on t1.buy_corporation_id = c.id
                             left join bytesailing_base.sys_user us on c.user_id = us.user_id) t1
              GROUP BY t1.id) t1
            ${ew.customSqlSegment}
    </select>

    <select id="getHeadStatistic" resultType="java.util.Map">
        SELECT IFNULL(SUM(t1.amountCNY), 0)                              AS sumAmount,
               IFNULL(SUM(sumClaimMoney), 0)                             AS sumClaimMoney,
               count(1)                                                  AS `count`,
               IFNULL(GROUP_CONCAT(DISTINCT t1.buy_corporation_id ), "") AS customerList
        FROM (SELECT t1.*,
                     IFNULL(t1.amount, 0) * IFNULL(t1.rate, 0) AS amountCNY,
                     CASE
                         WHEN (IFNULL(t1.amount, 0) * IFNULL(t1.rate, 0) - t1.sumClaimMoney) &lt;= 0 THEN
                             20
                         WHEN t1.sumClaimMoney = 0 THEN
                             0
                         ELSE 10
                         END                                   AS refundStatusNew
              FROM (SELECT t1.*,
                           (SELECT IFNULL(SUM(IFNULL(cc.money, 0) * IFNULL(arw.rate, 1)), 0)
                            FROM claim_contract cc
                                     left join claim c on cc.claim_id = c.id
                                     LEFT JOIN bytesailing_account.account_running_water arw on c.business_id = arw.id
                            WHERE cc.contract_id = t1.id) AS sumClaimMoney,
                           c.name                            customerName,
                           us.nick_name                      salesmanName,
                           us.user_id                        salesmanId
                    FROM contract t1
                             left join bytesailing_customer.customer c on t1.buy_corporation_id = c.id
                             left join bytesailing_base.sys_user us on c.user_id = us.user_id) t1) t1
            ${ew.customSqlSegment}
    </select>

    <select id="getProfitClearingPage" resultType="com.fjhx.sale.entity.contract.vo.ContractBudgetVo">
        SELECT t1.id AS      contractId,
               us1.nick_name userName,
               t1.*
        FROM contract t1
                 LEFT JOIN bytesailing_customer.customer cu on t1.buy_corporation_id = cu.id and cu.del_flag = 0
                 LEFT JOIN bytesailing_base.sys_user us1 ON cu.user_id = us1.user_id and us1.del_flag = 0
            ${ew.customSqlSegment}
    </select>

    <select id="getProfitBudgetPage" resultType="com.fjhx.sale.entity.contract.vo.ContractBudgetVo">
        SELECT (select GROUP_CONCAT(id) from contract_product WHERE contract_id = t1.id) AS contractProductIds,
               t1.id                                                                     AS contractId,
               t1.`code`,
               t1.buy_corporation_id,
               us1.nick_name                                                                userName,
               t1.amount,
               t1.currency,
               t1.currency_rate_json,
               t1.rate                                                                   AS rate,
               t2.*,
               IFNULL(t1.budget_money, 0)                                                AS budgetMoney,
               cu.name                                                                      customerName,
               t1.is_settled
        FROM contract t1
                 LEFT JOIN contract_budget t2 ON t1.id = t2.contract_id
                 LEFT JOIN bytesailing_customer.customer cu on t1.buy_corporation_id = cu.id and cu.del_flag = 0
                 LEFT JOIN bytesailing_base.sys_user us1 ON cu.user_id = us1.user_id and us1.del_flag = 0
            ${ew.customSqlSegment}
    </select>

    <select id="getProfitBudgetHeadStatistic" resultType="com.fjhx.sale.entity.contract.vo.ContractBudgetVo">
        SELECT t1.id   AS contractId,
               t1.amount,
               t1.currency,
               t1.currency_rate_json,
               t1.rate AS rate,
               t2.*
        FROM contract t1
                 LEFT JOIN contract_budget t2 ON t1.id = t2.contract_id
                 LEFT JOIN bytesailing_customer.customer cu on t1.buy_corporation_id = cu.id and cu.del_flag = 0
                 LEFT JOIN bytesailing_base.sys_user us1 ON cu.user_id = us1.user_id and us1.del_flag = 0
            ${ew.customSqlSegment}
    </select>

    <select id="getNoPackContractByCustomerId" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT
        *
        FROM
        (
        SELECT
        t1.*,
        t2.quantity AS cpQuantity,
        ( SELECT IFNULL( SUM( pd.pack_quantity * pdd.quantity ), 0 ) FROM pack_detail_product pdd LEFT JOIN pack_detail
        pd ON pdd.pack_detail_id = pd.id WHERE pdd.contract_product_id = t2.id ) AS sumPackQuantity
        FROM
        contract t1
        LEFT JOIN contract_product t2 ON t1.id = t2.contract_id
        <where>
            <if test="customerId neq null and customerId neq '' ">
                buy_corporation_id = #{customerId}
            </if>
        </where>
        ) t1
        WHERE t1.sumPackQuantity &lt; t1.cpQuantity
        AND t1.`status`=30
        GROUP BY t1.id
    </select>

    <select id="getSalesTotal" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT
            SUM( amount ) AS sumAmount,
            SUM( contractCount ) AS contractCount
        FROM
            (
                SELECT
                    SUM( amount * rate ) amount,
                    count(*) contractCount
                FROM
                    contract
                WHERE
                    buy_corporation_id = #{id}
                  AND STATUS BETWEEN 0
                    AND 87
                  AND is_show != 1
		AND is_change = 0
		AND del_flag = 0
                GROUP BY
                    buy_corporation_id UNION ALL
                SELECT
                    SUM( amount * rate ) amount,
                    count(*) contractCount
                FROM
                    sample
                WHERE
                    buy_corporation_id = #{id}
                  AND STATUS BETWEEN 0
                  AND 87
                  AND is_show != 1
                  AND is_change = 0
                  AND del_flag = 0
                GROUP BY
                    buy_corporation_id
            ) t1

    </select>
    <select id="getSalesTotalList" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT
            *
        FROM
            (
                SELECT
                    currency,
                    sell_corporation_id,
                    id,
                    "外销合同" AS type,
                    create_time,
                    create_user,
                    `code`,
                    buy_corporation_id,
                    advance_ratio,
                    amount,
                    rate,
                    amount * rate AS amountCNY,
                    (
                        SELECT
                            IFNULL( SUM( IFNULL( cc.money, 0 ) * IFNULL( arw.rate, 1 )), 0 )
                        FROM
                            claim_contract cc
                                LEFT JOIN claim c ON cc.claim_id = c.id
                                LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
                        WHERE
                            cc.contract_id = t1.id
                    ) AS sumClaimMoney
                FROM
                    contract t1
                WHERE
                    buy_corporation_id = #{id}
                  AND STATUS BETWEEN 0
                    AND 87
                  AND is_show != 1
		AND is_change = 0
		AND del_flag = 0 UNION ALL
                SELECT
                    currency,
                    sell_corporation_id,
                    id,
                    "样品单" AS type,
                    create_time,
                    create_user,
                    `code`,
                    buy_corporation_id,
                    advance_ratio,
                    amount,
                    rate,
                    amount * rate AS amountCNY,
                    (
                    SELECT
                    IFNULL( SUM( IFNULL( cc.money, 0 ) * IFNULL( arw.rate, 1 )), 0 )
                    FROM
                    claim_contract cc
                    LEFT JOIN claim c ON cc.claim_id = c.id
                    LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
                    WHERE
                    cc.contract_id = t1.id
                    ) AS sumClaimMoney
                FROM
                    sample t1
                WHERE
                    buy_corporation_id = #{id}
                  AND STATUS BETWEEN 0
                  AND 87
                  AND is_show != 1
                  AND is_change = 0
                  AND del_flag = 0
            ) t1
    </select>
    <select id="getAmount" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT
            SUM(amount) amount,
            DATE_FORMAT(create_time,'%Y-%m') time
        FROM
            contract
        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="contractStatistics" resultType="com.fjhx.sale.entity.sale.vo.SaleQuotationVo">
        SELECT
            COUNT(*) count,
            ifnull(c.`status`,-1) status,
            ifnull(DATE_FORMAT(sq.create_time,'%Y-%m'),-1) time
        FROM
            bytesailing_customer.customer c
              left  JOIN  contract sq ON sq.buy_corporation_id = c.id
            ${ew.customSqlSegment}
    </select>
    <select id="countrySalesStatistics" resultType="com.fjhx.sale.entity.contract.dto.ContractDto">
        SELECT
            sum(cc.amount) amount,
            COUNT(cc.buy_country_id) count,
            ai.name countryName

        FROM
            contract cc
                LEFT JOIN bytesailing_base.customize_area ai ON cc.buy_country_id = ai.id
            ${ew.customSqlSegment}
    </select>

    <select id="customSalesStatistics" resultType="com.fjhx.sale.entity.contract.dto.ContractDto">
        SELECT
            sum(cc.amount) amount,
            bc.name corporationName
        FROM
            contract cc
                LEFT JOIN bytesailing_customer.customer bc ON cc.buy_corporation_id = bc.id
            ${ew.customSqlSegment}
    </select>

    <select id="salesmanSalesStatistics" resultType="com.fjhx.sale.entity.contract.dto.ContractDto">
        SELECT
            SUM(cc.amount) amount,
            su.nick_name userName
        FROM
            contract cc
                LEFT JOIN bytesailing_base.sys_user su ON cc.create_user = su.user_id
            ${ew.customSqlSegment}
    </select>

    <select id="productSalesStatistics" resultType="com.fjhx.sale.entity.contract.dto.ContractDto">
        SELECT
            SUM(cp.amount) amount,
            pi.name productName
        FROM
            contract_product cp
                LEFT JOIN bytesailing_item.product_info pi ON cp.product_id = pi.id
            ${ew.customSqlSegment}
    </select>
    <select id="salesVolumeStatistics" resultType="com.fjhx.sale.entity.contract.dto.ContractDto">

        SELECT SUM(cp.quantity) quantity,
               pi.name          productName
        FROM contract_product cp
                 LEFT JOIN bytesailing_item.product_info pi ON cp.product_id = pi.id
            ${ew.customSqlSegment}
    </select>
    <select id="getAccountRunningWaterByContractId"
            resultType="com.fjhx.account.entity.account.vo.AccountRunningWaterVo">
        SELECT arw.id,
               arw.create_time,
               ap.type,
               arw.currency,
               pad.money          amount,
               pad.remark         remarks,
               am.`name`          accountManagementName,
               am.account_opening accountManagementOpening,
               arw.`name`,
               arw.status
        FROM contract c
                 JOIN bytesailing_purchase.purchase p ON p.data_resource_id = c.id AND p.del_flag = 0
                 JOIN bytesailing_purchase.pay_detail `pad` ON pad.purchase_id = p.id AND pad.del_flag = 0
                 JOIN bytesailing_purchase.pay pa ON pad.pay_id = pa.id AND pa.del_flag = 0
                 JOIN bytesailing_account.account_payment ap ON ap.business_id = pa.id AND ap.del_flag = 0
                 JOIN bytesailing_account.account_running_water arw ON arw.business_id = ap.id AND arw.del_flag = 0
                 LEFT JOIN bytesailing_account.account_management am
                           ON arw.account_management_id = am.id AND am.del_flag = 0
        WHERE c.id = #{contractId}
        UNION ALL
        SELECT arw.id,
               arw.create_time,
               ap.type,
               arw.currency,
               arfd.amount,
               arfd.remarks,
               am.`name`          accountManagementName,
               am.account_opening accountManagementOpening,
               arw.`name`,
               arw.status
        FROM contract c
                 JOIN bytesailing_account.account_request_funds_detail arfd
                      ON arfd.contract_id = c.id AND arfd.del_flag = 0
                 JOIN bytesailing_account.account_payment ap
                      ON ap.business_id = arfd.account_request_funds_id AND ap.del_flag = 0
                 JOIN bytesailing_account.account_running_water arw ON arw.business_id = ap.id AND arw.del_flag = 0
                 LEFT JOIN bytesailing_account.account_management am
                           ON arw.account_management_id = am.id AND am.del_flag = 0
        WHERE c.id = #{contractId}
        group by arfd.id
        UNION ALL
        SELECT arw.id,
               arw.create_time,
               30                 type,
               arw.currency,
               clc.money,
               arw.remarks,
               am.`name`          accountManagementName,
               am.account_opening accountManagementOpening,
               arw.`name`,
               arw.status
        FROM bytesailing_account.account_running_water arw
                 JOIN claim cl ON cl.business_id = arw.id
                 JOIN claim_contract clc ON clc.claim_id = cl.id
                 JOIN contract c ON clc.contract_id = c.id
                 LEFT JOIN bytesailing_account.account_management am
                           ON arw.account_management_id = am.id AND am.del_flag = 0
        WHERE arw.del_flag = 0
          AND c.id = #{contractId}
    </select>
    <select id="getContractAndSamplePagez" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT
        *
        FROM
        (
        SELECT
            t1.id,
            t1.sell_corporation_id,
            t1.contract_type,
            1 AS dataType,
            t1.`code`,
            t1.buy_corporation_id,
            t1.version,
            t1.amount,
            t1.create_user,
            t1.create_time,
            t1.refund_status,
            t1.`status`,
            (SELECT IFNULL(SUM(IFNULL(cc.money, 0) * IFNULL(arw.rate, 1)), 0)
             FROM claim_contract cc
                      LEFT JOIN claim c ON cc.claim_id = c.id
                      LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
             WHERE cc.contract_id = t1.id) AS sumClaimMoney,
            (SELECT IFNULL(SUM(cc.contract_money), 0)
             FROM claim_contract cc
                      LEFT JOIN claim c ON cc.claim_id = c.id
                      LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
             WHERE cc.contract_id = t1.id) AS sumContractClaimMoney,
            t1.currency
        FROM contract t1
        WHERE t1.`status` >= 30
          AND t1.`status` &lt; 88
          AND t1.is_show != 1
        AND t1.is_change = 0
        UNION
        SELECT
            t1.id, t1.sell_corporation_id, 3 AS contract_type, 2 AS dataType, t1.`code`, t1.buy_corporation_id, t1.versions AS version, t1.amount, t1.create_user, t1.create_time, IF( sumClaimMoney >= t1.amount, 20, IF ( sumClaimMoney != 0, 10, 0 ) ) AS refund_status, t1.`status`, t1.sumClaimMoney, t1.sumContractClaimMoney, t1.currency
        FROM
            (
            SELECT
            t1.*, (
            SELECT
            IFNULL( SUM ( IFNULL( cc.money, 0 ) * IFNULL( arw.rate, 1 )), 0 )
            FROM
            claim_contract cc
            LEFT JOIN claim c ON cc.claim_id = c.id
            LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
            WHERE
            cc.contract_id = t1.id
            ) AS sumClaimMoney, (
            SELECT
            IFNULL( SUM (cc.contract_money), 0 )
            FROM
            claim_contract cc
            LEFT JOIN claim c ON cc.claim_id = c.id
            LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
            WHERE
            cc.contract_id = t1.id
            ) AS sumContractClaimMoney
            FROM
            sample t1
            WHERE
            t1.`status` >= 30
            AND t1.`status` &lt; 88
            AND t1.is_show != 1
            AND t1.is_change = 0
            ) AS t1) t1
            ${ew.customSqlSegment}
    </select>

    <update id="updateContract" parameterType="com.fjhx.sale.entity.contract.po.Contract">
        update contract
        <set>
            <if test="id != null">id = #{id},</if>
            <if test="status != null">status = #{status},</if>
            <if test="isChange != null">is_change = #{isChange},</if>
            <if test="isShow != null">is_show = #{isShow},</if>
            <if test="oldContractId != null">old_contract_id = #{oldContractId},</if>
            <if test="approvedDate != null">approved_date = DATE_FORMAT(NOW(),'%Y-%m-%d %H:%m:%s'),</if>
            update_time = sysdate()
        </set>
        where id = #{upId}
    </update>

    <select id="getExportCopyList" resultType="com.fjhx.sale.entity.contract.vo.ContractVo">
        SELECT * FROM (SELECT
            t1.*,
            CASE
            WHEN t1.purchaseAmountCNY &lt; t1.amountCNY AND t1.sumClaimMoney &lt; t1.amountCNY THEN 10
            WHEN t1.purchaseAmountCNY &lt; t1.amountCNY AND t1.sumClaimMoney >= t1.amountCNY THEN 20
            WHEN t1.purchaseAmountCNY >= t1.amountCNY AND t1.sumClaimMoney &lt; t1.amountCNY THEN 30
            WHEN t1.purchaseAmountCNY >= t1.amountCNY AND t1.sumClaimMoney >= t1.amountCNY THEN 40
            ELSE 88
            END AS orderStatus
        FROM
            (
                SELECT
                    t1.*,
                    IFNULL( t1.amount * t1.rate, 0 ) AS amountCNY,
                    <if test="documentaryType neq null ">
                        (SELECT count(1) FROM ehsd_purchase p LEFT JOIN ehsd_documentary pd ON p.id = pd.business_id WHERE p.data_resource_id = t1.id AND pd.documentary_type = #{documentaryType}) AS documentaryCount,
                    </if>
                    IFNULL(t1.advance_ratio,0)*IFNULL(t1.amount,0)/100 AS earnest,
                    ( SELECT create_time FROM claim_contract WHERE contract_id = t1.id ORDER BY create_time ASC LIMIT 1) AS claimTime,
                    ( SELECT count( 1 ) FROM ehsd_purchase WHERE `status` = 30 AND data_resource_id = t1.id ) AS purchaseCount,
                    ( SELECT IFNULL(SUM(amount*rate),0) FROM ehsd_purchase WHERE `status` = 30 AND data_resource_id = t1.id) AS purchaseAmountCNY,
        ( SELECT count( 1 ) FROM pack_detail WHERE FIND_IN_SET( contract_ids, t1.id ) AND shipment_status = 1 ) AS
        packCount,
        (
        SELECT
        IFNULL( SUM( IFNULL( cc.money, 0 ) * IFNULL( arw.rate, 1 )), 0 )
        FROM
        claim_contract cc
        LEFT JOIN claim c ON cc.claim_id = c.id
        LEFT JOIN bytesailing_account.account_running_water arw ON c.business_id = arw.id
        WHERE
        cc.contract_id = t1.id
        ) AS sumClaimMoney,
        cus.nick_name as salesmanName
        FROM
        contract t1
        left join bytesailing_customer.customer cu on t1.buy_corporation_id = cu.id
        left join bytesailing_base.sys_user cus on cu.user_id = cus.user_id
        WHERE t1.`status` = 30
        ) t1
        ) t1
        ${ew.customSqlSegment}
    </select>
    <select id="getContractProductInfo" resultType="com.fjhx.item.entity.product.bo.ProductAnalysisBo">
        SELECT cp.product_id,
               count(DISTINCT (cp.contract_id))                AS orderCount,
               IFNULL(sum(cp.quantity), 0)                     AS saleQuantity,
               IFNULL(sum(cp.price * cp.quantity * c.rate), 0) AS saleAmount,
               IFNULL(min(cp.price * c.rate), 0)               AS saleMinPrice,
               IFNULL(max(cp.price * c.rate), 0)               AS saleMaxPrice
        FROM contract_product cp
                 LEFT JOIN contract c ON cp.contract_id = c.id
            ${ew.customSqlSegment}
    </select>
    <select id="getPurchaseProductInfo" resultType="com.fjhx.item.entity.product.bo.ProductAnalysisBo">
        SELECT epp.product_id,
               IFNULL(sum(epp.quantity), 0)                       AS purchasesQuantity,
               IFNULL(sum(epp.price * epp.quantity * ep.rate), 0) AS purchasesAmount,
               IFNULL(min(epp.price * ep.rate), 0)                AS purchasesMinPrice,
               IFNULL(max(epp.price * ep.rate), 0)                AS purchasesMaxPrice
        FROM ehsd_purchase_product epp
                 LEFT JOIN ehsd_purchase ep ON epp.purchase_id = ep.id
            ${ew.customSqlSegment}
    </select>
    <select id="getProductPriceInfo" resultType="com.fjhx.sale.entity.contract.vo.ContractProductVo">
        SELECT cp.*,
               c.currency,
               c.code contractCode,
               c.is_settled
        FROM contract_product cp
                 LEFT JOIN contract c ON cp.contract_id = c.id
            ${ew.customSqlSegment}
    </select>
</mapper>
