<?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.dayou.mapper.FinanceClaimMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dayou.entity.FinanceClaim">
        <result column="id" property="id" />
        <result column="created" property="created" />
        <result column="deleted" property="deleted" />
        <result column="modified" property="modified" />
        <result column="real_fund_id" property="realFundId" />
        <result column="production_fund_id" property="productionFundId" />
        <result column="claim_user_id" property="claimUserId" />
        <result column="claim_datetime" property="claimDatetime" />
        <result column="claim_amount" property="claimAmount" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id,
        created,
        deleted,
        modified,
        real_fund_id, production_fund_id, claim_user_id, claim_datetime, claim_amount
    </sql>

    <select id="getList" parameterType="com.dayou.entity.FinanceClaim" resultType="com.dayou.vo.FinanceClaimVO">
        SELECT
            fc.id,
            fc.real_fund_id,
            ( CASE orf.business_type WHEN 'MAJOR_BUSINESS' THEN '大中型业务' WHEN 'PERSONAL_BUSINESS' THEN '个贷业务' WHEN 'ASSET_BUSINESS' THEN '资产业务' WHEN 'ITEM_BUSINESS' THEN '土规业务' ELSE '-' END ) AS businessType,
            orf.should_amount,
            fc.claim_amount,
            u.NAME AS claimName,
            fc.created,
            orf.order_id,
            orf.order_name,
            orf.remark,
            off.production_should_amount,
            off.production_no
        FROM
            finance_claim fc
                LEFT JOIN order_fund orf ON fc.order_fund_id = orf.id
                LEFT JOIN ( SELECT id,order_fund_id,production_no,production_should_amount FROM production_fund WHERE deleted = 0) off  ON (off.order_fund_id = fc.order_fund_id  and fc.production_fund_id = off.id)
                LEFT JOIN user u ON u.id = fc.claim_user_id
        WHERE
            fc.real_fund_id = #{realFundId}
          AND fc.deleted = 0
        ORDER BY
            fc.created DESC
    </select>

    <select id="getTotalClaimAmountByProductionFundId" parameterType="java.lang.Long" resultType="java.math.BigDecimal">
        select ifnull(sum(claim_amount),0) from finance_claim where production_fund_id = #{productionFundId} and deleted = 0
    </select>

    <select id="getTotalClaimAmountByOrderFundId" parameterType="java.lang.Long" resultType="java.math.BigDecimal">
        select ifnull(sum(claim_amount),0) from finance_claim where order_fund_id = #{orderFundId} and deleted = 0
    </select>

    <select id="residueAmount" parameterType="java.lang.Long" resultType="java.math.BigDecimal">
        SELECT amount -( SELECT IFNULL( sum( claim_amount ), 0 ) FROM `finance_claim` WHERE deleted = 0 AND real_fund_id = #{financeFundId} ) AS residueAmount
        FROM
            finance_real_fund
        WHERE
            id = #{financeFundId} and deleted = 0
    </select>

    <sql id="majorStatQuery">
        SELECT
        fc.*,
        f.oId,
        f.pId,
        f.production_no as reportNo,
        m.order_id,
        f.shouldAmount as orderShouldAmount,
        m.financial,
        m.members,
        m.bailor,
        m.NAME AS orderName,
        mp.NAME,
        mp.if_save_file,
        mp.evaluate_amount,
        mp.production AS productionType,
        u.NAME AS clientManager,
        u1.NAME AS principal,
        cc1.NAME AS clientName,
        cc2.NAME AS clientSubName,
        frf.pay_datetime,
        frf.payer,
        u2.NAME AS claimUser,
        d.NAME AS evaluateDepartment,
        (
        SELECT
        GROUP_CONCAT( NAME SEPARATOR '、' )
        FROM
        department
        WHERE
        id IN (
        SELECT
        department_id
        FROM
        post
        WHERE
        id IN ( SELECT post_id FROM user_post WHERE user_id = u.id ))) AS marketDepartment
        FROM
        (select * from finance_claim where deleted = 0 and production_fund_id is not null
        AND claim_datetime &gt;= #{majorStat.startDate}
        AND claim_datetime &lt;= #{majorStat.endDate}
        ) fc
        INNER JOIN (
        SELECT
        p.order_fund_id oId,
        p.id AS pId,
        p.business_id,
        p.production_no,
        p.production_should_amount AS shouldAmount
        FROM
        production_fund p
        WHERE
        p.business_type = 'MAJOR_BUSINESS'
        AND p.deleted = 0
        ) f ON ( fc.order_fund_id = f.oId AND fc.production_fund_id = f.pId )
        LEFT JOIN major m ON f.business_id = m.id

        LEFT JOIN finance_real_fund frf ON frf.id = fc.real_fund_id
        LEFT JOIN (
        SELECT
        mpp.major_id,
        mpp.report_no,
        mpp.production,
        mpp.evaluate_amount,
        mpp.if_save_file,
        mpp.NAME
        FROM
        major_production mpp
        LEFT JOIN ( SELECT production_no, production_type, real_amount FROM production_fund WHERE business_type = 'MAJOR_BUSINESS' AND deleted = 0 ) ppf ON ( mpp.report_no = ppf.production_no AND mpp.production = ppf.production_type )
        WHERE
        ppf.real_amount IS NOT NULL
        ) mp ON ( mp.major_id = m.id AND mp.report_no = f.production_no )
        LEFT JOIN user u2 ON u2.id = fc.claim_user_id
        LEFT JOIN user u ON u.id = m.client_manager_id
        LEFT JOIN user u1 ON u1.id = m.principal_id
        LEFT JOIN department d ON d.id = m.department_id
        LEFT JOIN customer_company cc1 ON cc1.id = m.clientele_id
        LEFT JOIN customer_company cc2 ON cc2.id = m.clientele_sub_id
        LEFT JOIN customer_linkman cl1 ON cl1.id = m.clientele_contact_id
        <where>
            <if test="keyword!=null and keyword!='' ">
                and (
                m.order_id like concat ('%',#{keyword},'%')
                or f.production_no like concat ('%',#{keyword},'%')
                or u1.name like concat ('%',#{keyword},'%')
                or fc.claim_amount = #{keyword}
                or u2.NAME like concat ('%',#{keyword},'%')
                )
            </if>
            <if test="majorStat!=null and majorStat.payStartDate!=null and majorStat.payStartDate!='' ">
                and frf.pay_datetime &gt;= #{majorStat.payStartDate}
            </if>
            <if test="majorStat!=null and majorStat.payEndDate!=null and majorStat.payEndDate!='' ">
                and frf.pay_datetime &lt;= #{majorStat.payEndDate}
            </if>
            <if test="majorStat!=null and majorStat.ifSaveFile!=null ">
                and mp.if_save_file = #{majorStat.ifSaveFile}
            </if>
            <if test="majorStat!=null and majorStat.financial!=null ">
                and m.financial = #{majorStat.financial}
            </if>
        </where>

    </sql>
    <select id="majorStat" parameterType="com.dayou.vo.RealFundMajorStatVO" resultType="com.dayou.vo.RealFundMajorStatVO">
        <include refid="majorStatQuery" />
        ORDER BY
        fc.claim_datetime DESC
    </select>

    <select id="majorStatExport" parameterType="com.dayou.vo.RealFundMajorStatVO" resultType="com.dayou.vo.RealFundMajorStatVO">
        <include refid="majorStatQuery" />
        ORDER BY
        fc.claim_datetime ASC
    </select>

    <!--资产实收款统计-->
    <sql id="assetsStatQuery">
        SELECT
        claim.real_fund_id,
        claim.order_fund_id,
        claim.production_fund_id,
        claim.id,
        prod.production_no AS reportNo,
        assets.order_id AS orderId,
        assets.`name` AS orderName,
        (
        SELECT
        GROUP_CONCAT(DISTINCT department.name SEPARATOR '、' )
        FROM
        department,
        post,
        user_post,
        `user`
        WHERE
        `user`.id = user_post.user_id
        AND user_post.post_id = post.id
        AND post.department_id = department.id
        AND `user`.id = assets.client_manager_id
        AND user_post.deleted = 0
        ) AS marketDepartment,
        ( SELECT department.name FROM department WHERE department.id = assets.department_id ) AS evaluateDepartment,
        managerUser.name AS clientManagerName,
        principalUser.name AS principalName,
        realFund.payer AS payer,
        realFund.pay_datetime AS payDateTime,
        order_fund.should_amount AS orderShouldAmount,
        prodFund.production_should_amount AS prodShouldAmount,
        claim.claim_amount AS claimAmount,
        claimUser.name AS claimUser,
        claim.claim_datetime AS claimDatetime,
        assets.assets_business_gener AS assetsBusinessGener,
        ( SELECT customer_company.name FROM customer_company WHERE customer_company.id = assets.clientele_id ) AS clientName,
        ( SELECT customer_company.name FROM customer_company WHERE customer_company.id = assets.clientele_sub_id ) AS clientSubName,
        assets.bailor AS bailor,
        prod.evaluate_amount,
        (
        CASE
        WHEN prod.production_type = 'REPORT' THEN '评估报告'
        WHEN prod.production_type = 'CONSULT' THEN '咨询报告'
        WHEN prod.production_type = 'LETTER' THEN '意见函'
        ELSE '其他'
        END
        ) AS productionType,
        prod.if_save_file AS ifSaveFile
        FROM
        finance_claim AS claim
        LEFT JOIN finance_real_fund AS realFund ON realFund.id = claim.real_fund_id
        LEFT JOIN order_fund ON order_fund.id = claim.order_fund_id
        LEFT JOIN production_fund AS prodFund ON prodFund.id = claim.production_fund_id
        LEFT JOIN assets ON assets.id = order_fund.business_id
        AND assets.order_id = order_fund.order_id
        LEFT JOIN `user` AS managerUser ON managerUser.id = assets.client_manager_id
        LEFT JOIN `user` AS principalUser ON principalUser.id = assets.principal_id
        LEFT JOIN `user` AS claimUser ON claimUser.id = claim.claim_user_id
        LEFT JOIN assets_production AS prod ON assets.id = prod.business_id AND prodFund.production_no = prod.production_no
        WHERE order_fund.business_type = 'ASSET_BUSINESS'
        <if test="keyword!=null and keyword!='' ">
            and (
            assets.order_id like concat ('%',#{keyword},'%')
            or prod.production_no like concat ('%',#{keyword},'%')
            )
        </if>
        <if test="dto != null and dto.principalId != null and dto.principalId != ''">
            AND assets.principal_id = #{dto.principalId}
        </if>
        <if test="dto != null and dto.claimUserId != null and dto.claimUserId != ''">
            AND claim.claim_user_id = #{dto.claimUserId}
        </if>
        <if test="dto != null and dto.claimAmount != null and dto.claimAmount != ''">
            AND claim.claim_amount = #{dto.claimAmount}
        </if>
        <if test="dto != null and dto.assetsBusinessGener != null and dto.assetsBusinessGener != ''">
            AND assets.assets_business_gener = #{dto.assetsBusinessGener}
        </if>
        <if test="dto != null and dto.ifSaveFile != null and dto.ifSaveFile != ''">
            AND prod.if_save_file = #{dto.ifSaveFile}
        </if>
        <if test="dto != null and dto.startTime != null and dto.endTime!= null">
            AND (claim.claim_datetime BETWEEN #{dto.startTime} AND #{dto.endTime})
        </if>
        <if test="dto != null and dto.payStartTime != null and dto.payEndTime!= null">
            AND (realFund.pay_datetime BETWEEN #{dto.payStartTime} AND #{dto.payEndTime})
        </if>
        ORDER BY claim.claim_datetime DESC
    </sql>

    <!--查询资产实收款统计-->
    <select id="assetsSate" parameterType="com.dayou.dto.RealFundAssetsStatDTO" resultType="com.dayou.vo.RealFundAssetsStatVO">
        <include refid="assetsStatQuery" />
    </select>

    <!--资产实收款统计导出-->
    <select id="assetsSateExport" resultType="com.dayou.vo.RealFundAssetsStatVO">
        <include refid="assetsStatQuery" />
    </select>


    <sql id="personalStatSql">
        SELECT
            fc.*,
            f.should_amount,
            p.order_id,
            p.location,
            u.NAME AS clientManager,
            cc1.NAME AS clientName,
            cc2.NAME AS clientSubName,
            frf.pay_datetime,
            u2.NAME AS claimUser,
            p.bailorA,
            ( pt.amount / 10000 ) AS amount,
            p.if_save_file,
            (
                SELECT
                    GROUP_CONCAT( NAME SEPARATOR '、' )
                FROM
                    department
                WHERE
                    id IN (
                        SELECT
                            department_id
                        FROM
                            post
                        WHERE
                            id IN ( SELECT post_id FROM user_post WHERE user_id = u.id ))) AS marketDepartment
        FROM
            (
                SELECT
                    orderFund.id AS oId,
                    orderFund.business_id,
                    orderFund.order_id,
                    orderFund.should_amount
                FROM
                    order_fund orderFund
                WHERE
                    orderFund.business_type = 'PERSONAL_BUSINESS'
                  AND orderFund.deleted = 0
            ) f
                INNER JOIN
                (select * from finance_claim where deleted = 0
                AND claim_datetime &gt;= #{dto.startTime}
                AND claim_datetime &lt;= #{dto.endTime}
                )
                fc ON fc.order_fund_id = f.oId
                LEFT JOIN personal p ON f.business_id = p.id
                LEFT JOIN user u ON u.id = p.client_manager_id
                LEFT JOIN customer_company cc1 ON cc1.id = p.clientele_id
                LEFT JOIN customer_company cc2 ON cc2.id = p.clientele_sub_id
                LEFT JOIN finance_real_fund frf ON frf.id = fc.real_fund_id
                LEFT JOIN user u2 ON u2.id = fc.claim_user_id
                LEFT JOIN personal_target pt ON pt.personal_id = p.id
        WHERE
            p.deleted = 0 and fc.deleted = 0
        <if test="dto != null and dto.orderId != null and dto.orderId != ''">
            AND p.order_id = #{dto.orderId}
        </if>
        <if test="dto != null and dto.claimUser != null and dto.claimUser != ''">
            AND u2.NAME like concat ('%',#{dto.claimUser},'%')
        </if>
        <if test="dto != null and dto.claimAmount != null and dto.claimAmount != ''">
            AND fc.claim_amount = #{dto.claimAmount}
        </if>
        <if test="dto != null and dto.ifSaveFile != null">
            AND p.if_save_file = #{dto.ifSaveFile}
        </if>
        <if test="dto != null and dto.payStartTime != null and dto.payEndTime!= null">
            AND (frf.pay_datetime BETWEEN #{dto.payStartTime} AND #{dto.payEndTime})
        </if>
        ORDER BY
            fc.claim_datetime DESC
    </sql>
    <select id="personalStat" parameterType="com.dayou.vo.RealFundPersonalVO" resultType="com.dayou.vo.RealFundPersonalVO">
        <include refid="personalStatSql" />
    </select>

    <select id="personalStatExport" parameterType="com.dayou.vo.RealFundPersonalVO" resultType="com.dayou.vo.RealFundPersonalVO">
        <include refid="personalStatSql" />
    </select>

    <select id="queryOrderTotalAmount" resultType="com.dayou.entity.OrderFund">
        SELECT
            fc.order_fund_id as id,
            realAmount,
            oof.business_type
        FROM
            ( SELECT order_fund_id, sum( claim_amount ) realAmount FROM finance_claim WHERE deleted = 0 GROUP BY order_fund_id ) fc
                LEFT JOIN order_fund oof ON oof.id = fc.order_fund_id
    </select>

    <sql id="claimList">
        SELECT
        fc.id,
        frf.payer,
        frf.amount,
        frf.pay_datetime,
        fc.claim_amount,
        u.NAME AS creator,
        frf.created,
        frf.remark,
        u1.name as claimUser,
        fc.claim_datetime ,
        ( CASE off.business_type WHEN 'MAJOR_BUSINESS' THEN '大中型业务' WHEN 'PERSONAL_BUSINESS' THEN '个贷业务' WHEN 'ASSET_BUSINESS' THEN '资产业务' WHEN 'ITEM_BUSINESS' THEN '土规业务' ELSE '-' END ) AS businessType,
        off.order_id
        FROM
        finance_claim fc
        LEFT JOIN finance_real_fund frf ON frf.id = fc.real_fund_id
        left join user u on u.id = frf.creator_id
        left join user u1 on u1.id = fc.claim_user_id
        left join order_fund off on off.id = fc.order_fund_id
        where frf.deleted = 0 and fc.deleted = 0
        <if test="keyword!=null and keyword!='' ">
            and (
            frf.payer like concat ('%',#{keyword},'%')
            or frf.payer_bank like concat('%',#{keyword},'%')
            or u.name like concat('%',#{keyword},'%')
            or frf.payer_account like concat('%',#{keyword},'%')
            or frf.amount like concat('%',#{keyword},'%')
            or frf.remark like concat('%',#{keyword},'%')
            )
        </if>
        <if test="vo!=null and vo.startDate!=null and vo.startDate!=''">
            and frf.pay_datetime &gt;= #{vo.startDate}
        </if>
        <if test="vo!=null and vo.endDate!=null and vo.endDate!=''">
            and frf.pay_datetime &lt;= #{vo.endDate}
        </if>
        <if test="vo!=null and vo.xStartDate!=null and vo.xStartDate!=''">
            and fc.claim_datetime &gt;= #{vo.xStartDate}
        </if>
        <if test="vo!=null and vo.xEndDate!=null and vo.xEndDate!=''">
            and fc.claim_datetime &lt;= #{vo.xEndDate}
        </if>
        <if test="vo!=null and vo.businessType!=null and vo.businessType!=''">
            and off.business_type = #{vo.businessType}
        </if>
        <if test="vo!=null and vo.claimUserId!=null and vo.claimUserId!=''">
            and fc.claim_user_id = #{vo.claimUserId}
        </if>
        <if test="vo!=null and vo.userIds!=null and vo.userIds.size!=0">
            and  fc.claim_user_id in
            <foreach collection="vo.userIds" open="(" close=")" separator="," item="userId">
                #{userId}
            </foreach>
        </if>
        order by fc.claim_datetime DESC
    </sql>

    <select id="financeClaimsList" parameterType="com.dayou.vo.FinanceClaimsVO" resultType="com.dayou.vo.FinanceClaimsVO">
        <include refid="claimList" />
    </select>

    <select id="exportList" parameterType="com.dayou.vo.FinanceClaimsVO" resultType="com.dayou.vo.FinanceClaimsVO">
        <include refid="claimList" />
    </select>

    <select id="updateClaimProductionId" resultType="com.dayou.dto.history.HisClaimProd">
        SELECT
            t.id,
            p.id AS pid,
            fc.id AS fcid,
            fc.production_fund_id
        FROM
            ( SELECT id, created FROM order_fund WHERE business_type = #{businessType} AND deleted = 0 ) t
                LEFT JOIN ( SELECT id, order_fund_id FROM production_fund WHERE business_type = #{businessType} AND deleted = 0 ) p ON t.id = p.order_fund_id
                LEFT JOIN ( SELECT id, production_fund_id, order_fund_id FROM finance_claim WHERE deleted = 0 ) fc ON fc.order_fund_id = t.id
        WHERE
            fc.id IS NOT NULL  and p.id  is not null  and fc.production_fund_id is null
        ORDER BY
            t.created DESC
    </select>
</mapper>
