<?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.mst.CustomerMapper">

    <!-- 通用设置 -->
    <!-- 通用查询列 -->
    <sql id="Base_Column_List">
        cus_id, cus_code, cus_name, cus_phone, address_area, address_name, address_no, address_gcj02, address_full, contact_name, contact_phone, cus_from, channel_id, org_id, staff_id, report_staff, report_time, sale_status, remarks, follow_staffs, last_follow_staff, last_follow_id, last_follow_status, last_follow_time, follow_count, flg_valid, cp_id, op_create_time, op_create_user_id, op_update_time, op_update_user_id, op_app_code, op_timestamp, op_db_user
    </sql>



    <sql id="Base_Column_List_Response">
        tmc.cus_id, tmc.cus_code,tmc.cus_name, tmc.cus_phone, tmc.address_area, tmc.address_name, tmc.address_no,
                  tmc.address_gcj02, tmc.address_full, tmc.contact_name, tmc.contact_phone, tmc.cus_from, tmc.channel_id,
                  tmc.org_id, tmc.staff_id, tmc.report_staff, tmc.report_time, tmc.sale_status, tmc.remarks, tmc.follow_staffs,
                  tmc.last_follow_staff, tmc.last_follow_id, tmc.last_follow_status, tmc.last_follow_time, tmc.follow_count, tmc.flg_valid, tmc.cp_id
    </sql>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dk.mdm.model.pojo.mst.Customer">
        <id column="cus_id" property="cusId"/>
                <result column="cus_code" property="cusCode"/>
                <result column="cus_name" property="cusName"/>
                <result column="cus_phone" property="cusPhone"/>
                <result column="address_area" property="addressArea" typeHandler="JsonTypeHandler"/>
                <result column="address_name" property="addressName"/>
                <result column="address_no" property="addressNo"/>
                <result column="address_gcj02" property="addressGcj02" typeHandler="JsonTypeHandler"/>
                <result column="address_full" property="addressFull"/>
                <result column="contact_name" property="contactName"/>
                <result column="contact_phone" property="contactPhone"/>
                <result column="cus_from" property="cusFrom" typeHandler="UuidTypeHandler"/>
                <result column="channel_id" property="channelId" typeHandler="UuidTypeHandler"/>
                <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
                <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
                <result column="report_staff" property="reportStaff" typeHandler="UuidTypeHandler"/>
            <result column="report_time" property="reportTime" typeHandler="TimestampTypeHandler"/>
                <result column="sale_status" property="saleStatus"/>
                <result column="remarks" property="remarks"/>
                <result column="follow_staffs" property="followStaffs" typeHandler="UuidListTypeHandler"/>
                <result column="last_follow_staff" property="lastFollowStaff" typeHandler="UuidTypeHandler"/>
                <result column="last_follow_id" property="lastFollowId" typeHandler="UuidTypeHandler"/>
                <result column="last_follow_status" property="lastFollowStatus"/>
            <result column="last_follow_time" property="lastFollowTime" typeHandler="TimestampTypeHandler"/>
                <result column="follow_count" property="followCount"/>
                <result column="flg_valid" property="flgValid"/>
                <result column="cp_id" property="cpId"/>
            <result column="op_create_time" property="opCreateTime" typeHandler="TimestampTypeHandler"/>
                <result column="op_create_user_id" property="opCreateUserId" typeHandler="UuidTypeHandler"/>
            <result column="op_update_time" property="opUpdateTime" typeHandler="TimestampTypeHandler"/>
                <result column="op_update_user_id" property="opUpdateUserId" typeHandler="UuidTypeHandler"/>
                <result column="op_app_code" property="opAppCode"/>
            <result column="op_timestamp" property="opTimestamp" typeHandler="TimestampTypeHandler"/>
                <result column="op_db_user" property="opDbUser"/>
    </resultMap>

    <resultMap id="BaseResultMapResponse" type="com.dk.mdm.model.response.mst.CustomerResponse">
        <id column="cus_id" property="cusId"/>
        <result column="cus_code" property="cusCode"/>
        <result column="cus_name" property="cusName"/>
        <result column="cus_phone" property="cusPhone"/>
        <result column="address_area" property="addressArea" typeHandler="JsonTypeHandler"/>
        <result column="address_name" property="addressName"/>
        <result column="address_no" property="addressNo"/>
        <result column="address_gcj02" property="addressGcj02" typeHandler="JsonTypeHandler"/>
        <result column="address_full" property="addressFull"/>
        <result column="contact_name" property="contactName"/>
        <result column="contact_phone" property="contactPhone"/>
        <result column="cus_from" property="cusFrom" typeHandler="UuidTypeHandler"/>
        <result column="channel_id" property="channelId" typeHandler="UuidTypeHandler"/>
        <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
        <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
        <result column="report_staff" property="reportStaff" typeHandler="UuidTypeHandler"/>
        <result column="report_time" property="reportTime" typeHandler="TimestampTypeHandler"/>
        <result column="sale_status" property="saleStatus"/>
        <result column="remarks" property="remarks"/>
        <result column="follow_staffs" property="followStaffs" typeHandler="UuidListTypeHandler"/>
        <result column="last_follow_staff" property="lastFollowStaff" typeHandler="UuidTypeHandler"/>
        <result column="last_follow_id" property="lastFollowId" typeHandler="UuidTypeHandler"/>
        <result column="last_follow_status" property="lastFollowStatus"/>
        <result column="last_follow_time" property="lastFollowTime" typeHandler="TimestampTypeHandler"/>
        <result column="follow_count" property="followCount"/>
        <result column="flg_valid" property="flgValid"/>
        <result column="cp_id" property="cpId"/>
        <result column="cusFromName" property="cusFromName"/>
        <result column="channelName" property="channelName"/>
        <result column="orgName" property="orgName"/>
        <result column="staffName" property="staffName"/>
        <result column="reportStaffName" property="reportStaffName"/>
        <result column="followStaffName" property="followStaffName"/>
        <result column="lastFollowStaffName" property="lastFollowStaffName"/>
        <result column="saleStatusName" property="saleStatusName"/>
        <result column="next_follow_time" property="nextFollowTime" typeHandler="TimestampTypeHandler"/>

        <result column="follow_staff" property="followStaff"/>
        <result column="follow_staff_name" property="followStaffName"/>
        <result column="receivable_residue" property="receivableResidue"/>
        <result column="receipt_residue" property="receiptResidue"/>
        <result column="orderQuantity" property="orderQuantity"/>
        <result column="orderAmount" property="orderAmount"/>

        <result column="outboundQuantity" property="outboundQuantity"/>
        <result column="outboundAmount" property="outboundAmount"/>
        <result column="outboundNotAmount" property="outboundNotAmount"/>
        <result column="outboundNotQuantity" property="outboundNotQuantity"/>
        <result column="outboundReturnQuantity" property="outboundReturnQuantity"/>
        <result column="outboundReturnAmount" property="outboundReturnAmount"/>
    </resultMap>

    <!-- 通用条件列 -->
    <sql id="Condition">
        <where>
            <if test="cusCode != null and cusCode != ''">
                AND tmc.cus_code = #{cusCode}
            </if>
            <if test="cusName != null and cusName != ''">
                AND tmc.cus_name like concat('%', my_ex.likequery(#{cusName}) , '%')
            </if>
            <if test="cusPhone != null and cusPhone != ''">
                AND tmc.cus_phone like concat('%', my_ex.likequery(#{cusPhone}) , '%')
            </if>
            <if test="addressArea != null and addressArea != ''">
                AND tmc.address_area = #{addressArea}
            </if>
            <if test="addressName != null and addressName != ''">
                AND tmc.address_name = #{addressName}
            </if>
            <if test="addressNo != null and addressNo != ''">
                AND tmc.address_no = #{addressNo}
            </if>
            <if test="addressGcj02 != null and addressGcj02 != ''">
                AND tmc.address_gcj02 = #{addressGcj02}
            </if>
            <if test="addressFull != null and addressFull != ''">
                AND tmc.address_full = #{addressFull}
            </if>
            <if test="contactName != null and contactName != ''">
                AND tmc.contact_name like concat('%', my_ex.likequery(#{contactName}) , '%')
            </if>
            <if test="contactPhone != null and contactPhone != ''">
                AND tmc.contact_phone like concat('%', my_ex.likequery(#{contactPhone}) , '%')
            </if>
            <if test="cusFrom != null and cusFrom != ''">
                AND tmc.cus_from = #{cusFrom}::uuid
            </if>
            <if test="channelId != null and channelId != ''">
                AND tmc.channel_id = #{channelId}::uuid
            </if>
            <if test="orgId != null and orgId != ''">
                AND tmc.org_id = #{orgId}::uuid
            </if>
            <if test="staffId != null and staffId != ''">
                AND tmc.staff_id = #{staffId}::uuid
            </if>
            <if test="reportStaff != null and reportStaff != ''">
                AND tmc.report_staff = #{reportStaff}::uuid
            </if>
            <if test="reportTime != null">
                AND tmc.report_time = #{reportTime}
            </if>
            <if test="saleStatus != null and saleStatus != ''">
                AND tmc.sale_status = #{saleStatus}
            </if>
            <if test="remarks != null and remarks != ''">
                AND tmc.remarks = #{remarks}
            </if>
            <if test="followStaffs != null and followStaffs != ''">
                AND tmc.follow_staffs = #{followStaffs}::uuid
            </if>
            <if test="lastFollowStaff != null and lastFollowStaff != ''">
                AND tmc.last_follow_staff = #{lastFollowStaff}::uuid
            </if>
            <if test="lastFollowId != null and lastFollowId != ''">
                AND tmc.last_follow_id = #{lastFollowId}
            </if>
            <if test="lastFollowStatus != null and lastFollowStatus != ''">
                AND tmc.last_follow_status = #{lastFollowStatus}
            </if>
            <if test="lastFollowTime != null">
                AND tmc.last_follow_time = #{lastFollowTime}
            </if>
            <if test="followCount != null">
                AND tmc.follow_count = #{followCount}
            </if>
            <if test="flgValid != null">
                AND tmc.flg_valid = #{flgValid}
            </if>
            <if test="cpId != null">
                AND tmc.cp_id = #{cpId}
            </if>
            <if  test="searchText != null">
                AND (tmc.cus_code  like concat('%', my_ex.likequery(#{searchText}) , '%')
                OR  tmc.cus_name  like concat('%', my_ex.likequery(#{searchText}) , '%')
                OR  tmc.cus_phone like concat('%', my_ex.likequery(#{searchText}) , '%')
                OR  tmc.address_full like concat('%', my_ex.likequery(#{searchText}) , '%')
                OR  tmc.remarks like concat('%', my_ex.likequery(#{searchText}) , '%')
                )
            </if>

        </where>
    </sql>

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

    <!-- 查询表t_mst_customer，（条件查询+分页）列表 -->
    <select id="selectByCond" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_Response"/>,
        tmd.data_value  AS  "cusFromName",
        tmsc.channel_name  AS  "channelName",
        tmo.org_name  AS  "orgName",
        tms.staff_name  AS  "staffName",
        tms2.staff_name  AS  "reportStaffName",
        tdk.kind_name_i18n  ->>  #{i18n} AS "saleStatusName",
        tcf.next_follow_time,
        tma.receivable_residue,
        tma.receipt_residue
        FROM dkic_b.t_mst_customer tmc
        LEFT JOIN  ( select tccff.cus_id, max (tccff.next_follow_time)as next_follow_time from dkic_b.t_crm_cus_follow tccff group by tccff.cus_id )  tcf on tmc.cus_id = tcf.cus_id
        LEFT JOIN  dkic_b.t_mst_dictionary_data tmd  on tmd.data_id =  tmc.cus_from
        LEFT JOIN  dkic_b.t_mst_sale_channel tmsc  on tmsc.channel_id =  tmc.channel_id
        LEFT JOIN  dkic_b.t_mst_org tmo  on tmo.org_id =  tmc.org_id
        LEFT JOIN  dkic_b.t_mst_staff tms  on tms.staff_id =  tmc.staff_id
        LEFT JOIN  dkic_b.t_mst_staff tms2  on tms2.staff_id =  tmc.report_staff
        LEFT JOIN  sys.t_data_kind tdk  on tdk.kind_code =  tmc.sale_status
        LEFT JOIN  dkic_b.t_mac_account tma  on tma.object_id =  tmc.cus_id
        <include refid="Condition"/>
        order by tmc.cus_id DESC
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>

    <!-- 查询表t_mst_customer，（条件查询）个数 -->
    <select id="countByCond" resultType="Long">
        SELECT
        count(1)
        FROM dkic_b.t_mst_customer tmc

        <include refid="Condition"/>
    </select>

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



    <select id="selectByIdRespone" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_Response"/>,
        tmd.data_value AS "cusFromName",
        tmsc.channel_name AS "channelName",
        tmo.org_name AS "orgName",
        tms.staff_name AS "staffName",
        tms2.staff_name AS "reportStaffName",
        tdk.kind_name_i18n ->> #{i18n} AS "saleStatusName",
        -- tccfs.follow_staff as follow_staff,
        -- tms1.staff_name as follow_staff_name
        (SELECT COUNT(1) FROM dkic_b.t_psi_order tpo WHERE tpo.cus_id = tmc.cus_id AND tpo.cp_id = tmc.cp_id AND
        tpo.flg_valid) AS "orderQuantity",
        (SELECT sum(tpo.sum_amount) FROM dkic_b.t_psi_order tpo WHERE tpo.cus_id = tmc.cus_id AND tpo.cp_id = tmc.cp_id
        AND tpo.flg_valid) AS "orderAmount",


        (SELECT COUNT(1) FROM dkic_b.t_psi_outbound tpob WHERE tpob.cus_id = tmc.cus_id AND tpob.cp_id = tmc.cp_id AND
        tpob.flg_valid AND tpob.out_type = '出库类型-销售出库' AND tpob.out_status = '出库状态-已出库') AS
        "outboundQuantity",
        (SELECT sum(tpob.out_amt) FROM dkic_b.t_psi_outbound tpob WHERE tpob.cus_id = tmc.cus_id AND tpob.cp_id =
        tmc.cp_id AND tpob.flg_valid AND tpob.out_type = '出库类型-销售出库' AND tpob.out_status = '出库状态-已出库') AS
        "outboundAmount",


        (SELECT COUNT(1) FROM dkic_b.t_psi_order tpo WHERE tpo.cus_id = tmc.cus_id AND tpo.cp_id =
        tmc.cp_id AND tpo.flg_valid AND tpo.out_status = '出库状态-待出库' AND tpo.order_status = '订单状态-成交') AS
        "outboundNotQuantity",

        (SELECT sum(tpo.sum_amount) FROM dkic_b.t_psi_order tpo WHERE tpo.cus_id = tmc.cus_id AND tpo.cp_id =
        tmc.cp_id AND tpo.flg_valid AND tpo.out_status = '出库状态-待出库' AND tpo.order_status = '订单状态-成交') AS
        "outboundNotAmount",


        (SELECT  COUNT(1) FROM dkic_b.t_psi_outbound tpob WHERE tpob.cus_id = tmc.cus_id AND tpob.cp_id =
        tmc.cp_id AND tpob.flg_valid AND tpob.out_type = '出库类型-销退回库') AS
        "outboundReturnQuantity",

        (SELECT sum(tpob.out_amt) FROM dkic_b.t_psi_outbound tpob WHERE tpob.cus_id = tmc.cus_id AND tpob.cp_id =
        tmc.cp_id AND tpob.flg_valid AND tpob.out_type = '出库类型-销退回库') AS
        "outboundReturnAmount",

        tma.receivable_residue,
        tma.receipt_residue



        FROM dkic_b.t_mst_customer tmc
        LEFT JOIN dkic_b.t_mst_dictionary_data tmd on tmd.data_id = tmc.cus_from
        LEFT JOIN dkic_b.t_mst_sale_channel tmsc on tmsc.channel_id = tmc.channel_id
        LEFT JOIN dkic_b.t_mst_org tmo on tmo.org_id = tmc.org_id
        LEFT JOIN dkic_b.t_mst_staff tms on tms.staff_id = tmc.staff_id
        LEFT JOIN dkic_b.t_mst_staff tms2 on tms2.staff_id = tmc.report_staff
        LEFT JOIN sys.t_data_kind tdk on tdk.kind_code = tmc.sale_status
        LEFT JOIN  dkic_b.t_mac_account tma  on tma.object_id =  tmc.cus_id

        -- LEFT JOIN dkic_b.t_crm_cus_follow_staff tccfs on tccfs.follow_staff = any(tmc.follow_staffs)
        -- LEFT JOIN dkic_b.t_mst_staff tms1 on tms1.staff_id = tccfs.follow_staff
        WHERE tmc.cus_id = #{id}::uuid
    </select>

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

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

    <insert id="insertBatch">
        insert into dkic_b.t_mst_customer
        (
        <trim suffixOverrides=",">
            cus_code,
            cus_name,
            cus_phone,
            address_area,
            address_name,
            address_no,
            address_gcj02,
            address_full,
            contact_name,
            contact_phone,
            cus_from,
            channel_id,
            org_id,
            staff_id,
            report_staff,
            report_time,
            sale_status,
            remarks,
            follow_staffs,
            last_follow_staff,
            last_follow_id,
            last_follow_status,
            last_follow_time,
            follow_count,
            cp_id,
            op_app_code,
        </trim>
        )
        values
        <foreach collection="list" index="index" item="item" separator=",">
            (
            <trim suffixOverrides=",">
                #{item.cusCode},
                #{item.cusName},
                #{item.cusPhone},
                #{item.addressArea},
                #{item.addressName},
                #{item.addressNo},
                #{item.addressGcj02},
                #{item.addressFull},
                #{item.contactName},
                #{item.contactPhone},
                #{item.cusFrom}::uuid,
                #{item.channelId}::uuid,
                #{item.orgId}::uuid,
                #{item.staffId}::uuid,
                #{item.reportStaff}::uuid,
                #{item.reportTime},
                #{item.saleStatus},
                #{item.remarks},
                #{item.followStaffs},
                #{item.lastFollowStaff}::uuid,
                #{item.lastFollowId}::uuid,
                #{item.lastFollowStatus},
                #{item.lastFollowTime},
                #{item.followCount},
                #{item.cpId},
                #{item.opAppCode},
            </trim>
            )
        </foreach>
    </insert>

    <!--    查询跟进人-->
    <select id="selectFollowStaffs" resultType="Object">
        SELECT follow_staffs
        from dkic_b.t_mst_customer
        WHERE cus_id = #{id}::uuid
    </select>



    <!--    公海的客户需要把跟进人清空-->
    <update id="updateFollowStaffs">
        update dkic_b.t_mst_customer
        set
            follow_staffs = null
        where cus_id = #{id}::uuid
    </update>
</mapper>
