<?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.chaozhanggui.dao.system.dao.TbPlussUserPromotionMapper">
  <resultMap id="BaseResultMap" type="com.chaozhanggui.dao.system.entity.TbPlussUserPromotion">
    <id column="user_id" jdbcType="INTEGER" property="userId" />
    <result column="type_code" jdbcType="VARCHAR" property="typeCode" />
    <result column="current_fee" jdbcType="DECIMAL" property="currentFee" />
    <result column="parent_user_id" jdbcType="VARCHAR" property="parentUserId" />
    <result column="is_extend" jdbcType="VARCHAR" property="isExtend" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
  </resultMap>
  <sql id="Base_Column_List">
    user_id, type_code, current_fee, parent_user_id, is_extend, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from tb_pluss_user_promotion
    where user_id = #{userId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from tb_pluss_user_promotion
    where user_id = #{userId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.chaozhanggui.dao.system.entity.TbPlussUserPromotion">
    insert into tb_pluss_user_promotion (user_id, type_code, current_fee, 
      parent_user_id, is_extend, create_time, 
      update_time)
    values (#{userId,jdbcType=INTEGER}, #{typeCode,jdbcType=VARCHAR}, #{currentFee,jdbcType=DECIMAL}, 
      #{parentUserId,jdbcType=VARCHAR}, #{isExtend,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, 
      #{updateTime,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.chaozhanggui.dao.system.entity.TbPlussUserPromotion">
    insert into tb_pluss_user_promotion
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userId != null">
        user_id,
      </if>
      <if test="typeCode != null">
        type_code,
      </if>
      <if test="currentFee != null">
        current_fee,
      </if>
      <if test="parentUserId != null">
        parent_user_id,
      </if>
      <if test="isExtend != null">
        is_extend,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userId != null">
        #{userId,jdbcType=INTEGER},
      </if>
      <if test="typeCode != null">
        #{typeCode,jdbcType=VARCHAR},
      </if>
      <if test="currentFee != null">
        #{currentFee,jdbcType=DECIMAL},
      </if>
      <if test="parentUserId != null">
        #{parentUserId,jdbcType=VARCHAR},
      </if>
      <if test="isExtend != null">
        #{isExtend,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.chaozhanggui.dao.system.entity.TbPlussUserPromotion" >
    update tb_pluss_user_promotion
    <set>
      <if test="typeCode != null">
        type_code = #{typeCode,jdbcType=VARCHAR},
      </if>
      <if test="currentFee != null">
        current_fee = #{currentFee,jdbcType=DECIMAL},
      </if>
      <if test="parentUserId != null">
        parent_user_id = #{parentUserId,jdbcType=VARCHAR},
      </if>
      <if test="isExtend != null">
        is_extend = #{isExtend,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        update_time = #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.chaozhanggui.dao.system.entity.TbPlussUserPromotion">
    update tb_pluss_user_promotion
    set type_code = #{typeCode,jdbcType=VARCHAR},
      current_fee = #{currentFee,jdbcType=DECIMAL},
      parent_user_id = #{parentUserId,jdbcType=VARCHAR},
      is_extend = #{isExtend,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = #{updateTime,jdbcType=TIMESTAMP}
    where user_id = #{userId,jdbcType=INTEGER}
  </update>

  <select id="selectByUserIdOrAgecyCode" resultType="java.util.Map">
    SELECT
    p.user_id AS id,
    u.loginName as agencyCode,
    u.trueName as agencyName,
    p.parent_user_id,
    pr.loginName as parentLoginName,
    pr.trueName as parentTrueName,
    p.current_fee,
    p.type_code,
    p.is_extend
    FROM
    (
    SELECT
    @ids AS _ids,
    ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
    @l := @l + 1 AS LEVEL
    FROM
    tb_pluss_user_promotion,
    ( SELECT @ids := #{userId}, @l := 0 ) b
    WHERE
    @ids IS NOT NULL
    ) ID,
    tb_pluss_user_promotion p left join tb_pluss_user_info u on p.user_id=u.id left join tb_pluss_user_info pr on p.parent_user_id=pr.id
    WHERE
    FIND_IN_SET( p.user_id, ID._ids )
    AND p.type_code=#{userType} and p.user_id!=#{userId}
    <if test="agencyCode != null and agencyCode!=''">
      and u.loginName = #{agencyCode}
    </if>

    <if test="isExtend !=null and isExtend!=''"></if>
     and (p.is_extend=1 or p.is_extend=2 or p.is_extend=0)
    ORDER BY
    user_id
    </select>


  <select id="selectMaxFeeByUserId" resultType="java.math.BigDecimal">
    select max(current_fee)  from tb_pluss_user_promotion where parent_user_id=#{userId}
  </select>

  <select id="selectByUserId" resultType="java.util.Map">
    SELECT
      t.sumConsumeFee,
      m.yestedayConsumeFee,
      p.sumfansShareMoney,
      p.yestedayShareMoney,
      p.current_fee AS currentFee
    FROM
      (
        SELECT
          sum( o.consumeFee ) AS sumConsumeFee,
          101 AS id
        FROM
          (
            SELECT
              p.user_id,
              p.current_fee,
              p.type_code,
              p.parent_user_id,
              p.is_extend
            FROM
              (
                SELECT
                  @ids AS _ids,
                  ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
              @l := @l + 1 AS LEVEL
            FROM
              tb_pluss_user_promotion,
              ( SELECT @ids := #{userId}, @l := 0 ) b
            WHERE
              @ids IS NOT NULL
          ) ID,
          tb_pluss_user_promotion p
        WHERE
          FIND_IN_SET( p.user_id, ID._ids )
        ORDER BY
          user_id
      ) d
        LEFT JOIN view_base_order o ON d.user_id = o.userId
      ) t
	LEFT JOIN (
	SELECT
		sum( IFNULL( o.consumeFee, 0 ) ) AS yestedayConsumeFee,
		101 AS id
	FROM
		(
		SELECT
			p.user_id,
			p.current_fee,
			p.type_code,
			p.parent_user_id,
			p.is_extend
		FROM
			(
			SELECT
				@ids AS _ids,
				( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
				@l := @l + 1 AS LEVEL
			FROM
				tb_pluss_user_promotion,
				( SELECT @ids := #{userId}, @l := 0 ) b
			WHERE
				@ids IS NOT NULL
			) ID,
			tb_pluss_user_promotion p
		WHERE
			FIND_IN_SET( p.user_id, ID._ids )
		ORDER BY
			user_id
		) d
		LEFT JOIN view_base_order o ON d.user_id = o.userId
	WHERE
	date_format( `o`.`createDt`, '%Y-%m-%d' ) = date_format(( curdate() - INTERVAL 0 DAY ), '%Y-%m-%d' )) m ON t.id = m.id
      JOIN ( SELECT * FROM view_merchant_profit_sum WHERE userId = #{userId} ) p
  </select>

  <select id="selectByParentUserId" resultMap="BaseResultMap">
    select * from tb_pluss_user_promotion where user_id=#{userId}
  </select>

  <select id="selectCount" resultType="java.util.Map">
    SELECT
      count( s.id ) as sumCount,
      IFNULL(sum(case s.`status` when 1 then 1 else 0 end),0) as NoSellCount,
      IFNULL(sum(case s.`status` when 2 then 1 else 0 end),0)  as sellCount,
      IFNULL(sum(case s.`status` when 3 then 1 else 0 end),0) as activityCount

    FROM
      (
        SELECT
          @ids AS _ids,
          ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
      @l := @l + 1 AS LEVEL
    FROM
      tb_pluss_user_promotion,
      ( SELECT @ids := #{userId}, @l := 0 ) b
    WHERE
      @ids IS NOT NULL
      ) ID,
      tb_pluss_user_promotion p right join view_device_stock s on p.user_id=s.userId
    WHERE
      FIND_IN_SET( p.user_id, ID._ids )
      and p.user_id!=#{userId}

  </select>

  <select id="selectMarkByUserId" resultType="java.util.Map">
    SELECT
    m.user_id AS userId,
    m.`name`,
    m.phone,
    m.`status`,
    m.remark,
    m.create_time AS createTime,
    m.update_time AS updateTime
    FROM
    tb_pluss_user_marker m
    LEFT JOIN (
    SELECT
    p.user_id
    FROM
    (
    SELECT
    @ids AS _ids,
    ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
    @l := @l + 1 AS LEVEL
    FROM
    tb_pluss_user_promotion,
    ( SELECT @ids := #{userId}, @l := 0 ) b
    WHERE
    @ids IS NOT NULL
    ) ID,
    tb_pluss_user_promotion p
    WHERE
    p.type_code = 'MC'
    AND FIND_IN_SET( p.user_id, ID._ids )
    ) d ON m.user_id = d.user_id
    where 1=1
      <if test="phone !=null and phone !=''">
        and m.phone=#{phone}
      </if>

    <if test="name !=null and name != ''">
      and m.name=#{name}
    </if>
    ORDER BY
      m.create_time,m.update_time

  </select>

  <select id="selectCountByUserId" resultType="java.lang.Integer">
    SELECT
      IFNULL(count(p.user_id),0) as sumAccount
    FROM
      (
        SELECT
          @ids AS _ids,
          ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
      @l := @l + 1 AS LEVEL
    FROM
      tb_pluss_user_promotion,
      ( SELECT @ids := #{userId}, @l := 0 ) b
    WHERE
      @ids IS NOT NULL
      ) ID,
      tb_pluss_user_promotion p
    WHERE
      p.type_code='MC' and
      FIND_IN_SET( p.user_id, ID._ids )
    ORDER BY
      p.user_id
  </select>

  <select id="selectOrderByUserIdOrAgecyCode" resultType="java.util.Map">

    SELECT
    DISTINCT s.merchantCode,
    p.user_id AS id,
    u.loginName AS agencyCode,
    a.userName AS agencyName,
    p.parent_user_id,
    pr.loginName AS parentLoginName,
    pa.userName AS parentTrueName,
    p.current_fee,
    p.type_code,
    p.is_extend,
    FORMAT( IFNULL( k.sumConsumeFee, 0 ), 2 ) AS sumConsumeFee,
    FORMAT( IFNULL( k.yestedayConsumeFee, 0 ), 2 ) AS yestedayConsumeFee
    FROM
    (
    SELECT
    @ids AS _ids,
    ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
    @l := @l + 1 AS LEVEL
    FROM
    tb_pluss_user_promotion,
    ( SELECT @ids := #{userId}, @l := 0 ) b
    WHERE
    @ids IS NOT NULL
    ) ID,
    tb_pluss_user_promotion p
    LEFT JOIN tb_pluss_user_info u ON p.user_id = u.id
    LEFT JOIN tb_pluss_user_info pr ON p.parent_user_id = pr.id
    left join tb_pluss_user_app a on p.user_id=a.userId
    left join tb_pluss_user_app pa on p.parent_user_id=pa.userId
    left join tb_pluss_merchant_channel_status s on a.merchantCode=s.merchantCode
    left join tb_pluss_merchant_base_info b on a.merchantCode=b.merchantCode
    LEFT JOIN (
    SELECT
    i.userId,
    IFNULL( sum( i.sumConsumeFee ), 0 ) AS sumConsumeFee,
    IFNULL( sum( i.yestedayConsumeFee ), 0 ) AS yestedayConsumeFee
    FROM
    view_order_info i
    GROUP BY
    i.userId
    ) k ON p.user_id = k.userId
    WHERE
    FIND_IN_SET( p.user_id, ID._ids )
    AND p.type_code = 'MC'
    AND p.user_id != #{userId}
    <if test="agencyCode != null and agencyCode!=''">
      and u.loginName = #{agencyCode}
    </if>

    <if test="merchantCode != null and merchantCode!=''">
      and a.merchantCode = #{merchantCode}
    </if>

    <if test="merchantType != null and merchantType!=''">
      and b.merchantType = #{merchantType}
    </if>

    <if test="status != null and status!=''">
      and s.`status` = #{status}
    </if>

    <if test="reqUserId != null and reqUserId!=''">
      and p.user_id = #{reqUserId}
    </if>
    <if test="phone != null and phone != ''">
      and u.phone = #{phone}
    </if>
    ORDER BY
    user_id desc

  </select>

  <select id="selectUserProByUserId" resultMap="BaseResultMap">

    SELECT
      P.user_id AS userId,
      P.type_code AS typeCode,
      P.current_fee AS currentFee,
      P.parent_user_id AS parentUserId,
      P.is_extend AS isExtend,
      P.create_time AS createTime,
      P.update_time AS updateTime,
      u.loginName
    FROM
      tb_pluss_user_promotion P
        LEFT JOIN tb_pluss_user_info u ON P.user_id = u.id
    WHERE
      P.user_id = #{userId}
  </select>

  <select id="selectUserPromotionByUserId" resultMap="BaseResultMap">

    select d.*,i.loginName from (SELECT t2.*
    FROM (
    SELECT  @supId AS _id,
    (SELECT @supId := parent_user_id FROM tb_pluss_user_promotion WHERE user_id = _id ) AS supdeptid,
    @level := @level + 1 AS lvl
    FROM  (SELECT @supId := #{orderUserId}, @level := 0) vars,
    tb_pluss_user_promotion h
    WHERE @supId != 0) t1
    JOIN (SELECT * FROM tb_pluss_user_promotion ) t2
    ON t1._id = t2.user_id
    where t2.parent_user_id=#{userId}
    ORDER BY t1.lvl DESC) d left join tb_pluss_user_info i on d.user_id=i.id

  </select>

  <select id="selectDeviceStok" resultType="java.util.Map">

    SELECT
      s.snNo,
      s.actMercName,
      o.merchantCode,
      i.phone,
      s.`status`,
      o.countId AS countSum,
      o.consumeFee,
      u.loginName
    FROM
      (
        SELECT
          @ids AS _ids,
          ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
      @l := @l + 1 AS LEVEL
    FROM
      tb_pluss_user_promotion,
      ( SELECT @ids := #{userId}, @l := 0 ) b
    WHERE
      @ids IS NOT NULL
      ) ID,
      tb_pluss_user_promotion p
      RIGHT JOIN view_device_stock s ON p.user_id = s.userId
      LEFT JOIN tb_pluss_user_info i ON p.user_id = i.id
      LEFT JOIN (
      SELECT
      count( o.id ) AS countId,
      sum( o.consumeFee ) AS consumeFee,
      b.id,
      o.merchantCode
      FROM
      tb_pluss_merchant_order o
      LEFT JOIN tb_pluss_merchant_base_info b ON o.merchantCode = b.merchantCode
      WHERE
      o.`status` = 1
      GROUP BY
      b.id,
      o.merchantCode
      ) o ON s.actMercId = o.id
      LEFT JOIN tb_pluss_user_info u ON p.parent_user_id = u.id
    WHERE
      FIND_IN_SET( p.user_id, ID._ids )
      AND p.user_id != #{userId}
    <if test="merchantCode !=null and merchantCode!=''">
      and o.merchantCode=#{merchantCode}
    </if>
  </select>

  <select id="selectPromotionByUserId" resultType="java.util.Map">

    select * from view_merchant_profit_sum where userId=#{userId}
  </select>

  <select id="selectOrdersByUserId" resultType="java.util.Map">

    SELECT
      o.orderNumber,
      o.merchantCode,
      o.consumeFee,
      o.merchantName,
      o.createDt,
      p.current_fee as currentFee,
      p.type_code as typeCode
    FROM
      view_base_order o left join tb_pluss_user_promotion p on o.userId=p.user_id
    WHERE
      o.userId =#{userId}
      <if test="orderNumber != null and orderNumber != ''">
        and o.orderNumber=#{orderNumber}
      </if>
    order by o.id desc
    </select>

  <select id="selectCountNumByUserId" resultType="java.util.Map">

    SELECT
      d.sumCountNum,
      m.countNum,
      (d.sumCountNum-m.countNum) subNum
    FROM
      (
        SELECT
          count( t.user_id ) AS sumCountNum,
          101 AS id
        FROM
          (
            SELECT
              p.user_id
            FROM
              (
                SELECT
                  @ids AS _ids,
                  ( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
              @l := @l + 1 AS LEVEL
            FROM
              tb_pluss_user_promotion,
              ( SELECT @ids := #{userId}, @l := 0 ) b
            WHERE
              @ids IS NOT NULL
          ) ID,
          tb_pluss_user_promotion p
        WHERE
          p.type_code = 'MC'
          AND FIND_IN_SET( p.user_id, ID._ids )
        ORDER BY
          p.user_id
      ) t
      ) d
	LEFT JOIN (
	SELECT
		count( d.id ) AS countNum,
		101 AS id
	FROM
		(
		SELECT
			s.*
		FROM
			tb_pluss_merchant_channel_status s
			LEFT JOIN tb_pluss_merchant_base_info b ON s.merchantCode = b.merchantCode
		WHERE
			b.userId IN (
			SELECT
				p.user_id
			FROM
				(
				SELECT
					@ids AS _ids,
					( SELECT @ids := GROUP_CONCAT( user_id ) FROM tb_pluss_user_promotion WHERE FIND_IN_SET( parent_user_id, @ids ) ) AS cids,
					@l := @l + 1 AS LEVEL
				FROM
					tb_pluss_user_promotion,
					( SELECT @ids := #{userId}, @l := 0 ) b
				WHERE
					@ids IS NOT NULL
				) ID,
				tb_pluss_user_promotion p
			WHERE
				p.type_code = 'MC'
				AND FIND_IN_SET( p.user_id, ID._ids )
			ORDER BY
				p.user_id
			)
			AND s.`status` IN ( '3', '6' )
		GROUP BY
			s.merchantCode
		) d
	) m ON d.id = m.id
  </select>
</mapper>