<?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.account.mapper.account.AccountDeptRunningWaterMapper">
    <select id="getPage" resultType="com.fjhx.account.entity.account.vo.AccountRunningWaterVo">
        select arw.id,
               arw.account_management_id,
               arw.status,
               arw.amount,
               arw.currency,
               arw.name,
               arw.received,
               arw.opening_bank,
               arw.account_opening,
               arw.transaction_time,
               arw.remarks,
               arw.create_user,
               arw.create_time,
               arw.update_user,
               arw.update_time,
               am.alias accountManagementName,
               adrw.type,
               adrw.id  accountDeptRunningWaterId
        from account_running_water arw
                 left join account_management am on arw.account_management_id = am.id
                 left join account_dept_running_water adrw on arw.id = adrw.running_water_id
            ${ew.customSqlSegment}
    </select>

    <select id="DeptRunningWaterReport" resultType="com.fjhx.account.entity.account.vo.AccountRunningWaterVo">
        SELECT SUM(IF(ar.`status` = 10, wd.amount, 0)) incomeAmount,
               SUM(IF(ar.`status` = 20, wd.amount, 0)) expenditureAmount,
               wd.dept_id                              deptId,
               DATE_FORMAT(ar.create_time, '%Y-%m') time,
	        SUM(IF(ar.`status` = 10,wd.amount,0) - IF(ar.`status` = 20,wd.amount,0)) balanceAmount
        FROM
            account_dept_running_water rw
            JOIN account_dept_running_water_detail wd
        ON rw.id = wd.dept_running_water_id
            LEFT JOIN account_running_water ar ON rw.running_water_id = ar.id
            ${ew.customSqlSegment}
    </select>
    <select id="deptRunningWaterStatistics" resultType="com.fjhx.account.entity.account.vo.AccountRunningWaterVo">
        select
        arw.status,
        <!-- 如果没有分配部门，则使用资金流水表的金额来计算无部门收入数据-->
        IF(arw.`status` = 10,if(rwd.amount is null,ifnull(sum(arw.amount),0),ifnull(sum(rwd.amount),0)),0) incomeAmount,
        <!-- 如果没有分配部门，则使用资金流水表的金额来计算无部门支出数据-->
        IF(arw.`status` = 20,if(rwd.amount is null,ifnull(sum(arw.amount),0),ifnull(sum(rwd.amount),0)),0)
        expenditureAmount,
        adrw.dept_id
        from account_running_water arw
        left join account_dept_running_water adrw on arw.id = adrw.running_water_id
        left join account_dept_running_water_detail rwd on adrw.id = rwd.dept_running_water_id
        ${ew.customSqlSegment}
    </select>

</mapper>
