<?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.copy.trade.dao.PositionMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.copy.trade.entity.po.Position">
    	<result column="id" property="id" />
    	<result column="created_time" property="createdTime" />
    	<result column="updated_time" property="updatedTime" />
        <result column="customer_id" property="customerId" />
        <result column="position_id" property="positionId" />
        <result column="trader_id" property="traderId" />
        <result column="symbol" property="symbol" />
        <result column="direction" property="direction" />
        <result column="leverage" property="leverage" />
        <result column="open_price" property="openPrice" />
        <result column="total_position" property="totalPosition" />
        <result column="total_principal_amount" property="totalPrincipalAmount" />
        <result column="available_position" property="availablePosition" />
        <result column="current_position" property="currentPosition" />
        <result column="principal_amount" property="principalAmount" />
        <result column="contract_order_entrust_id" property="contractOrderEntrustId" />
        <result column="status" property="status" />
        <result column="transaction_fee" property="transactionFee" />
        <result column="open_time" property="openTime" />
        <result column="close_time" property="closeTime" />
        <result column="close_price" property="closePrice" />
        <result column="profit_and_loss" property="profitAndLoss" />
        <result column="dividend_fee" property="dividendFee" />
        <result column="is_send_close_message" property="isSendCloseMessage" />
        <!-- <result column="stopLossPrice" property="stopLossPrice" />
        <result column="stopProfitPrice" property="stopProfitPrice" /> -->
    </resultMap>
    
    <resultMap id="RiskResultMap" type="com.copy.trade.entity.dto.PositionDto">
        <result column="id" property="id" />
        <result column="position_id" property="positionId" />
        <result column="symbol" property="symbol" />
        <result column="loss_price" property="lossPrice" />
        <result column="profit_price" property="profitPrice" />
        <result column="direction" property="direction" />
        <result column="principal_amount" property="principalAmount" />
        <result column="loss_amount" property="lossAmount" />
        <result column="profit_amount" property="profitAmount" />
    </resultMap>
    <resultMap id="resultPosition" type="com.copy.trade.entity.vo.PositionVo">
            
        <result column="customerMemberId" property="customerMemberId" />
        <result column="traderMemberId" property="traderMemberId" />
        <result column="traderName" property="traderName" />
        <result column="customerName" property="customerName" />
        
    	<result column="id" property="id" />
    	<result column="created_time" property="createdTime" />
    	<result column="updated_time" property="updatedTime" />
        <result column="customer_id" property="customerId" />
        <result column="position_id" property="positionId" />
        <result column="trader_id" property="traderId" />
        <result column="symbol" property="symbol" />
        <result column="direction" property="direction" />
        <result column="leverage" property="leverage" />
        <result column="open_price" property="openPrice" />
        <result column="total_position" property="totalPosition" />
        <result column="total_principal_amount" property="totalPrincipalAmount" />
        <result column="available_position" property="availablePosition" />
        <result column="current_position" property="currentPosition" />
        <result column="principal_amount" property="principalAmount" />
        <result column="contract_order_entrust_id" property="contractOrderEntrustId" />
        <result column="status" property="status" />
        <result column="transaction_fee" property="transactionFee" />
        <result column="open_time" property="openTime" />
        <result column="close_time" property="closeTime" />
        <result column="close_price" property="closePrice" />
        <result column="profit_and_loss" property="profitAndLoss" />
        <result column="dividend_fee" property="dividendFee" />
        <result column="trader_position_id" property="traderPositionId" />

    </resultMap>
    <select id="sumPrincipalAmount" resultType="java.math.BigDecimal">
        SELECT IFNULL(SUM(p.current_position*sp.price/p.leverage),0) FROM position p LEFT JOIN symbol_price sp ON p.symbol = sp.symbol WHERE customer_id = #{customerId}  AND trader_id= #{traderId} AND (status=10 OR status=20);
    </select>
    <update id="updateAvailablePosition">
        UPDATE position SET available_position = available_position + #{volume} WHERE position_id = #{positionId}
    </update>

    <select id="followPosition" resultMap="BaseResultMap">
        SELECT p.* FROM copied_trade ct LEFT JOIN position p ON ct.contract_order_entrust_id = p.contract_order_entrust_id WHERE ct.copy_contract_order_entrust_id=#{contractOrderEntrustId} AND ct.`status`=3 AND (p.`status` = 10 or p.`status`=20);
    </select>

    <select id="followPositionByTraderPositionId" resultMap="BaseResultMap">
        SELECT * FROM position WHERE trader_position_id = #{traderPositionId} AND (status = 10 OR status = 20);
    </select>
    
    <select id="sumPositionList" resultMap="BaseResultMap">
        select * from position  WHERE customer_id = #{customerId}  AND trader_id= #{traderId} AND (status=10 OR status=20);
    </select>
    
    <select id="getTraderPosition" resultMap="BaseResultMap">
        SELECT cp.* 
        FROM position p 
		LEFT JOIN copied_trade ct ON p.contract_order_entrust_id = ct.contract_order_entrust_id
		LEFT JOIN position cp ON ct.copy_contract_order_entrust_id = cp.contract_order_entrust_id
		WHERE p.customer_id = #{customerId}  and p.contract_order_entrust_id = #{contractOrderEntrustId}
    </select>
    
    <select id="selectPositionStatusNot30All" resultMap="RiskResultMap">
  		select p.id,p.position_id,p.symbol, 
               p.open_price*(1-0.01*rc.stop_loss_percentage*if(p.direction=0,1,-1)/p.leverage) as loss_price, 
               p.open_price*(1+0.01*rc.stop_profit_percentage*if(p.direction=0,1,-1)/p.leverage) as profit_price,
               p.direction,p.principal_amount,
               p.principal_amount*(-0.01)*rc.stop_loss_percentage as  loss_amount,
               p.principal_amount*0.01*rc.stop_profit_percentage as profit_amount
		from position p
		LEFT JOIN customer_follow_symbol cfs on cfs.customer_id = p.customer_id and p.trader_id = cfs.trader_id and p.symbol = cfs.symbol
		LEFT JOIN risk_control rc on rc.id= cfs.risk_control_id
		where p.customer_id !=p.trader_id and is_send_close_message != 1 and  (p.status=10 OR p.status=20)
		and cfs.risk_control_id is not null and (rc.stop_loss_percentage is not null or rc.stop_profit_percentage is not null) order by position_id ;
    </select>

    <update id="updateCurrentPosition">
       UPDATE position SET current_position = current_position + #{volume},status = #{status},close_time=#{closeTime} WHERE position_id = #{positionId}
    </update>

    <select id="closedPositionList" resultMap="BaseResultMap">
        SELECT * from position
        <where>
            status = 30 and customer_id = trader_id
            <if test="traderId != null">
               AND customer_id = #{traderId}
            </if>
            <if test="startTime != null">
                <![CDATA[  AND close_time >= #{startTime} ]]>
            </if>
            <if test="endTime != null">
                <![CDATA[  AND close_time < #{endTime} ]]>
            </if>
        </where>
    </select>
    
    <select id="updatePositionList" resultMap="BaseResultMap">
        SELECT * from position
        <where>
            and customer_id = trader_id
            <if test="traderId != null">
               AND customer_id = #{traderId}
            </if>
            <if test="startTime != null">
                <![CDATA[  AND updated_time >= #{startTime} ]]>
            </if>
            <if test="endTime != null">
                <![CDATA[  AND updated_time < #{endTime} ]]>
            </if>
        </where>
    </select>

    <select id="sumFollowAmount" resultType="java.math.BigDecimal">
        SELECT IFNULL(SUM(total_principal_amount),0) FROM position WHERE trader_id = #{traderId} and trader_id !=customer_id
    </select>
    
    <select id="sumTotalFollowAmount" resultType="java.math.BigDecimal">
        SELECT IFNULL(SUM(total_principal_amount),0) FROM position WHERE  trader_id != customer_id
    </select>
    
    <select id="sumFollowAmountToday" resultType="java.math.BigDecimal">
        SELECT IFNULL(SUM(total_principal_amount),0) FROM position WHERE trader_id = #{traderId} and trader_id !=customer_id  <![CDATA[  AND close_time >= #{startTime} ]]>
    </select>
    <select id="page" resultMap="resultPosition">
		SELECT c1.nickname as customerName, c1.member_id as customerMemberId,
		        c2.nickname as traderName, c2.member_id as traderMemberId ,
		        p.*
		from position p  left join customer c1 on p.customer_id=c1.id left join customer c2 on p.trader_id=c2.id
        <where>
            p.customer_id &lt;&gt; p.trader_id and p.status=30
            <if test="positionForm.customerMemberId != null">
               AND c1.member_id = #{positionForm.customerMemberId}
            </if>
            <if test="positionForm.traderMemberId != null">
               AND c2.member_id = #{positionForm.traderMemberId}
            </if>
            <if test="positionForm.positionId != null">
               AND p.position_id = #{positionForm.positionId}
            </if>
            <if test="positionForm.customerName != null and positionForm.customerName !=''">
               AND c1.nickname LIKE concat('%',#{positionForm.customerName},'%')
            </if>
            <if test="positionForm.traderName != null and positionForm.traderName !=''">
               AND c2.nickname LIKE concat('%',#{positionForm.traderName},'%')
            </if>
            ORDER by p.id DESC
        </where>
    </select>
    <select id="selectDividendFee" resultType="java.math.BigDecimal">
     	select sum(dividend_fee) from position 
			<where>
                 trader_id != customer_id and status = 30 and dividend_fee is not null
            <if test="position.traderId != null">
               and trader_id = #{position.traderId}
            </if>
            <if test="position.createdTime != null">
                <![CDATA[  AND updated_time >= #{position.createdTime} ]]>
            </if>
            <if test="position.updatedTime != null">
                <![CDATA[  AND updated_time <= #{position.updatedTime} ]]>
            </if>
             <if test="position.customerId != null">
               and customer_id = #{position.customerId}
            </if>
        </where>
     </select>
    <select id="selectCommission" resultType="java.math.BigDecimal">
     	select sum(transaction_fee) from position 
			<where>
                 trader_id != customer_id and status = 30 and transaction_fee is not null
            <if test="position.traderId != null">
               and trader_id = #{position.traderId}
            </if>
            <if test="position.createdTime != null">
                <![CDATA[  AND updated_time >= #{position.createdTime} ]]>
            </if>
            <if test="position.updatedTime != null">
                <![CDATA[  AND updated_time <= #{position.updatedTime} ]]>
            </if>
             <if test="position.customerId != null">
               and customer_id = #{position.customerId}
            </if>
        </where>
     </select>
     
      <select id="selectStudentProfit" resultType="java.math.BigDecimal">
     	select sum(profit_and_loss) from position 
			<where>
                 trader_id != customer_id and status = 30 and profit_and_loss is not null
               and trader_id = #{traderId} and customer_id=#{customerId}
            </where>
     </select>
     
      <select id="getStudentPositionByTraderPositionId" resultMap="BaseResultMap">
     	select * from position 
			<where>
                 trader_id != customer_id 
               and trader_position_id = #{traderPositionId} and customer_id=#{customerId}
            </where>
            order by id desc limit 0,1
     </select>
    
</mapper>
