<?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.huiju.estateagents.mapper.TaPersonMapper">
    <select id="selectCardList" resultType="java.util.HashMap">
        SELECT
            t.person_id AS id,
            t.name,
            t.company,
            t.department,
            t.post,
            t.user_id as userId,
            t.tel AS phone,
            t.avatarurl AS avatar,
            t.photo,
            u.description as description,
            (t.person_id = #{consultant} or t.user_id = #{consultant}) as mine
        FROM
            ta_person t left join ta_user u on t.user_id = u.user_id
        LEFT JOIN ta_person_building p ON u.user_id = p.user_id
        WHERE
            t.person_type = #{personType}
        AND t.status = #{status}
        and u.status != 9
        and t.org_id = #{orgId}
        <if test="buildingId != null and buildingId != ''">
            and p.building_id = #{buildingId}
        </if>
        ORDER BY
            u.weight desc,
            t.create_date DESC
    </select>

    <select id="selectBuildingConsultants" resultType="java.util.HashMap">
        SELECT
            t.person_id AS id,
            u.user_name,
            u.org_name,
            u.department,
            u.position,
            u.phone,
            u.avatar,
            u.photo,
            u.description

        FROM
            ta_person t
        JOIN ta_person_building s USING (user_id)
        left join ta_user u on t.user_id = u.user_id
        WHERE
            s.building_id = #{buildingId}
        AND t.person_type = #{personType}
        AND t. STATUS = #{status}
        and t.org_id = #{orgId}
        and u.org_id = #{orgId}
        and u.status = 1
        ORDER BY u.weight desc,
            t.create_date DESC
    </select>

    <select id="getSalesExecutive" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
            *
        FROM
            ta_person t
        WHERE
            t.person_type = 'Sales Executive'
        AND t.status = 1
        LIMIT 1
    </select>

    <select id="getPersonByOpenId" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
            *
        FROM
            ta_person t
        WHERE
            t.mini_openid = #{openId}
        AND IFNULL(t.status, 0) &gt; -1
    </select>

    <update id="setFieldIncrement">
        UPDATE ta_person
        SET ${field} = IFNULL(${field}, 0) + #{increment}
        WHERE person_id = #{personId}
    </update>

    <update id="setPointsIncrement">
        UPDATE ta_person
        SET  points = IFNULL(points, 0) + #{increment}
        WHERE person_id = #{personId}
    </update>

    <select id="selectCustomer" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
	a.*,
	b.event as event,
	b.activity as activity,
	b.data as data,
	(select b.visit_time FROM ta_person_visit_record b where a.person_id = b.person_id ORDER BY b.visit_time desc LIMIT 1) as visitTime
FROM
	ta_person a
	LEFT JOIN ta_person_visit_record b ON a.person_id = b.person_id
WHERE
	a.person_type IS NULL
	ORDER BY create_date desc
    </select>

    <select id="getById" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
	a.*
FROM
	ta_person a
WHERE
	a.person_id = #{personId}
    </select>

    <select id="getUserProjects" resultType="java.lang.String">
        SELECT
	b.building_name
FROM
	ta_person_building a
	LEFT JOIN ta_building b ON a.building_id = b.building_id
	WHERE a.user_id = #{personId}
    </select>

    <select id="selectByIdPerson" resultType="com.huiju.estateagents.entity.TaPerson">
        select * from ta_person where mini_openid = #{openid};

    </select>

    <select id="getConsultantByName" resultType="java.lang.String">
        select person_id from ta_person where name like CONCAT('%',#{name}, '%')
    </select>

    <select id="getConsultantByTel" resultType="java.lang.String">
        select person_id from ta_person where tel = #{tel}
    </select>

    <select id="selectCardListofMine" resultType="java.util.HashMap">
        SELECT
        t.person_id AS id,
        t.name,
        t.company,
        t.department,
        t.post,
        t.user_id as userId,
        t.tel AS phone,
        t.avatarurl AS avatar,
        t.photo,
        u.description as description
        FROM
        ta_person t left join ta_user u on t.user_id = u.user_id
        WHERE
        t.person_type = #{personType}
        AND t.status = #{status}
        <if test="personIds != null">
            and t.person_id in
            <foreach collection="personIds" item="item" index="index" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        ORDER BY
        u.weight desc,
        t.create_date DESC
    </select>


    <select id="selectRecentlyCount" resultType="integer" >
        SELECT
            COUNT(1) as activity_count
        FROM
        ta_person tp
        where tp.org_id = #{org} AND
        tp.person_type IN ('customer','drift','estate agent')

        <if test="startDate != null or endDate != null">
            AND  tp.create_date BETWEEN #{startDate} and #{endDate}
        </if>
        <if test="startDate == null or endDate == null">
            AND tp.create_date BETWEEN DATE_SUB(now(),INTERVAL 7 DAY) and now()
        </if>
    </select>


    <select id="selectUserBehavior" resultType="com.huiju.estateagents.po.PersonPO">

        SELECT
            temp_date.date as date,
            temp_date.type_name as activity,
            temp.activityCount as activityCount
        FROM
        (
        SELECT
          DATE_FORMAT( DATE_SUB( now( ), INTERVAL a.rownum DAY ), '%Y-%m-%d' ) AS date, b.type_id, b.type_name
          from sequence a, td_biz_event_type b

            <trim prefix="where">
                <if test="startDate != null or endDate != null">
                    a.rownum <![CDATA[ <= ]]> datediff(#{endDate}, #{startDate})
                </if>
            </trim>

        ) AS temp_date

        LEFT JOIN (
            SELECT
                COUNT(1) as activityCount,
                tpvr.event_type,
                DATE_FORMAT( tpvr.visit_time , '%Y-%m-%d' ) as date
            FROM
              ta_person tp
            INNER JOIN ta_person_visit_record tpvr ON tp.person_id = tpvr.person_id
            where tp.org_id = #{org} AND tp.person_type IN ('customer','drift','estate agent')
            <if test="buildingId != null and buildingId != ''">
                and tpvr.building_id = #{buildingId}
            </if>
            <if test="eventType != null and eventType != ''">
                and tpvr.event_type = #{eventType}
            </if>
            <if test="event != null and event != ''">
                and tpvr.event = #{event}
            </if>
            <if test="activity != null and activity != ''">
                and tpvr.activity = #{activity}
            </if>

            GROUP BY  tpvr.event_type, DATE_FORMAT( tpvr.visit_time , '%Y-%m-%d' )
        ) AS temp ON temp_date.date = temp.date and temp_date.type_id = temp.event_type
        order by temp_date.date asc
    </select>

    <select id="selectActiveUserCount" resultType="map">
        SELECT
            temp_date.date as date,
            sum(temp.activity_count) as activity_count,
            temp.visit_time as visit_time
        FROM
        (
            SELECT
              <if test="dateType == 'day'.toString()">
                  DATE_FORMAT( DATE_SUB( now( ), INTERVAL a.rownum DAY ), '%Y-%m-%d' ) AS date
              </if>
              <if test="dateType == 'week'.toString()">
                  DATE_FORMAT( DATE_SUB( now( ), INTERVAL a.rownum WEEK ), '%Y-%m-%d' ) AS date
              </if>
              <if test="dateType == 'month'.toString()">
                  DATE_FORMAT( DATE_SUB( now( ), INTERVAL a.rownum MONTH ), '%Y-%m' ) AS date
              </if>
            FROM
              sequence a

              <trim prefix="where">
                  <if test="startDate != null or endDate != null">
                      a.rownum <![CDATA[ < ]]> datediff(#{endDate}, #{startDate})
                  </if>
                  <if test="startDate == null or endDate == null">
                      a.rownum <![CDATA[ < ]]> 7
                  </if>
              </trim>

        ) AS temp_date
        LEFT JOIN (
            SELECT
                COUNT(1) as activity_count,
                tpvr.max_visit_time AS visit_time
            FROM
               ta_person tp
             LEFT JOIN
            ( SELECT *, MAX(visit_time) as max_visit_time FROM ta_person_visit_record where org_id = #{org} GROUP BY  person_id  ) as tpvr
            ON tp.person_id = tpvr.person_id
             where tp.org_id = #{org} AND tp.person_type IN ('customer','drift','estate agent')
             GROUP BY DATE_FORMAT( tpvr.max_visit_time , '%Y-%m-%d' )
        ) AS temp ON
        <if test="dateType == 'month'.toString()">
            temp_date.date = DATE_FORMAT( temp.visit_time , '%Y-%m' ) GROUP BY temp_date.date ORDER BY temp_date.date
        </if>
        <if test="dateType == 'day'.toString()">
            temp_date.date = DATE_FORMAT( temp.visit_time , '%Y-%m-%d' ) GROUP BY temp_date.date ORDER BY temp_date.date
        </if>

    </select>

    <select id="selectNewsUserCount" resultType="map">
        SELECT
        authorization_count_table.date as date,
        ifnull(authorization_count_table.authorization_count, 0) as authorization_count,
        ifnull(user_count_table.user_count, 0) as user_count
        FROM
        (
            SELECT
            *
            FROM
            (
            SELECT
              DATE_FORMAT( DATE_SUB( now( ), INTERVAL a.rownum DAY ), '%Y-%m-%d' ) AS date
            FROM
              sequence a

                <trim prefix="where">
                    <if test="startDate != null or endDate != null">
                        a.rownum <![CDATA[ <= ]]> datediff(#{endDate}, #{startDate})
                    </if>
                </trim>


            ) AS temp_date
            LEFT JOIN (

                    SELECT
                        COUNT(1) as authorization_count,
                        tp.create_date as create_date
                    FROM
                      ta_person tp
                    where tp.person_type IN ('customer','drift','estate agent') and tp.org_id = #{orgId}
                    and tp.phone is NOT NULL
                    <if test="startDate != null or endDate != null">
                        AND tp.create_date BETWEEN #{startDate} and #{endDate}
                    </if>
                    <if test="startDate == null or endDate == null">
                         AND tp.create_date BETWEEN DATE_SUB(now(),INTERVAL 7 DAY) and now()
                    </if>
                    GROUP BY DATE_FORMAT( tp.create_date , '%Y-%m-%d' )

                ) AS temp ON temp_date.date = DATE_FORMAT( temp.create_date , '%Y-%m-%d' )

        ) as authorization_count_table
        ,
        (
          SELECT
            *
            FROM
            (
            SELECT
             DATE_FORMAT( DATE_SUB( now( ), INTERVAL a.rownum DAY ), '%Y-%m-%d' ) AS date
            FROM
              sequence a

                <trim prefix="where">
                    <if test="startDate != null or endDate != null">
                        a.rownum <![CDATA[ <= ]]> datediff(#{endDate}, #{startDate})
                    </if>
                </trim>

        ) AS temp_date
        LEFT JOIN (

                SELECT
                    COUNT(1) as user_count,
                    tp.create_date as create_date
                FROM
                 ta_person tp
                where tp.person_type IN ('customer','drift','estate agent') and tp.org_id = #{orgId}
                <if test="startDate != null or endDate != null">
                    AND tp.create_date BETWEEN #{startDate} and #{endDate}
                </if>
                <if test="startDate == null or endDate == null">
                    AND tp.create_date BETWEEN DATE_SUB(now(),INTERVAL 7 DAY) and now()
                </if>
                GROUP BY DATE_FORMAT( tp.create_date , '%Y-%m-%d' )

            ) AS temp ON temp_date.date = DATE_FORMAT( temp.create_date , '%Y-%m-%d' )

        ) as user_count_table
        where
          user_count_table.date = authorization_count_table.date
        GROUP BY date
    </select>

    <select id="selectUserSourcePie" resultType="integer">
        select count(1)
        FROM ta_person
        WHERE org_id = #{org} AND person_type IN ('customer','drift','estate agent')
        <if test="recommendPersonType != null and recommendPersonType != ''">
            and recommend_person_type = #{recommendPersonType}
        </if>
    </select>

    <select id="selectUserSourceColumnar" resultType="map">
        SELECT
        tpf.from_name as from_name,
        (
            SELECT
                COUNT(1)
            FROM ta_person tps
            LEFT JOIN td_person_from tpfs
            ON tps.from_code = tpfs.from_code
            WHERE tpfs.from_code = tpf.from_code and tps.phone is NOT NULL
            AND tps.org_id = #{org}
            and tps.person_type IN ('customer','drift','estate agent')
            <if test="startDate != null or endDate != null">
                and tps.create_date BETWEEN #{startDate} and #{endDate}
            </if>
            <if test="startDate == null or endDate == null">
                and tps.create_date BETWEEN DATE_SUB( tps.create_date, INTERVAL 7 DAY ) and now()
            </if>
        ) as registered,
        (
            SELECT
                COUNT(1)
            FROM ta_person tps
            LEFT JOIN td_person_from tpfs
            ON tps.from_code = tpfs.from_code
            WHERE tpfs.from_code = tpf.from_code
            AND tps.org_id = #{org}
            and tps.person_type IN ('customer','drift','estate agent')
            <if test="startDate != null or endDate != null">
                and tps.create_date BETWEEN #{startDate} and #{endDate}
            </if>
            <if test="startDate == null or endDate == null">
                and tps.create_date BETWEEN DATE_SUB( tps.create_date, INTERVAL 7 DAY ) and now()
            </if>
        ) as user_count

        FROM td_person_from tpf
        LEFT JOIN ta_person tp
        ON tp.from_code = tpf.from_code
        where tp.org_id = #{org} AND tp.person_type IN ('customer','drift','estate agent')
        GROUP BY tpf.from_code
    </select>

    <select id="selectUserSourceData" resultType="map">

        select
            temp_date.date AS date,
            temp_date.from_name as from_name,
            temp_date.from_code as from_code,
            IFNULL(user_count.count, 0) as count,
            IFNULL(registered_count.count,0) as registered,
            user_count.create_date as create_date
        FROM
        (
            SELECT
            DATE_FORMAT( DATE_SUB( <if test="endDate != null">#{endDate}</if><if test="endDate == null">now()</if>, INTERVAL a.rownum DAY ), '%Y-%m-%d' ) AS date,
            tempf.from_name as from_name,
            tempf.from_code as from_code
            FROM
            sequence a
            ,
            td_person_from tempf

                <trim prefix="where">
                    <if test="startDate != null or endDate != null">
                        a.rownum <![CDATA[ <= ]]> datediff(#{endDate}, #{startDate})
                    </if>
                </trim>

        ) AS temp_date

        LEFT JOIN
        (
            SELECT
                ifnull(COUNT(1), 0) as count,
                DATE_FORMAT( tps.create_date, '%Y-%m-%d' ) as create_date,
                tpfs.from_code as from_code,
                tpfs.from_name as from_name
            FROM ta_person tps
            LEFT JOIN td_person_from tpfs
            ON tps.from_code = tpfs.from_code
            WHERE tpfs.from_code = tps.from_code
            AND tps.org_id = #{org}
            and tps.person_type IN ('customer','drift','estate agent')
            AND tps.create_date BETWEEN #{startDate} AND #{endDate}

            GROUP BY tpfs.from_code, DATE_FORMAT( tps.create_date, '%Y-%m-%d' )
        ) as user_count
        ON DATE_FORMAT(user_count.create_date,'%Y-%m-%d') =  temp_date.date and temp_date.from_code = user_count.from_code
        LEFT JOIN
        (
            SELECT
                ifnull(COUNT(1), 0) as count,
                DATE_FORMAT( tps.create_date, '%Y-%m-%d' ) as create_date,
                tpfs.from_code as from_code,
                tpfs.from_name as from_name
            FROM ta_person tps
            LEFT JOIN td_person_from tpfs
            ON tps.from_code = tpfs.from_code
            WHERE tpfs.from_code = tps.from_code
                AND tps.org_id = #{org}
                and tps.person_type IN ('customer','drift','estate agent')
                AND tps.create_date BETWEEN #{startDate} AND #{endDate}
                and tps.phone is not null
            GROUP BY tpfs.from_code,DATE_FORMAT( tps.create_date, '%Y-%m-%d' )
        ) as registered_count
        ON DATE_FORMAT(user_count.create_date,'%Y-%m-%d') =  temp_date.date and temp_date.from_code = registered_count.from_code
        order by temp_date.date DESC
    </select>

    <select id="getPersonList" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
            a.*
        FROM
            ta_person a
            LEFT JOIN ta_person_building b ON a.person_id = b.person_id
            <where>
                1=1
                <if test="personType != null and personType!= ''">
                    and a.person_type = #{personType}
                </if>
                <if test="name != null and name!= ''">
                    and a.name like CONCAT('%',#{name}, '%')
                </if>
                <if test="personTags != null and personTags!= ''">
                    and a.person_tags like CONCAT('%',#{personTags}, '%')
                </if>
                <if test="phone != null and phone!= ''">
                    and a.tel = #{phone}
                </if>
                <if test="buildingId != null and buildingId!= ''">
                    and b.building_id = #{buildingId}
                </if>
                <if test="status != null">
                    and a.status = #{status}
                </if>
            </where>
            GROUP BY a.person_id
    </select>

    <select id="channelBrokerList" resultType="com.huiju.estateagents.entity.TaPerson">
        select
        p.*,
        COUNT(rc.person_id) AS recommendCount
        from ta_channel_person tch
        left join  ta_person p on  tch.person_id = p.person_id and p.person_type = 'estate agent' and tch.status = 1
        LEFT JOIN ta_recommend_customer rc ON p.person_id = rc.person_id
        <where>
        <if test="name !=null and name !=''">
            and (p.name like CONCAT('%',#{name}, '%') or p.nickname like CONCAT('%',#{name}, '%'))
        </if>
        <if test="phone !=null and phone !=''">
            and rc.phone like CONCAT('%',#{phone}, '%')
        </if>
            and p.org_id= #{orgid}
            and tch.channel_id = #{channelId}
        </where>
        GROUP BY tch.person_id
    </select>

    <select id="InviteClientsList" resultType="com.huiju.estateagents.entity.TaPerson">
        select * from ta_person WHERE recommend_agent = #{id}
    </select>

    <select id="sumPointsByOrgId" resultType="java.lang.Integer">
        select sum(points) from ta_person t where 1 = 1
        <if test="orgId">
            and t.org_id = #{orgId}
        </if>
    </select>

    <update id="upDatePersonCityToId">
           UPDATE ta_person a
        INNER JOIN (
            SELECT
                t.*, s.shortname AS province
            FROM
                td_city t
            INNER JOIN td_city s ON t.parentid = s.id
        ) b ON a.city = b.shortname
        AND a.province = b.province
        Left join ta_recommend_customer m on m.org_id = a.org_id and m.person_id = a.person_id
        set a.city = b.id, m.city = b.id
        where a.city IS NOT NULL
        and (a.city REGEXP '[^0-9.]')=1
        and a.person_id = #{personId}
    </update>

    <select id="judgeBindStatusByCondition" resultType="java.lang.Integer">
        select count(1) from ta_user a
        LEFT JOIN ta_person b on a.user_id = b.user_id
        where a.org_id = #{orgId} and b.user_id = #{userId} and a.phone = #{phone}
    </select>

    <select id="selectDriftCustomerPageList" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
           t.* ,d.scene_type,d.scene_alias
        FROM
            ta_person t
            LEFT JOIN ta_person_from_record r ON t.person_id = r.person_id AND r.is_first_time = 1 and r.org_id = #{orgId}
            left join td_wx_dict d on r.scene_id = d.scene_id
        WHERE
            t.org_id = #{orgId}
        and t.person_type = #{personEstateDrift}
        <if test="buildingId !=null and buildingId !=''">
            and t.building_id = #{buildingId}
        </if>
        <if test="sceneType !=null and sceneType !=''">
            and d.scene_type = #{sceneType}
        </if>
        order by t.create_date desc
    </select>

    <select id="selectFromNum" resultType="java.lang.Integer">
        SELECT
            count( 1 )
        FROM
        (
            SELECT
                t.from_record_id,
                t.person_id
            FROM
                ta_person_from_record t
                LEFT JOIN ta_person p ON t.share_person_id = p.person_id
                WHERE t.is_first_time = 1
            and t.org_id = #{orgId}
            <if test="personType !=null and personType !=''">
                and p.person_type = #{personType}
            </if>
                GROUP BY t.person_id) d
    </select>
    <select id="selectTodayRecentlyCount" resultType="java.lang.Integer">
        SELECT
            COUNT(1) as activity_count
        FROM
        ta_person tp
        where tp.org_id = #{orgId} AND
        tp.person_type IN ('customer','drift','estate agent')
        AND DATE_FORMAT(tp.create_date,'%Y-%m-%d') = DATE_FORMAT(#{nowDate},'%Y-%m-%d')
    </select>

    <select id="selectCityPerson" resultType="java.util.Map">
        SELECT
            a.city AS city,
            b.shortname AS NAME,
            b.lng,
            b.lat,
            a.cityCount
        FROM
            (
                SELECT
                t.*,
                count( DISTINCT t.person_id ) AS cityCount
                FROM
                ta_person_position t
                INNER JOIN ta_person s ON s.person_id = t.person_id
                WHERE
                t.org_id = #{orgId}
                GROUP BY
                t.citycode
            ) a
            INNER JOIN td_city b ON b.citycode = a.citycode
            AND b.leveltype = 2
    </select>
    <select id="getPersonBy" resultType="com.huiju.estateagents.entity.TaPerson">
        SELECT
            t.*,
            s.nickname AS share_person_name
        FROM
            ta_person t
            LEFT JOIN ta_person s ON s.org_id = t.org_id
            AND t.recommend_person = s.person_id
        WHERE
            t.org_id = #{orgId}
        <if test="name != null and '' != name">
            AND t.nickname LIKE CONCAT( '%', #{name}, '%' )
        </if>
        <if test="phone != null and '' != phone">
            AND t.phone = 123
        </if>
        <if test="recommended != null and '' != recommended">
            AND s.nickname LIKE CONCAT( '%', #{recommended}, '%' )
        </if>
            AND IFNULL( t.avatarurl, '' ) > ''
            AND t.`status` > - 1
        ORDER BY
            t.create_date DESC
    </select>

    <insert id="savePersonPosition" parameterType="com.huiju.estateagents.entity.TaPersonPositon">
        insert into ta_person_position
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="personId != null">
                person_id,
            </if>
            <if test="lon != null">
                lon,
            </if>
            <if test="lat != null">
                lat,
            </if>
            <if test="citycode != null">
                citycode,
            </if>
            <if test="country != null">
                country,
            </if>
            <if test="province != null">
                province,
            </if>
            <if test="city != null">
                city,
            </if>
            <if test="district != null">
                district,
            </if>
            <if test="address != null">
                address,
            </if>
            <if test="createTime != null">
                create_time,
            </if>
            <if test="orgId != null">
                org_id,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="personId != null">
                #{personId,jdbcType=INTEGER},
            </if>
            <if test="lon != null">
                #{lon,jdbcType=VARCHAR},
            </if>
            <if test="lat != null">
                #{lat,jdbcType=VARCHAR},
            </if>
            <if test="citycode != null">
                #{citycode},
            </if>
            <if test="country != null">
                #{country},
            </if>
            <if test="province != null">
                #{province},
            </if>
            <if test="city != null">
                #{city},
            </if>
            <if test="district != null">
                #{district},
            </if>
            <if test="address != null">
                #{address},
            </if>
            <if test="createTime != null">
                #{createTime},
            </if>
            <if test="orgId != null">
                #{orgId}
            </if>
        </trim>
    </insert>

    <update id="cancelConsulatant">
        UPDATE ta_person
        SET  person_type = 'customer', user_id = null
        WHERE person_id = #{personId}
    </update>
</mapper>
