<?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.fjhx.stock.mapper.StockWaterMapper">

    <select id="getPickingStatistics" resultType="java.util.Map">
        select uu.id                                                    userId,
               uu.RealName                                              userName,
               if(sw.StockChangeType = 15, -sw.ChangeNum, sw.ChangeNum) changeNum,
               ifnull(m.TechnologyType, 4)                              materialType,
               m.Width                                                  materialWidth,
               ifnull(sw.Price, 0.00)                                   materialPrice
        from stock_waterdetial sw
                 inner join material m on sw.MaterialCode = m.code
                 inner join u_user uu on uu.ID = sw.OperUserId
            ${ew.customSqlSegment}
    </select>

    <select id="getPickingStockChangeTypeCount" resultType="java.util.Map">
        select sum(if(sw.StockChangeType = 15, 1, 0)) cancellingStocks,
               sum(if(sw.StockChangeType = 20, 1, 0)) exWarehouse,
               sum(if(sw.StockChangeType = 23, 1, 0)) supplementaryDelivery
        from stock_waterdetial sw
                 inner join material m on sw.MaterialCode = m.code
            ${ew.customSqlSegment}
    </select>

    <select id="getPickingPage" resultType="java.util.LinkedHashMap">
        select sw.CreatedTime                     createdTime,
               m.TechnologyType                   materialType,
               m.code                             materialCode,
               m.name                             materialName,
               m.spec                             materialSpec,
               m.StockUnitID                      materialUnit,
               sw.ChangeNum                       changeNum,
               sw.Price                           materialPrice,
               format(sw.Price * sw.ChangeNum, 2) money,
               uu.RealName                        realName
        from stock_waterdetial sw
                 inner join material m on sw.MaterialCode = m.code
                 inner join u_user uu on uu.ID = sw.OperUserId
            ${ew.customSqlSegment}
    </select>

    <select id="contractPaymentStatistics" resultType="java.util.Map">
        select ifnull(m.TechnologyType, 4)                                  materialType,
               if(pc.PurContractState = 3, pc.AdjustAmount, pc.TotalAmount) money,
               s.AccountDate                                                accountDate,
               pc.SupplierId                                                supplierId,
               s.Name                                                       supplierName
        from purchase_contract pc
                 left join material m on pc.MaterialCode = m.code
                 left join supplier s on pc.SupplierId = s.ID
            ${ew.customSqlSegment}
    </select>

    <select id="subscriptionAmountPage" resultType="java.util.LinkedHashMap">
        select s.Name            supplierName,
               pc.PurchaseBillNo purchaseBillNo,
               m.name            materialName,
               pc.PurchaseQty    purchaseQty,
               pc.Price          price,
               pc.TotalAmount    totalAmount,
               pc.AdjustAmount   adjustAmount,
               pc.ApprovalTime   approvalTime
        from purchase_contract pc
                 left join material m on pc.MaterialCode = m.code
                 left join supplier s on pc.SupplierId = s.ID
            ${ew.customSqlSegment}
    </select>

    <select id="remainingToday" resultType="java.util.Map">
        select ifnull(m.Purpose, '其他')     materialPurpose,
               ifnull(m.TechnologyType, 4) materialType,
               m.Width                     materialWidth,
               sd.Quantity                 quantity,
               sd.Price                    price
        from stock_detail sd
                 inner join material m on sd.MaterialCode = m.code
        where sd.IsDelete = 0
    </select>

    <select id="remainingTodayPage" resultType="java.util.LinkedHashMap">
        SELECT t.*,
               t2.changeNum
        FROM (
                 SELECT m.ID                                                                               AS materialId,
                        mc.NAME                                                                            AS categoryName,
                        m.NAME                                                                             AS materialName,
                        m.CODE                                                                             AS materialCode,
                        m.Width                                                                            AS materialWidth,
                        sum(sd.Quantity)                                                                   AS sum,
                        count(sd.Quantity)                                                                 AS count,
                        m.SafetyStock                                                                      AS materialSafetyStock,
                        if(a.MaterialCode is null, 1,
                           IF(a.CheckTagCount = a.TagQuantity AND a.CheckTagCount = a.HandTagCount, 1,
                              0))                                                                          AS inventoryResults,
                        ifnull(a.CheckTagCount - a.TagQuantity, 0)                                         AS correctionQuantity,
                        a.CheckTime                                                                        AS checkTime,
                        uu.RealName                                                                        AS OperUserName
                 FROM material m
                          LEFT JOIN stock_detail sd ON sd.MaterialCode = m.`code`
                          LEFT JOIN (
                     SELECT HandTagCount,
                            TagQuantity,
                            CheckTagCount,
                            MaterialCode,
                            CheckTime,
                            RecordId
                     FROM (SELECT scd.HandTagCount,
                                  scd.TagQuantity,
                                  scd.CheckTagCount,
                                  scd.MaterialCode,
                                  scd.CheckTime,
                                  scd.RecordId,
                                  row_number() over ( PARTITION BY MaterialCode ORDER BY CheckTime DESC ) AS r_index
                           FROM stock_checkrecorddetail scd
                           WHERE CheckTime IS NOT NULL) aaa
                     WHERE r_index = 1
                 ) a ON m.CODE = a.MaterialCode
                          LEFT JOIN stock_checkrecord sc ON a.RecordId = sc.ID
                          LEFT JOIN u_user uu ON uu.id = sc.OperUserId
                          LEFT JOIN material_category mc ON mc.CODE = m.CategoryCode
                     ${ew.customSqlSegment}
             ) t
                 LEFT JOIN (
            SELECT swd.materialCode,
                   sum(swd.ChangeNum) changeNum
            FROM stock_waterdetial swd
            WHERE datediff(now(), swd.CreatedTime) &lt; 30
              AND swd.StockChangeType IN (20, 23)
            GROUP BY swd.MaterialCode
        ) t2 on t2.materialCode = t.materialCode
        order by t2.changeNum desc
    </select>

    <select id="selectMaterialHouse" resultType="java.util.Map">
        select m.id               materialId,
               sh.Name            houseName,
               sum(sd.Quantity)   sum,
               count(sd.Quantity) count
        from material m
                 inner join stock_detail sd on sd.MaterialCode = m.code
                 inner join stock_house sh on sh.id = sd.StockHouseId
            ${ew.customSqlSegment}
    </select>

    <select id="selectMaterialIdByHouseId" resultType="java.lang.String">
        select distinct sd.MaterialCode
        from stock_detail sd
        where sd.IsDelete = 0
          and sd.StockHouseId = #{houseId}
    </select>

    <select id="inStockList" resultType="java.util.Map">
        select sd.MaterialCode       materialCode,
               sd.RfidCode           rfidCode,
               sd.Quantity           quantity,
               sd.CreatedTime        createTime,
               sh.Name               houseName,
               sa.Name               areaName,
               st.QuantityCheckState quantityCheckState
        from stock_detail sd
                 left join stock_house sh on sd.StockHouseId = sh.ID
                 left join stock_area sa on sd.PlaceAreaId = sa.ID
                 left join stock_tag st on sd.RfidCode = st.RfidCode
            ${ew.customSqlSegment}
    </select>

    <select id="remainingTodayList" resultType="java.util.Map">
        SELECT m.ID   materialId,
               m.Name materialName,
               m.Code materialCode
        FROM material m
                 INNER JOIN stock_detail sd ON sd.MaterialCode = m.Code
                 LEFT JOIN (
            SELECT s.HandTagCount,
                   s.TagQuantity,
                   s.CheckTagCount,
                   s.MaterialCode,
                   s.CheckTime,
                   s.RecordId
            FROM (
                     SELECT scd.HandTagCount,
                            scd.TagQuantity,
                            scd.CheckTagCount,
                            scd.MaterialCode,
                            scd.CheckTime,
                            scd.RecordId
                     FROM stock_checkrecorddetail scd
                     WHERE scd.CheckTime IS NOT NULL
                     ORDER BY scd.CheckTime DESC
                 ) s
            GROUP BY s.MaterialCode
        ) a ON m.CODE = a.MaterialCode
            ${ew.customSqlSegment}
    </select>

    <select id="receiptSequence" resultType="java.util.LinkedHashMap">
        (SELECT
        m.Code materialCode,
        m.`Name` materialName,
        m.Spec spec,
        pc.PurchaseBillNo purchaseBillNo,
        s.`Name` supplierName,
        m.StockUnitID stockUnitID,
        sio.Quantity quantity,
        swd.Price price,
        swd.CreatedTime createTime,
        sum(swd.ChangeNum) changeNum,
        sum(swd.ChangeNum * swd.Price) amount
        FROM stock_waterdetial swd
        LEFT JOIN material m ON swd.MaterialCode = m.`Code`
        LEFT JOIN stock_water sw ON swd.WaterId = sw.ID
        LEFT JOIN stock_inoutbill sio ON sw.LinkId = sio.ID
        LEFT JOIN purchase_contract pc ON sio.FromBillNo = pc.PurchaseBillNo
        LEFT JOIN supplier s ON pc.SupplierId = s.ID
        WHERE swd.IsDelete != 1
        AND (swd.CreatedTime BETWEEN #{condition.beginTime} AND #{condition.endTime})
        AND swd.StockChangeType IN (10)
        AND swd.LinkId != ''
        AND swd.LinkId IS NOT NULL
        <if test="condition.keyword neq null and condition.keyword neq '' ">
            and (
            instr(m.Code, #{condition.keyword} )>0
            or instr(m.`Name`, #{condition.keyword} )>0
            or instr(s.`Name`, #{condition.keyword} )>0
            or instr(pc.PurchaseBillNo, #{condition.keyword} )>0
            )
        </if>
        GROUP BY pc.PurchaseBillNo)
        union all
        (SELECT
        m.Code materialCode,
        m.`Name` materialName,
        m.Spec spec,
        pc.PurchaseBillNo purchaseBillNo,
        s.`Name` supplierName,
        m.StockUnitID stockUnitID,
        '' quantity,
        pc.Price price,
        asod.CreatedTime createTime,
        sum(-asod.Quantity) changeNum,
        sum(-asod.Amount) amount
        FROM apply_stockoutdetail asod
        LEFT JOIN material m ON asod.MaterialCode = m.`Code`
        LEFT JOIN supplier s ON asod.SupplierId = s.ID
        LEFT JOIN purchase_contract pc ON asod.BalancePurBillNo = pc.PurchaseBillNo
        WHERE asod.IsDelete != 1
        AND asod.BackMaterialType = 1
        AND (asod.CreatedTime BETWEEN #{condition.beginTime} AND #{condition.endTime})
        AND asod.BackMaterialProgress IN (3,4, 5, 10, 11)
        <if test="condition.keyword neq null and condition.keyword neq '' ">
            and (
            instr(m.Code, #{condition.keyword} )>0
            or instr(m.`Name`, #{condition.keyword} )>0
            or instr(s.`Name`, #{condition.keyword} )>0
            or instr(pc.PurchaseBillNo, #{condition.keyword} )>0
            )
        </if>
        GROUP BY asod.MaterialCode,
        asod.BalancePurBillNo)
    </select>

    <select id="contractPaymentList" resultType="java.util.Map">
        SELECT left(asod.CreatedTime, 10) outDate,
               asod.BalancePurBillNo,
               asod.MaterialCode,
               asot.BatchNo,
               round(asot.Quantity) AS    Quantity,
               asot.Price,
               asot.Amount,
               asot.ApplyReason
        FROM apply_stockoutdetail asod
                 LEFT JOIN apply_stockouttag asot ON asod.ID = asot.LinkBackDetailId
        WHERE asod.balancePurBillNo = #{balancePurBillNo}
    </select>

    <select id="receiptList" resultType="java.util.Map">
        SELECT ifnull(asod.BalancePurBillNo, '未关联'),
               CASE
                   asod.BalanceAcount
                   WHEN 0 THEN
                       '未冲抵'
                   WHEN 1 THEN
                       '已冲抵'
                   END              AS balanceState,
               asot.PurchaseBillNo,
               round(asot.Quantity) AS Quantity,
               asot.ApplyReason
        FROM apply_stockoutdetail asod
                 LEFT JOIN apply_stockouttag asot ON asod.ID = asot.LinkBackDetailId
        WHERE BackMaterialType = 1
          AND asot.PurchaseBillNo = #{purchaseBillNo}
          AND asod.BackMaterialProgress >= 4
    </select>

    <select id="getWater" resultType="java.util.Map">
        select m.Code        materialCode,
               m.Name        materialName,
               m.Width       width,
               swd.ChangeNum changeNum,
               swd.RfidCode  rfid
        from stock_waterdetial swd
                 left join material m on swd.MaterialCode = m.code
                 left join u_user uu on uu.ID = swd.OperUserId
                 left join acc_account aa on uu.ID = aa.ID
            ${ew.customSqlSegment}
    </select>

    <select id="getMaterialReturn" resultType="java.util.Map">
        select m.Code              materialCode,
               m.Name              materialName,
               m.Width             width,
               sbd.material_meters changeNum,
               sbd.rfid            rfid
        from stock_back sb
                 left join stock_back_details sbd on sb.id = sbd.stock_back_id
                 left join material m on sbd.material_id = m.id
            ${ew.customSqlSegment}
    </select>

    <select id="getTransferPickingList" resultType="java.util.Map">
        select m.Code       materialCode,
               m.Name       materialName,
               m.Width      width,
               std.quantity changeNum,
               uu.RealName  receiveUser,
               uu2.RealName submitUser
        from stock_transfer st
                 left join stock_transfer_details std on st.id = std.stock_transfer_id
                 left join material m on st.material_id = m.id
                 left join u_user uu on uu.ID = st.receive_user
                 left join acc_account aa on uu.ID = aa.ID

                 left join acc_account aa2 on aa2.AccountNo = st.submit_user
                 left join u_user uu2 on uu2.ID = aa2.ID
            ${ew.customSqlSegment}
    </select>

    <select id="getTransferBackList" resultType="java.util.Map">
        select m.Code       materialCode,
               m.Name       materialName,
               m.Width      width,
               std.quantity changeNum,

               uu.RealName  receiveUser,
               uu2.RealName submitUser
        from stock_transfer st
                 left join stock_transfer_details std on st.id = std.stock_transfer_id
                 left join material m on st.material_id = m.id

                 left join u_user uu on uu.ID = st.receive_user
                 left join acc_account aa on uu.ID = aa.ID

                 left join acc_account aa2 on aa2.AccountNo = st.submit_user
                 left join u_user uu2 on uu2.ID = aa2.ID
            ${ew.customSqlSegment}
    </select>
    <select id="getInventoryDetails" resultType="java.util.Map">
        SELECT scrd.ID            AS detialId,
               CASE
                   m.TechnologyType
                   WHEN 0 THEN
                       '直喷'
                   WHEN 1 THEN
                       '热转'
                   WHEN 2 THEN
                       '打纸'
                   WHEN 3 THEN
                       '墨水'
                   WHEN 4 THEN
                       '其他'
                   END            AS categoryName,
               m.Purpose             purpose,
               scrd.MaterialCode  AS materialCode,
               m.`Name`           AS materialName,
               scrd.TagQuantity   AS stockCount,
               scrd.CheckTagCount AS scanfCount,
               scrd.HandTagCount  AS handCount,
               CASE
                   scrd.TagQuantity
                   WHEN scrd.CheckTagCount THEN
                       '正常'
                   ELSE '异常'
                   END            AS result,
               scrd.CheckTime     AS checkTime,
               uu.RealName        AS checkUser
        FROM stock_checkrecorddetail scrd
                 LEFT JOIN material m ON scrd.MaterialCode = m.`Code`
                 LEFT JOIN u_user uu ON scrd.CreateUserID = uu.ID
        WHERE scrd.RecordId = #{condition.recordId}
          AND scrd.IsDelete = 0
          AND (scrd.TagQuantity != scrd.AllStockScanCount OR scrd.Quantity != scrd.AllStockScanQty)
        ORDER BY scrd.MaterialCode
    </select>

    <select id="outPage" resultType="java.util.LinkedHashMap">
        SELECT sw.ID              waterId,
               m.`Name`           materialName,
               m.`Code`           materialCode,
               uu.RealName        realName,
               sw.StockChangeType stockChangeType,
               sw.CreatedTime     createdTime,
               sw.Remark          remark
        FROM stock_water sw
                 LEFT JOIN material m ON sw.MaterialCode = m.`Code`
                 LEFT JOIN u_user uu ON sw.OperUserId = uu.ID
            ${ew.customSqlSegment}
    </select>

    <select id="outStatistics" resultType="java.util.Map">
        SELECT count(0)           count,
               sum(swd.ChangeNum) sum
        FROM stock_water sw
                 LEFT JOIN material m ON sw.MaterialCode = m.`Code`
                 LEFT JOIN u_user uu ON sw.OperUserId = uu.ID
                 LEFT JOIN stock_waterdetial swd on sw.ID = swd.WaterId
            ${ew.customSqlSegment}
    </select>


</mapper>
