<?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="cn.superdesk.uniorder.dao.mapper._statistics.PayableStatisticsMapper">


	<resultMap id="BaseResultMap" type="cn.superdesk.uniorder.dao.entity._dashboard.TempDashboard">
		<id column="id" property="id" jdbcType="BIGINT"/>
	</resultMap>
	<resultMap id="DashboardProjectPurchaseResultMap" type="cn.superdesk.uniorder.dto.vo._dashboard.UnifiedDashboardProjectPurchaseVo">
		<result column="projectId" property="projectId" jdbcType="BIGINT"/>
		<result column="projectName" property="projectName" jdbcType="VARCHAR"/>
		<result column="orderAmount" property="orderAmount" jdbcType="DECIMAL"/>
		<result column="lng" property="lng" jdbcType="DECIMAL"/>
		<result column="lat" property="lat" jdbcType="DECIMAL"/>
	</resultMap>




    <!--应付明细查询-->
	<select id="queryPayableDetailData" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableDetailDataVo">

		SELECT

		ascu.accounting_order_sn accountingOrderSn,
		ascu.update_user_id chargeUserId,
		ascu.update_time chargeCreatedAt,
		sysUser.fullname chargeUserName,

		uoc.id AS creditId,
		uoc.id AS creditNo,
		uoc.credit_type creditType, #0为微信 其他福利积分
		uoc.credit_name  creditName, #积分类型名称
		uoc.balance balance,
		#uoc.balance / (1 + uog.operation_tax_rate) incomeNoTax,
		#uoc.balance - (		uoc.balance / (1 + uog.operation_tax_rate)	) taxAmount,

		uog.id AS creditId,
		uo.sale_id settlementId,
		uo.sale_name settlementName,
		uo.order_sn orderSn,
		uog.id AS creditNo,
		uo.service_no serviceNo,
		uo.service_name serviceNoName,
		uo.refund_order_sn refundOrderSn,
		uo.service_name serviceName,
		uo.order_state orderState,
		uo.order_state_name orderStateName,
		uo.create_time billCreatedAt,
		uo.finish_time finishTime,
		uog.id goodsId,
		uog.goods_name goodsName,
		uog.unit goodsUnit,
		uog.quantity goodsQuantity,
		uog.cost_price goodsPrice,
		uog.cost_price * uog.quantity AS goodsTotalAmount,
		uog.merch_tax_code merchTaxCode,
		uog.merch_tax_rate merchTaxRate,
		uog.accounting_state_customer accountingAtate,
		uo.invoice_status makeInvoiceStatus,
		uog.back_account_status backStatus,

		0 costNoTax,
		0 taxAmount,
		#uog.cost_price * uog.quantity / (1 + uog.merch_tax_rate) costNoTax,
		#uog.cost_price * uog.quantity - (	uog.cost_price * uog.quantity / (1 + uog.operation_tax_rate)	) taxAmount,
		0 payableAmount,
		uoc.balance/uog.price*uog.quantity*uog.cost_price balanceCost

		FROM
		( accounting_score_customer ascu
		RIGHT JOIN accounting_score_customer_x_credit ascuxc on ascu.accounting_order_sn = ascuxc.accounting_order_sn )
		LEFT JOIN unified_order_credit uoc ON ascuxc.unified_order_credit_id = uoc.id
		LEFT JOIN unified_order_goods uog ON ascuxc.unified_order_goods_id = uog.id
		LEFT JOIN unified_order uo ON ascuxc.unified_order_id = uo.id
		LEFT JOIN sys_enterprise se ON ascu.enterprise_id = se.enterprise_id
		LEFT JOIN sys_oder_user AS sou ON uo.purchase_user_id = sou.user_id
		LEFT join sys_user sysUser on ascu.update_user_id=sysUser.id

		where
		1=1

		#and ascu.accounting_order_sn = 'DZ2020102100004'

		#and uo.service_no = 'FLSC_QCH'
		#and uog.receivable_statistics_state = 0
		#and uo.complet_state = 1 #1-已完成
		#and uo.finish_time is not null
		and uog.operation_tax_rate is not null
		#and uoc.accounting_state_customer in (1,2)

		<if test="accountingOrderSn != null and accountingOrderSn != ''" >
			and ascu.accounting_order_sn = #{accountingOrderSn}
		</if>


	</select>


	<!--应付运费明细查询-->
	<select id="queryPayableFreightDetailData" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableDetailDataVo">

		SELECT

		uog.id AS creditId,
		uo.sale_id settlementId,
		uo.sale_name settlementName,
		uo.order_sn orderSn,
		uog.id AS creditNo,
		uo.service_no serviceNo,
		uo.service_name serviceNoName,
		uo.refund_order_sn refundOrderSn,
		uo.service_name serviceName,
		uo.order_state orderState,
		uo.order_state_name orderStateName,
		uo.create_time billCreatedAt,
		uo.finish_time finishTime,
		uog.id goodsId,
		uog.goods_name goodsName,
		uog.unit goodsUnit,
		uog.quantity goodsQuantity,
		uog.cost_price goodsPrice,
		uog.cost_price * uog.quantity AS goodsTotalAmount,
		uog.merch_tax_code merchTaxCode,
		uog.merch_tax_rate merchTaxRate,
		uog.accounting_state_customer accountingAtate,
		uo.invoice_status makeInvoiceStatus,
		uog.back_account_status backStatus,
		uog.cost_price balanceCost,
		0 payableAmount,
		0 costNoTax,
		0 taxAmount

		FROM unified_order_goods uog
		LEFT JOIN unified_order uo ON uo.order_sn = uog.order_sn
		WHERE
		1 = 1
		#AND uo.service_no = 'FLSC_QCH'
		#and uog.receivable_statistics_state = 0
		#and uo.complet_state = 1 #1-已完成
		#and uo.finish_time is not null
		and uog.operation_tax_rate is not null
		#and uog.accounting_state_supplier in (1,2)
		#and uo.order_sn = 'ME20210303143102088615'
		and uog.goods_id =1 #商户承担运费

		<if test="orderSnList != null and orderSnList.size() &gt; 0">
			and uo.order_sn in (
			<foreach collection="orderSnList" index="index" item="item" separator=",">
				#{item}
			</foreach>
			)
		</if>

	</select>

	<!--查询应付每日数据-->
	<select id="queryPrayableDayData" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableDayDataVo">

         SELECT
            GROUP_CONCAT(id) detail_id,DATE_FORMAT(finish_time,'%Y-%m') pertain_month,DATE_FORMAT(finish_time,'%Y-%m-%d') account_at,settlement_id,service_no,service_no_name,accounting_order_sn,collection_order_sn,merch_tax_rate,

            credit_id,
            settlement_name,
            sum(cost_no_tax) cost_no_tax,
            sum(tax_amount) tax_amount,
            sum(payable_amount)payable_amount

        FROM
            st_payable_detail_data

            where 1 = 1

		<if test="chargeStatus != null and chargeStatus != ''">
			and charge_status = #{chargeStatus}
		</if>

		<if test="accountState != null and accountState != ''">
			and account_state = #{accountState}
		</if>

        GROUP BY DATE_FORMAT(finish_time,'%Y-%m-%d'),settlement_id,service_no,merch_tax_rate

	</select>

	<!--应付汇总报表-->
	<select id="getPayableStatisticsPageVoList" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableStatisticsPageVo">

		SELECT * from
		(

			SELECT
			settlement_id,
			settlement_name,
		    merch_tax_rate,
			sum(cost_no_tax) cost_no_tax,
			sum(tax_amount) tax_amount,
			sum(payable_amount) payable_amount
			FROM
		    st_payable_day_data t1
			WHERE
			1 = 1

			<if test="startTime != null and startTime != ''">
				and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
			</if>

			<if test="endTime != null and endTime != ''">
				and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
			</if>

			<if test="settlementId != null and settlementId != ''" >
				and settlement_id = #{settlementId}
			</if>

			<if test="serviceNo != null and serviceNo != ''" >
				and t1.service_no = #{serviceNo}
			</if>

			GROUP BY
			settlement_id,
		    merch_tax_rate


			UNION

			SELECT
			settlement_id,
			'小计',
			99 merch_tax_rate,
			sum(cost_no_tax) cost_no_tax,
			sum(tax_amount) tax_amount,
			sum(payable_amount) payable_amount
			FROM
		    st_payable_day_data t1
			WHERE
			1 = 1

			<if test="startTime != null and startTime != ''">
				and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
			</if>

			<if test="endTime != null and endTime != ''">
				and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
			</if>

			<if test="settlementId != null and settlementId != ''" >
				and t1.settlement_id = #{settlementId}
			</if>

			<if test="serviceNo != null and serviceNo != ''" >
				and t1.service_no = #{serviceNo}
			</if>

			GROUP BY
			settlement_id
		) t
		where 1=1

		<if test="listSettlementId != null and listSettlementId.size() &gt; 0">
			and settlement_id in (
			<foreach collection="listSettlementId" index="index" item="item" separator=",">
				#{item}
			</foreach>
			)
		</if>


		ORDER BY t.settlement_id,t.merch_tax_rate


	</select>

	<!--获得应付报表分页后的settlementId-->
	<select id="getPayableStatisticsPageLimitSettlementId" resultType="java.lang.Long">

		SELECT
		settlement_id
		FROM
		st_payable_day_data t1
		WHERE
		1 = 1
		<if test="startTime != null and startTime != ''">
			and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
		</if>

		<if test="endTime != null and endTime != ''">
			and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
		</if>

		<if test="settlementId != null and settlementId != ''" >
			and t1.settlement_id = #{settlementId}
		</if>

		<if test="serviceNo != null and serviceNo != ''" >
			and t1.service_no = #{serviceNo}
		</if>

		GROUP BY 		settlement_id


	</select>



	<!--查询应付报表总页数-->
	<select id="getPayableStatisticsTotalPageNum" resultType="java.lang.Integer">

		SELECT count(*) totalNum from
		(
			SELECT
			settlement_id
			FROM
		    st_payable_day_data t1
			WHERE
			1 = 1
			<if test="startTime != null and startTime != ''">
				and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
			</if>

			<if test="endTime != null and endTime != ''">
				and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
			</if>

			<if test="settlementId != null and settlementId != ''" >
				and t1.settlement_id = #{settlementId}
			</if>

			<if test="serviceNo != null and serviceNo != ''" >
				and t1.service_no = #{serviceNo}
			</if>

			GROUP BY 		settlement_id
		)t



	</select>


	<!--查询应付报表合计Data-->
	<select id="getPayableStatisticsTotalData" resultType="java.util.HashMap">

		SELECT
		sum(cost_no_tax) costNoTax,
		sum(tax_amount) taxAmount,
		sum(payable_amount) payableAmount
		FROM
		st_payable_day_data t1
		WHERE
		1 = 1
		<if test="startTime != null and startTime != ''">
			and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
		</if>

		<if test="endTime != null and endTime != ''">
			and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
		</if>

		<if test="settlementId != null and settlementId != ''" >
			and t1.settlement_id = #{settlementId}
		</if>

		<if test="serviceNo != null and serviceNo != ''" >
			and t1.service_no = #{serviceNo}
		</if>


	</select>

	<select id="getPayableStatisticsDayDataByExcel" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableStatisticsDayDataByExcelVo">

		SELECT
		*,
		CASE WHEN t1.account_type =1 then '正常入账' WHEN t1.account_type =2 then '撤销入账'  else '冲销入账' end accountTypeName,
		CASE WHEN t1.account_way =1 then '系统入账' else '手工记账' end accountWayName,
		DATE_FORMAT(account_at,'%Y-%m-%d') formatAccountAt,
		merch_tax_rate/100 formatMerchTaxRate
		FROM
		st_payable_day_data t1
		WHERE
		1 = 1
		<if test="startTime != null and startTime != ''">
			and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
		</if>

		<if test="endTime != null and endTime != ''">
			and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
		</if>

		<if test="settlementId != null and settlementId != ''" >
			and t1.settlement_id = #{settlementId}
		</if>

		<if test="serviceNo != null and serviceNo != ''" >
			and t1.service_no = #{serviceNo}
		</if>


	</select>


	<select id="getPayableStatisticsDetailDataByExcel" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableStatisticsDetailDataByExcelVo">

		SELECT 		*,
		CASE WHEN t1.account_state =0 then '未入账' WHEN t1.account_state =1 then '已入账' WHEN t1.account_state =3 then '撤销入账'  else '已撤销' end accountStateName,
		CASE WHEN t1.accounting_state =1 then '已确认' else '已取消' end accountingTypeName,
		CASE WHEN t1.data_type =1 then '订单流水' else '订单商品' end dataTypeName,
		CASE WHEN t1.charge_status =1 then '' WHEN t1.account_state =2 then '已冲销'  else '已撤销' end chargeStatusName,
		merch_tax_rate/100 formatMerchTaxRate
		from  st_payable_detail_data t1
		where 1=1
		<!--and t1.account_state =1-->

		<if test="startTime != null and startTime != ''">
			and t1.account_at &gt;= concat(#{startTime}, ' 00:00:00')
		</if>

		<if test="endTime != null and endTime != ''">
			and t1.account_at &lt;= concat(#{endTime}, ' 23:59:59')
		</if>

		<if test="settlementId != null and settlementId != ''" >
			and t1.settlement_id = #{settlementId}
		</if>

		<if test="serviceNo != null and serviceNo != ''" >
			and t1.service_no = #{serviceNo}
		</if>

		ORDER BY created_at


	</select>
	<select id="getPayableBalanceVOList"
			resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableBalanceDetail">
		SELECT
		    t.settlementName,
		    t.serviceNoName,
		    t.payableAmount,
		    t.actualPay,
		    (t.payableAmount - t.actualPay) as endingBalance
		FROM
		    (
				SELECT
				t1.settlement_id,
				t2.sale_name AS settlementName,
				t1.service_no_name AS serviceNoName,
				sum(
				IF
				( t1.account_type IN ( 1, 2 ), t1.payable_amount, 0 )) AS payableAmount,
				sum(
				IF
				( t1.account_type = 3, t1.payable_amount, 0 )) AS actualPay
				FROM
				st_payable_day_data t1 left join unified_supplier t2 on t1.settlement_id = t2.sale_id and t1.service_no = t2.service_no
				WHERE
				1 = 1
				<if test="serviceNo != null and serviceNo !='' ">
					and t1.service_no = #{serviceNo}
				</if>
				<if test="startDate != null and startDate != ''">
					and t1.account_at &gt;= concat(#{startDate}, ' 00:00:00')
				</if>
				<if test="endDate != null and endDate != ''">
					and t1.account_at &lt;= concat(#{endDate}, ' 23:59:59')
				</if>
				<if test="settlementId != null and settlementId != ''" >
					and t1.settlement_id = #{settlementId}
				</if>
				GROUP BY t1.settlement_id
			)t
			where 1 = 1
		<if test="settlementIds != null and settlementIds.size() > 0">
			and settlement_id in (
			<foreach collection="settlementIds" index="index" item="item" separator=",">
				#{item}
			</foreach>
			)
		</if>
		order by endingBalance desc
	</select>


	<!--应付回款对冲数据-->
	<select id="queryPayableReturnedMoneyDetailData" resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableDetailDataVo">

		SELECT

		ascu.accounting_order_sn accountingOrderSn,
		ascu.update_user_id chargeUserId,
		ascu.update_time chargeCreatedAt,
		sysUser.fullname chargeUserName,

		IFNULL(uoc.id,uog.id) AS creditId,
		uoc.id AS creditNo,
		uoc.credit_type creditType, #0为微信 其他福利积分
		uoc.credit_name  creditName, #积分类型名称
		uoc.balance balance,
		#uoc.balance / (1 + uog.operation_tax_rate) incomeNoTax,
		#uoc.balance - (		uoc.balance / (1 + uog.operation_tax_rate)	) taxAmount,

		uog.id AS creditId,
		uo.sale_id settlementId,
		uo.sale_name settlementName,
		uo.order_sn orderSn,
		uog.id AS creditNo,
		uo.service_no serviceNo,
		uo.service_name serviceNoName,
		uo.refund_order_sn refundOrderSn,
		uo.service_name serviceName,
		uo.order_state orderState,
		uo.order_state_name orderStateName,
		uo.create_time billCreatedAt,
		uo.finish_time finishTime,
		uog.id goodsId,
		uog.goods_name goodsName,
		uog.unit goodsUnit,
		uog.quantity goodsQuantity,
		uog.cost_price goodsPrice,
		uog.cost_price * uog.quantity AS goodsTotalAmount,
		uog.merch_tax_code merchTaxCode,
		uog.merch_tax_rate merchTaxRate,
		uog.accounting_state_customer accountingAtate,
		uo.invoice_status makeInvoiceStatus,
		uog.back_account_status backStatus,

		0 costNoTax,
		0 taxAmount,
		#uog.cost_price * uog.quantity / (1 + uog.merch_tax_rate) costNoTax,
		#uog.cost_price * uog.quantity - (	uog.cost_price * uog.quantity / (1 + uog.operation_tax_rate)	) taxAmount,
		0 payableAmount,
		uoc.balance/uog.price*uog.quantity*uog.cost_price balanceCost

		FROM
		( accounting_unified_supplier ascu
		RIGHT JOIN accounting_unified_supplier_x_goods ascuxc on ascu.accounting_order_sn = ascuxc.accounting_order_sn )
		LEFT JOIN unified_order_goods uog ON ascuxc.unified_order_goods_id = uog.id
		LEFT JOIN unified_order uo ON ascuxc.unified_order_id = uo.id
		#LEFT JOIN sys_enterprise se ON ascu.enterprise_id = se.enterprise_id
		LEFT JOIN sys_oder_user AS sou ON uo.purchase_user_id = sou.user_id
		LEFT join sys_user sysUser on ascu.update_user_id=sysUser.id
		LEFT JOIN unified_order_credit uoc ON uoc.goods_id = ascuxc.goods_id and uoc.order_sn  = ascuxc.order_sn

		where
		1=1

		#and ascu.accounting_order_sn = 'cs3_GYSDZ20220615005'

		#and uo.service_no = 'FLSC_QCH'
		#and uog.receivable_statistics_state = 0
		#and uo.complet_state = 1 #1-已完成
		#and uo.finish_time is not null
		and uog.operation_tax_rate is not null
		#and uoc.accounting_state_customer in (1,2)

		<if test="accountingOrderSn != null and accountingOrderSn != ''" >
			and ascu.accounting_order_sn = #{accountingOrderSn}
		</if>


	</select>
	<select id="selectPayableBalanceByCondition"
			resultType="cn.superdesk.uniorder.dto.vo._statistics.payable.PayableStatisticsDayDataByExcelVo">
		select t1.id,
			   date_format(t1.account_at, '%Y-%m-%d')     as accountAtStr,
			   t1.pertain_month as pertainMonth,
			   case t1.account_type
				   when 1 then '正常入账'
				   when 2 then '撤销入账'
				   when 3 then '冲销账款'
				   else '未知类型' end                        as accountTypeName,
			   case t1.account_way
				   when 0 then '系统入账'
				   when 1 then '手工记账'
				   else '未知' end                          as accountWayName,
			   t1.accounting_order_sn as accountingOrderSn,
			   t1.settlement_id as settlementId,
			   t2.sale_name                               as settlementName,
			   t1.service_no as serviceNo,
			   format(t1.merch_tax_rate, 2)               as merchTaxRate,
			   t1.cost_no_tax as costNoTax,
			   t1.tax_amount as taxAmount,
			   t1.payable_amount as payableAmount,
			   t1.create_user_name as createUserName,
			   date_format(t1.created_at, '%Y-%m-%d %T')  as createTimeStr,
			   t1.update_user_name as updateUserName,
			   date_format(t1.update_time, '%Y-%m-%d %T') as updateTimeStr
		from st_payable_day_data t1 left join unified_supplier t2 on t1.settlement_id = t2.sale_id and t1.service_no = t2.service_no
		where 1=1
		<if test="queryType == 3">
			and t1.account_type in (1,2)
		</if>
		<if test="queryType == 4">
			and t1.account_type = 3
		</if>

		<if test="serviceNo != null and serviceNo !='' ">
			and t1.service_no = #{serviceNo}
		</if>
		<if test="startDate != null and startDate != ''">
			and t1.account_at &gt;= concat(#{startDate}, ' 00:00:00')
		</if>
		<if test="endDate != null and endDate != ''">
			and t1.account_at &lt;= concat(#{endDate}, ' 23:59:59')
		</if>
		<if test="settlementId != null and settlementId != ''" >
			and t1.settlement_id = #{settlementId}
		</if>

		<if test="settlementIds != null and settlementIds.size() > 0">
			and t1.settlement_id in (
			<foreach collection="settlementIds" index="index" item="item" separator=",">
				#{item}
			</foreach>
			)
		</if>
		order by t1.account_at asc, t1.created_at asc
	</select>
	<select id="getSettlementIdsPage" resultType="java.lang.Long">

		SELECT
			settlement_id
		FROM
		st_payable_day_data t1
		WHERE
		1 = 1
		<if test="startDate != null and startDate != ''">
			and t1.account_at &gt;= concat(#{startDate}, ' 00:00:00')
		</if>
		<if test="endDate != null and endDate != ''">
			and t1.account_at &lt;= concat(#{endDate}, ' 23:59:59')
		</if>
		<if test="settlementId != null and settlementId != ''" >
			and t1.settlement_id = #{settlementId}
		</if>
		<if test="serviceNo != null and serviceNo != ''">
			and t1.service_no = #{serviceNo}
		</if>
		GROUP BY 		settlement_id


	</select>

</mapper>