<?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.dk.mdm.mapper.mac.AccountItemMapper">

    <!-- 通用设置 -->
    <!-- 通用查询列 -->
    <sql id="Base_Column_List">
        item_id
        , acc_item_type, object_id, org_id, staff_id, biznis_type, biznis_id, biznis_no, acc_date, rec_status, amt_rec, amt_pay, amt_should, amt_handle, amt_waive, amt_residue, flg_lock, remarks, make_staff, make_time, flg_valid, cp_id
    </sql>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dk.mdm.model.pojo.mac.AccountItem">
        <id column="item_id" property="itemId"/>
        <result column="acc_item_type" property="accItemType"/>
        <result column="object_id" property="objectId" typeHandler="UuidTypeHandler"/>
        <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
        <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
        <result column="biznis_type" property="biznisType"/>
        <result column="biznis_id" property="biznisId" typeHandler="UuidTypeHandler"/>
        <result column="biznis_no" property="biznisNo"/>
        <result column="acc_date" property="accDate" typeHandler="TimestampTypeHandler"/>
        <result column="rec_status" property="recStatus"/>
        <result column="amt_rec" property="amtRec"/>
        <result column="amt_pay" property="amtPay"/>
        <result column="amt_should" property="amtShould"/>
        <result column="amt_handle" property="amtHandle"/>
        <result column="amt_waive" property="amtWaive"/>
        <result column="amt_residue" property="amtResidue"/>
        <result column="flg_lock" property="flgLock"/>
        <result column="remarks" property="remarks"/>
        <result column="make_staff" property="makeStaff" typeHandler="UuidTypeHandler"/>
        <result column="make_time" property="makeTime" typeHandler="TimestampTypeHandler"/>
        <result column="flg_valid" property="flgValid"/>
        <result column="cp_id" property="cpId"/>
    </resultMap>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMapResponse" type="com.dk.mdm.model.response.mac.AccountItemResponse">
        <id column="item_id" property="itemId"/>
        <result column="acc_item_type" property="accItemType"/>
        <result column="object_id" property="objectId" typeHandler="UuidTypeHandler"/>
        <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
        <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
        <result column="biznis_type" property="biznisType"/>
        <result column="biznis_id" property="biznisId" typeHandler="UuidTypeHandler"/>
        <result column="biznis_no" property="biznisNo"/>
        <result column="acc_date" property="accDate" typeHandler="TimestampTypeHandler"/>
        <result column="rec_status" property="recStatus"/>
        <result column="amt_rec" property="amtRec"/>
        <result column="amt_pay" property="amtPay"/>
        <result column="amt_should" property="amtShould"/>
        <result column="amt_handle" property="amtHandle"/>
        <result column="amt_waive" property="amtWaive"/>
        <result column="amt_residue" property="amtResidue"/>
        <result column="flg_lock" property="flgLock"/>
        <result column="remarks" property="remarks"/>
        <result column="make_staff" property="makeStaff" typeHandler="UuidTypeHandler"/>
        <result column="make_time" property="makeTime" typeHandler="TimestampTypeHandler"/>
        <result column="flg_valid" property="flgValid"/>
        <result column="cp_id" property="cpId"/>
    </resultMap>

    <!-- 通用条件列 -->
    <sql id="Condition">
        <if test="accItemType != null and accItemType != ''">
            AND t.acc_item_type = #{accItemType}
        </if>
        <if test="objectId != null and objectId != ''">
            AND t.object_id = #{objectId}::uuid
        </if>
        <if test="orgId != null and orgId != ''">
            AND t.org_id = #{orgId}::uuid
        </if>
        <if test="staffId != null and staffId != ''">
            AND t.staff_id = #{staffId}::uuid
        </if>
        <if test="biznisType != null and biznisType != ''">
            AND t.biznis_type = #{biznisType}
        </if>
        <if test="biznisId != null and biznisId != ''">
            AND t.biznis_id = #{biznisId}
        </if>
        <if test="biznisNo != null and biznisNo != ''">
            AND t.biznis_no = #{biznisNo}
        </if>
        <if test="accDate != null">
            AND t.acc_date = #{accDate}
        </if>
        <if test="recStatus != null and recStatus != ''">
            AND t.rec_status = #{recStatus}
        </if>
        <if test="amtRec != null">
            AND t.amt_rec = #{amtRec}
        </if>
        <if test="amtPay != null">
            AND t.amt_pay = #{amtPay}
        </if>
        <if test="amtShould != null">
            AND t.amt_should = #{amtShould}
        </if>
        <if test="amtHandle != null">
            AND t.amt_handle = #{amtHandle}
        </if>
        <if test="amtWaive != null">
            AND t.amt_waive = #{amtWaive}
        </if>
        <if test="amtResidueFlg != null">
            AND t.amt_residue > 0
        </if>
        <if test="amtResidueZeroFlg != null">
            AND t.amt_residue != 0
        </if>
        <if test="amtResidue != null">
            AND t.amt_residue = #{amtResidue}
        </if>
        <if test="flgLock != null">
            AND t.flg_lock = #{flgLock}
        </if>
        <if test="remarks != null and remarks != ''">
            AND t.remarks = #{remarks}
        </if>
        <if test="makeStaff != null and makeStaff != ''">
            AND t.make_staff = #{makeStaff}
        </if>
        <if test="makeTime != null">
            AND t.make_time = #{makeTime}
        </if>
        <if test="makeTimeStart != null and makeTimeEnd != null">
            AND t.make_time &gt;= #{makeTimeStart}::timestamp with time zone
            AND t.make_time &lt; #{makeTimeEnd}::timestamp with time zone + interval '1 day'
        </if>
        <if test="flgValid != null">
            AND t.flg_valid = #{flgValid}
        </if>
        <if test="cpId != null">
            AND t.cp_id = #{cpId}
        </if>
        <!-- 如果是退货，只差剩余应收小于0的 -->
        <if test="formType == 'refund'">
            AND t.amt_residue <![CDATA[ < ]]> 0
        </if>
        <if test="orderId != null">
            AND tpo.from_id = #{orderId}::uuid
        </if>
        <if test="outTypeList != null and outTypeList.size()>0">
            AND tpo.out_type =any(#{outTypeList,typeHandler=StringListTypeHandler})
        </if>
        <if test="intoTypeList != null and intoTypeList.size()>0">
            AND tpi.into_type =any(#{intoTypeList,typeHandler=StringListTypeHandler})
        </if>
    </sql>

    <sql id="idsForeach">
        <!-- 根据主键itemId批量操作 -->
        WHERE item_id in
        <foreach collection="ids" index="index" item="item" separator="," open="(" close=")">
            #{item}
        </foreach>
    </sql>

    <!-- 根据主键查询表t_mac_account_item的一行数据 -->
    <select id="selectByCond" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_mac_account_item as t
        where 1 = 1
        <include refid="Condition"/>
    </select>

    <!-- 查询表t_mac_account_item，（条件查询）个数 -->
    <select id="countByCond" resultType="Long">
        SELECT
        count(1)
        FROM dkic_b.t_mac_account_item as t
        where 1 = 1
        <include refid="Condition"/>
    </select>

    <!--查询应收和收款汇总（根据制单员权限）-->
    <select id="getReceivableAccountSum" resultType="Map">
        select

        (SELECT SUM ( tpo.fact_amt) AS receivable
        FROM
        dkic_b.t_psi_order tpo
        WHERE
        tpo.flg_valid
        AND tpo.cp_id = #{cpId}
        AND (
        tpo.make_staff = #{staffId}::uuid
        OR EXISTS ( SELECT 1 FROM dkic_b.t_mst_staff_purview tmsp WHERE tmsp.staff_id = tpo.make_staff AND
        tmsp.purview_code = 'PU10000003' )
        )
        <!--开始日期-->
        <if test="accDateStart != null">
            AND tpo.make_time &gt;= #{accDateStart,typeHandler=TimestampTypeHandler}
        </if>
        <!--截止日期-->
        <if test="accDateEnd != null">
            AND tpo.make_time &lt;= #{accDateEnd,typeHandler=TimestampTypeHandler}
        </if>
        ),
        (SELECT SUM ( tpo.fact_amt) AS returnAmt
        FROM
        dkic_b.t_psi_outbound tpo
        WHERE
        tpo.flg_valid
        AND tpo.out_type = '出库类型-销退回库'
        AND tpo.cp_id = #{cpId}
        AND (
        tpo.make_staff = #{staffId}::uuid
        OR EXISTS ( SELECT 1 FROM dkic_b.t_mst_staff_purview tmsp WHERE tmsp.staff_id = tpo.make_staff AND
        tmsp.purview_code = 'PU10000003' )
        )
        <!--开始日期-->
        <if test="accDateStart != null">
            AND tpo.out_date &gt;= #{accDateStart,typeHandler=TimestampTypeHandler}
        </if>
        <!--截止日期-->
        <if test="accDateEnd != null">
            AND tpo.out_date &lt;= #{accDateEnd,typeHandler=TimestampTypeHandler}
        </if>
        ),
        (SELECT SUM ( tmrp.sum_amt_rec) AS receipt
        FROM dkic_b.t_mac_rec_pay tmrp
        WHERE
        tmrp.flg_valid
        AND tmrp.cp_id = #{cpId}
        AND (
        tmrp.make_staff = #{staffId}::uuid
        OR EXISTS ( SELECT 1 FROM dkic_b.t_mst_staff_purview tmsp WHERE tmsp.staff_id = tmrp.make_staff AND
        tmsp.purview_code = 'PU10000003' )
        )
        <!--开始日期-->
        <if test="accDateStart != null">
            AND tmrp.acc_date &gt;= #{accDateStart,typeHandler=TimestampTypeHandler}
        </if>
        <!--截止日期-->
        <if test="accDateEnd != null">
            AND tmrp.acc_date &lt;= #{accDateEnd,typeHandler=TimestampTypeHandler}
        </if>
        )

    </select>

    <!-- 查询应收账款明细 -->
    <select id="getReceivableAccountItem" resultMap="BaseResultMapResponse">
        SELECT t.item_id,
        t.item_id as "accItemId",
        t.acc_item_type,
        t.object_id,
        tmc.cus_code as "cusCode",
        tmc.cus_name as "cusName",
        tmc.cus_phone as "cusPhone",
        tmc.address_full as "addressFull",
        t.org_id,
        tmo.org_name as "orgName",
        t.staff_id,
        tms.staff_name as "staffName",
        t.biznis_type,
        t.biznis_id,
        t.biznis_no,
        t.acc_date,
        t.rec_status,
        sys.f_get_name_i18n(tdk1.kind_name_i18n, #{i18n}) as "recStatusName",
        coalesce(sys.f_get_name_i18n(tdk2.kind_name_i18n, #{i18n}), '其他收入') as "biznisTypeName",
        t.amt_rec,
        t.amt_pay,
        t.amt_should,
        t.amt_handle,
        t.amt_waive,
        t.amt_residue as "amtNotHandle",
        t.amt_residue as "amtReceivableHandle",
        t.amt_residue,
        t.remarks,
        t.make_staff,
        t.make_time,
        t.flg_valid,
        t.cp_id
        FROM dkic_b.t_mac_account_item as t
        left join dkic_b.t_psi_outbound as tpo on tpo.out_id = t.biznis_id and t.biznis_type = 't_psi_outbound'
        LEFT JOIN sys.t_data_kind tdk2 ON tdk2.kind_code = tpo.out_type
        left join dkic_b.t_mac_other_receivable as tmor
        on tmor.receivable_id = t.biznis_id and t.biznis_type = 't_mac_other_receivable'
        left join dkic_b.t_mst_customer tmc on tmc.cus_id = t.object_id
        left join dkic_b.t_mst_org tmo on tmo.org_id = t.org_id
        left join dkic_b.t_mst_staff tms on tms.staff_id = t.staff_id
        left join sys.t_data_kind as tdk1 on t.rec_status = tdk1.kind_code
        where t.flg_valid
        and t.acc_item_type = '账款类型-应收'
        and t.amt_residue <![CDATA[ <> ]]> 0
        <include refid="Condition"/>
        order by t.acc_date
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>

    <!-- 查询应付账款明细 -->
    <select id="getPayableAccountItem" resultMap="BaseResultMapResponse">
        SELECT t.item_id,
        t.item_id as "accItemId",
        t.acc_item_type,
        t.object_id,
        supplier.sup_code as "supCode",
        supplier.sup_name as "supName",
        t.org_id,
        tmo.org_name as "orgName",
        t.staff_id,
        tms.staff_name as "staffName",
        t.biznis_type,
        t.biznis_id,
        t.biznis_no,
        t.acc_date,
        t.rec_status,
        sys.f_get_name_i18n(tdk1.kind_name_i18n, #{i18n}) as "recStatusName",
        sys.f_get_name_i18n(tdk2.kind_name_i18n, #{i18n}) as "biznisTypeName",
        t.amt_rec,
        t.amt_pay,
        t.amt_should,
        t.amt_handle,
        t.amt_waive,
        t.amt_residue,
        t.amt_residue as "amtNotHandle",
        t.amt_residue as "amtPayableHandle",
        t.remarks,
        t.make_staff,
        t.make_time,
        t.flg_valid,
        t.cp_id
        FROM dkic_b.t_mac_account_item as t
        left join dkic_b.t_psi_inbound as tpi on tpi.into_id = t.biznis_id and t.biznis_type = 't_psi_inbound'
        LEFT JOIN sys.t_data_kind tdk2 ON tdk2.kind_code = tpi.into_type
        left join dkic_b.t_mst_supplier supplier on supplier.sup_id = t.object_id
        left join dkic_b.t_mst_org tmo on tmo.org_id = t.org_id
        left join dkic_b.t_mst_staff tms on tms.staff_id = t.staff_id
        left join sys.t_data_kind as tdk1 on t.rec_status = tdk1.kind_code
        where t.flg_valid
        and t.acc_item_type = '账款类型-应付'
        and t.amt_residue <![CDATA[<>]]> 0
        <include refid="Condition"/>
        order by t.acc_date
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>

    <!-- 查询应收账款明细 -->
    <select id="getReceivableAccountItemForUpdate" resultMap="BaseResultMapResponse">
        SELECT t.item_id,
               t.item_id     as "accItemId",
               t.acc_item_type,
               t.object_id,
               t.org_id,
               t.staff_id,
               t.biznis_type,
               t.biznis_id,
               t.biznis_no,
               t.acc_date,
               t.rec_status,
               t.amt_rec,
               t.amt_pay,
               t.amt_should,
               t.amt_handle,
               t.amt_waive,
               t.amt_residue as "amtNotHandle",
               t.amt_residue as "amtReceivableHandle",
               t.amt_residue,
               t.remarks,
               t.make_staff,
               t.make_time,
               t.flg_valid,
               t.cp_id
        FROM dkic_b.t_mac_account_item as t
                 inner join dkic_b.t_psi_outbound as tpo
                            on tpo.out_id = t.biznis_id and t.biznis_type = 't_psi_outbound'
        where t.flg_valid
          and t.acc_item_type = '账款类型-应收'
          and t.amt_residue <![CDATA[<>]]> 0
          AND t.object_id = #{objectId}::uuid
          AND tpo.from_id = #{orderId}::uuid
        order by t.acc_date
            for
        update
    </select>

    <!-- 根据主键查询表t_mac_account_item的一行数据 -->
    <select id="selectById" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_mac_account_item
        WHERE item_id = #{id}::uuid
    </select>

    <!-- 根据主键锁定表t_mac_account_item的一行数据 -->
    <select id="selectByIdForUpdate" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_mac_account_item
        WHERE item_id = #{id}::uuid
        for update
    </select>

    <!-- 根据主键锁定表t_mac_account_item的多行数据 -->
    <select id="selectByIdsForUpdate" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_mac_account_item
        <include refid="idsForeach"/>
        for update
    </select>

    <insert id="insertBatch">
        insert into dkic_b.t_mac_account_item
        (
        <trim suffixOverrides=",">
            acc_item_type,
            object_id,
            org_id,
            staff_id,
            biznis_type,
            biznis_id,
            biznis_no,
            acc_date,
            rec_status,
            amt_rec,
            amt_pay,
            amt_should,
            amt_handle,
            amt_waive,
            amt_residue,
            remarks,
            make_staff,
            make_time,
            cp_id,
            op_app_code,
        </trim>
        )
        values
        <foreach collection="list" index="index" item="item" separator=",">
            (
            <trim suffixOverrides=",">
                #{item.accItemType},
                #{item.objectId}::uuid,
                #{item.orgId}::uuid,
                #{item.staffId}::uuid,
                #{item.biznisType},
                #{item.biznisId}::uuid,
                #{item.biznisNo},
                #{item.accDate},
                #{item.recStatus},
                #{item.amtRec},
                #{item.amtPay},
                #{item.amtShould},
                #{item.amtHandle},
                #{item.amtWaive},
                #{item.amtResidue},
                #{item.remarks},
                #{item.makeStaff}::uuid,
                #{item.makeTime},
                #{item.cpId},
                #{item.opAppCode},
            </trim>
            )
        </foreach>
    </insert>

    <!-- 查询收款总额 -->
    <select id="getSumAmtRec" resultType="java.util.Map">
        SELECT COALESCE(sum(t.amt_rec), 0) as "sumAmtRec"
        FROM dkic_b.t_mac_account_item as t
        where t.flg_valid
          and t.flg_lock = false
          and t.acc_item_type = '账款类型-收款'
          and t.object_id = #{id}::uuid
    </select>

    <!-- 查询收款总额（锁定金额） -->
    <select id="getSumAmtRecLock" resultType="java.util.Map">
        SELECT COALESCE(sum(t.amt_rec), 0) as "sumAmtRecLock"
        FROM dkic_b.t_mac_account_item as t
        where t.flg_valid
          and t.flg_lock
          and t.acc_item_type = '账款类型-收款'
          and t.object_id = #{id}::uuid
    </select>

    <!-- 查询付款总额 -->
    <select id="getSumAmtPay" resultType="java.util.Map">
        SELECT COALESCE(sum(t.amt_pay), 0) as "sumAmtPay"
        FROM dkic_b.t_mac_account_item as t
        where t.flg_valid
          and t.acc_item_type = '账款类型-付款'
          and t.object_id = #{id}::uuid
    </select>

    <!-- 查询订单未出库金额  -->
    <select id="getSumAmtOrder" resultType="java.util.Map">
        SELECT COALESCE(sum(tpo.sum_amount - tpo.out_amt), 0) as "sumAmtOrder"
        FROM dkic_b.t_psi_order as tpo
        where tpo.flg_valid
          and tpo.out_status in ('出库状态-出库中', '出库状态-待出库')
          and tpo.cus_id = #{id}::uuid
    </select>

    <!-- 查询采购未入库金额  -->
    <select id="getSumAmtPur" resultType="java.util.Map">
        SELECT COALESCE(sum(tpp.sum_amount - tpp.into_amt), 0) as "sumAmtPur"
        FROM dkic_b.t_psi_purchase as tpp
        where tpp.flg_valid
          and tpp.into_status in ('入库状态-待入库', '入库状态-入库中')
          and tpp.sup_id = #{id}::uuid
    </select>

    <delete id="deleteById">
        DELETE
        FROM dkic_b.t_mac_account_item
        WHERE item_id = #{id}::uuid;
    </delete>
</mapper>
