<?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="cn.toesbieya.jxc.stock.mapper.StockMapper">
    <select id="search" resultType="cn.toesbieya.jxc.common.model.vo.StockSearchResult">
        select cid,
               cname,
               sum(num)         total_num,
               sum(num * price) total_price
        from biz_stock ${ew.customSqlSegment}
        group by cid
    </select>

    <select id="export" resultType="cn.toesbieya.jxc.stock.model.vo.StockExport">
        select a.cid,
               a.cname,
               a.total_num,
               a.total_price,
               b.cgddid,
               b.cgrkid,
               b.price                                            cg_price,
               from_unixtime(b.ctime / 1000, '%Y-%m-%d %H:%m:%s') ctime,
               c.num                                              rk_num,
               d.num                                              cg_num
        from (
                     select cid,
                            cname,
                            sum(num)         total_num,
                            sum(num * price) total_price
                     from biz_stock ${ew.customSqlSegment}
                     group by cid
                     ) a
                     join biz_stock b using (cid)
                     left join biz_purchase_inbound_sub c on c.cid = a.cid and c.pid = b.cgrkid
                     left join biz_purchase_order_sub d on c.cid = d.cid and d.pid = b.cgddid
        order by a.cid, b.cgddid desc, b.cgrkid desc
    </select>

    <insert id="insertBatch" parameterType="cn.toesbieya.jxc.common.model.entity.BizStock">
        insert into biz_stock (cid, cname, num, price, ctime, cgrkid, cgddid) values
        <foreach collection="list" item="item" separator=",">
            (#{item.cid,jdbcType=INTEGER}, #{item.cname,jdbcType=VARCHAR}, #{item.num,jdbcType=DECIMAL},
             #{item.price,jdbcType=DECIMAL}, #{item.ctime,jdbcType=BIGINT}, #{item.cgrkid,jdbcType=VARCHAR},
             #{item.cgddid,jdbcType=VARCHAR})
        </foreach>
    </insert>

    <update id="outbound">
        update biz_stock
        set num = num - #{num,jdbcType=DECIMAL}
        where id = #{id,jdbcType=INTEGER}
          and num <![CDATA[ >= ]]> #{num,jdbcType=DECIMAL}
    </update>
</mapper>