<template>
    <div class='replenishment-start-quick fs-14'>
        <div class="plr10 bgc-fff ptb10">
            <div class="drug-item kitbox" :key="k">
                <div class="photo">
                    <img src="@/assets/images/drug_default.png" alt="">
                </div>
                <div class="box-flex-1 pl10">
                    <div class="fs-15 ellipsis_1 c-333">{{query.drugName}}</div>
                    <div class="fs-14 c-666 kitbox">
                        <div class="box-flex-1">
                            <div>当前库存量：{{query.qty}}</div>
                            <div v-if="outDetailId">未放置数量：{{query.quantity}}</div>
                        </div>
                        <div class="stepper kitbox">
                            <van-stepper v-model="num" integer min="0" max="99" />
                            <div v-if="repAll" class="text">补满</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="fs-14 pl15 ptb10 bgc-fff kitbox">
            <div class="box-flex-1 lh24">
                <span>从上往下数</span>
                <div class="color-block"></div>
                <span class="ml5 fs-12">已关闭</span>
                <div class="color-block ml10 red"></div>
                <span class="ml5 fs-12">故障</span>
            </div>
        </div>

        <div class="list-panel">
            <div class="kitbox ">
                <div class="left-list">
                    <van-sidebar v-model="activeKey">
                        <van-sidebar-item v-for="(item, i) in list" :key="i" :title="(i+1)+'层'"  />
                    </van-sidebar>
                </div>
                <div class="list box-flex-1 bgc-fff">
                    <template v-if="curItem">
                        <template v-for="(item, k) in curItem.list">
                            <div class="item" v-if="item.state!=20" :key="k">
                                <ProductItem v-longpress="()=>{gotoDetail(item)}" bussuness="quick" @onChange="onChange($event, item)" :data="item" :index="k"/>
                            </div>
                        </template>

                        <!-- <div class="item" v-for="(item, k) in curItem.list" :key="k">
                            <ProductItem v-if="item.state!=20" bussuness="quick" @onChange="onChange($event, item)" :data="item" :index="k"/>
                        </div> -->
                    </template>
                </div>
            </div>
        </div>

        <div class="bot-banner">
            <div class="kitbox">
                <div class="box-flex-1 plr5"><van-button @click="openAndCloseCargo" block plain color="#17b3ec"  type="primary" round>关闭/开启货道</van-button></div>
                <div class="box-flex-1 plr5"><van-button @click="mergeAndSplitCargo" block plain color="#17b3ec"  type="primary" round>合并/拆分货道</van-button></div>
                <div class="box-flex-1 plr5"><van-button @click="sumit" block color="#17b3ec"  type="primary"  round>完成补货({{allNum}})</van-button></div>
            </div>
        </div>
    </div>
</template>
<script>
import medicineAbinetApi from '@/api/api-medicineAbinet'
import ProductItem from '@/components/ProductItem'
export default{
    name: 'replenishmentStartQuick',
    components: {
        ProductItem
    },
    data(){
        return {
            num: 0,
            query: this.$route.query,
            selItemList: [],
            allNum: 0,
            curCargo: '',

            deviceId: this.$route.query.deviceId,
            list: [],
            activeKey: 0,
            curItem: [],
            repAll: true,
            outDetailId: this.$route.query.outDetailId || ''
        }
    },
    watch:{
        activeKey(n){
            this.curItem = ''
            this.$nextTick(()=>{
                this.curItem = this.list[n]
            })
        },
        num(n, o){
            this.repAll = false
            this.accessNum()
        }
    },
    created() {
        this.initPage()
    },
    methods:{
        $refreshData(p){
            if(p){
                var oQty = this.curCargo.cargoCapacity - this.curCargo.qty
                //1修改容量 2矫正库存 3下架药品  4更换药品
                switch(Number(p.bussiness)){
                    case 1: 
                    case 2: 
                        if(p.bussiness==1){
                            // 1修改容量
                            this.curCargo.cargoCapacity = p.data
                            if(this.curCargo.qty > this.curCargo.cargoCapacity){
                                this.curCargo.qty = this.curCargo.cargoCapacity
                            }
                        } else {
                            // 2矫正库存
                            this.curCargo.qty = p.data
                            if(this.curCargo.qty > this.curCargo.cargoCapacity){
                                this.curCargo.cargoCapacity = this.curCargo.qty
                            }
                        }
                        
                        if(this.curCargo.isActive){
                            this.allNum = this.allNum - oQty + (this.curCargo.cargoCapacity - this.curCargo.qty)
                        }
                        break;
                    case 3: 
                        // 3下架药品 
                        this.curCargo.shelfStatus = 0
                        this.curCargo.qty = 0
                        if(this.curCargo.isActive){
                            this.allNum = this.allNum - oQty + this.curCargo.cargoCapacity
                        }
                        break;
                    case 4: 
                        // 4更换药品
                        this.curItem.list.splice(this.curItem.list.indexOf(this.curCargo), 1)
                        if(this.curCargo.isActive){
                            this.allNum = this.allNum - oQty
                        }
                        break;
                }
            } else {
                this.findMediicinecabinetInventoryByDeviceId()
            }
        },
        initPage(){
            this.findMediicinecabinetInventoryByDeviceId()
        },
        findMediicinecabinetInventoryByDeviceId(){
            this.$loading('加载中..')
            let p = {
                deviceId: this.deviceId
            }
            console.log('params', p)
            medicineAbinetApi
                .findMediicinecabinetInventoryByDeviceId(p)
                .then(res=>{
                    console.log('findMediicinecabinetInventoryByDeviceId', res)
                    this.$toast.clear()
                    if(res.detailModelList && res.detailModelList.length){
                        var list = _.map(res.detailModelList, v=>{
                            var key = _.keys(v)[0]
                            return {
                                index: key,
                                list: _.filter(v[key], m=>{
                                    m.isActive = false
                                    return m.drugCode == this.query.drugCode || !m.drugCode
                                }),
                            }
                        })
                        list = _.sortBy(list, 'index')
                        this.list = list
                        this.curItem = this.list[this.activeKey]
                        console.log(list, this.curItem)
                    }
                })
                .catch(err=>{
                    console.error(err)
                })
        },
        onChange(isActive, item){
            var num = this.accessItemNum(item)
            item.isActive = isActive
            if(isActive){
                this.selItemList.push(item)
                this.allNum += num
            } else {
                this.selItemList.splice(this.selItemList.indexOf(item), 1)
                this.allNum -= num
            }
            console.log(this.curItem.list.indexOf(item))
        },
        accessItemNum(item){
            var num = 0
            if(this.repAll){
                num += item.cargoCapacity - item.qty
            } else {
                if(this.num - item.qty > 0){
                    num += (this.num - item.qty)
                }
            }
            return num
        },
        accessNum(){
            var num = 0
            this.selItemList.forEach(v=>{
                num += this.accessItemNum(v)
            })
            this.allNum = num
        },
        sumit(){
            if(!this.selItemList || !this.selItemList.length){
                this.$toast("请选择操作货道")
                return
            }
            if(!this.repAll){
                var exist = _.find(this.selItemList, v=>{
                    return v.qty > this.num
                })
                if(exist){
                    this.$dialog.alert({
                        title: '补货设置',
                        message: `补货数量不能小于当前货道库存，请重新选择数量进行补货`,
                        confirmButtonText: '我已知悉',
                    })
                    return
                }
            }
            if(this.outDetailId && this.query.quantity<this.allNum){
                this.$toast('当前补货数量超过了未放置数量，请重新设置')
                return
            }
            this.$dialog.confirm({
                title: '补货设置',
                message: `确定进行补货？`,
                confirmButtonText: '确定',
            })
            .then(() => {
                var list = _.map(this.selItemList, v=>{
                    return {
                        cargoId: v.id,
                        drugId: this.query.drugId,
                        qty: this.repAll? Number(v.cargoCapacity) : this.num
                    }
                }) 
                this.$nextTick(()=>{
                    this.$loading('保存中..')
                    let p = {
                        list: JSON.stringify({list: list}),
                        userId: this.user.id,
                        outDetailId: this.outDetailId
                    }
                    console.log('params', p)
                    medicineAbinetApi
                        .batchAddInventory(p)
                        .then(res=>{
                            this.query.qty += this.allNum
                            this.query.quantity -= this.allNum
                            if(this.query.quantity<0){
                                this.query.quantity = 0
                            }
                            this.allNum = 0
                            console.log('batchAddInventory', res)
                            this.selItemList.forEach(v=>{
                                v.isActive = false
                            })
                            this.selItemList = []
                            this.$toast({
                                message: '操作成功',
                                forbidClick: true,
                                onClose: ()=>{
                                    
                                }
                            })
                            this.setBackRefresh(true)
                            this.$refreshData()
                        })
                        .catch(err=>{
                            console.error(err)
                        })
                })

            })
            var exist = _.find(this.selItemList, v=>{
                return v.faultState == 1
            })
            // if(exist){
            //     this.$toast('所选货道存在故障货道')
            //     return
            // }

            // batchAddInventory
        },
        checkOpenOrClose(){
            return new Promise((resolve, reject)=>{
                var g = _.groupBy(this.selItemList, 'cargoState')
                if(g[1] && g[0]){
                    this.$dialog.confirm({
                        title: '货道设置',
                        message: `选中货道已包含"关闭"和"开启"货道,请选择`,
                        confirmButtonText: '全部开启',
                        cancelButtonText: '全部关闭'
                    })
                    .then(() => {
                        resolve(1)
                    })
                    .catch(()=>{
                        resolve(0)
                    })
                } else {
                    resolve(g[1]? 0 : 1)
                }
            })
        },
        openAndCloseCargo(){
            if(!this.selItemList || !this.selItemList.length){
                this.$toast('请选择要操作的货道')
                return
            }
            this.checkOpenOrClose().then(cargoState=>{
                this.$nextTick(()=>{
                    var ids = _.map(this.selItemList, v=>{
                        return v.id
                    })
                    this.$loading('保存中..')
                    let p = {
                        cargoIds: ids.join(','),//必穿		货道id，多个id，英文逗号隔开，例如   1,2 		4,5,6
                        cargoState 		//必传		1开启，0关闭
                    }
                    console.log('params', p)
                    medicineAbinetApi
                        .openAndCloseCargo(p)
                        .then(res=>{
                            console.log('openAndCloseCargo', res)
                            this.selItemList.forEach(v=>{
                                v.isActive = false
                                v.cargoState = cargoState
                            })
                            this.selItemList = []
                            this.$toast({
                                message: '操作成功',
                                forbidClick: true,
                                onClose: ()=>{
                                }
                            })
                            this.setBackRefresh(true)
                        })
                        .catch(err=>{
                            console.error(err)
                        })
                })
            })
        },
        checkMerge(){
            return new Promise((resolve, reject)=>{
                var exist = _.find(this.selItemList, v=>{
                    return !!v.drugCode
                })
                if(exist){
                    this.$toast.clear()
                    this.$dialog.confirm({
                        message: '当前合并货道存在药品，需把药品下架并取出，如您继续合并默认下架全部药品',
                        confirmButtonText: '继续合并'
                    })
                    .then(() => {
                        this.$loading('保存中..')
                        resolve(true)
                    })
                    .catch(() => {
                        resolve(false)
                    });
                    return 
                }
                resolve(true)
            })
        },
        checkSplit(){
            return new Promise((resolve, reject)=>{
                this.$toast.clear()
                this.$dialog.confirm({
                    message: '货道拆分后请取下货道上的药品',
                    confirmButtonText: '继续拆分'
                })
                .then(() => {
                    resolve(true)
                })
                .catch(() => {
                    resolve(false)
                });
            })
        },
        async mergeAndSplitCargo(){
            this.$loading('保存中..')
            var ids = []
            var g = _.groupBy(this.selItemList, 'state')
            if((g['21'] || g['20']) && g['1']){
                this.$toast.clear()
                this.$dialog.alert({
                    title: '货道设置',
                    message: `当前选中货道包含合并，您需要先手动拆分合并的货道`,
                    confirmButtonText: '我已知悉',
                })
                return
            }
            var isMerge = g['21']? false : true
            if(isMerge){
                console.log(this.selItemList, 'this.selectList')
                if(!this.selItemList.length || this.selItemList.length<2){
                    this.$toast('至少选择两个相邻的货道')
                    return
                }
                var list = _.sortBy(this.selItemList, ['layerNo', 'wayerNo'])
                var exist = _.find(list, (v, i)=>{
                    var next = list[i+1]
                    if(next){
                        if(next && v.layerNo!=next.layerNo){
                            return true
                        }
                        if(Number(v.wayerNo)+1 != Number(next.wayerNo)){
                            return true
                        }
                    }
                    return false
                })
                if(exist){
                    this.$toast('只能选择相邻的货道进行合并')
                    return 
                }
                if(!await this.checkMerge()){
                    return
                }
                ids = _.map(list, v=>{
                    return v.id
                })
            } else {
                if(!this.selItemList.length || this.selItemList.length>1 || this.selItemList[0].state!=21){
                    this.$toast('请选择一个主货道')
                    return
                }
                if(!await this.checkSplit()){
                    return
                }
                this.$loading('保存中..')
                var item = this.selItemList[0]
                ids.push(item.id)
            }
            
            var p = {
                userId: this.user.id,
                cargoIds: ids.join(','),
                isMerge
            }
            console.log(p)
            medicineAbinetApi
                .mergeAndSplitCargo(p)
                .then(res=>{
                    console.log('mergeAndSplitCargo', res)
                    if(res.status == 200){
                        this.selItemList = []
                        this.$toast('操作成功')
                        this.$refreshData()
                        this.setBackRefresh(true)
                    } 
                })
                .catch(err=>{
                    console.error(err)
                })
        },
        gotoDetail(item){
            if(item.shelfStatus==1){
                this.curCargo = item; 
                this.gotoUrl('./productDetail', {
                    id: item.id,
                    from: 'quick'
                })
            }
        }
    },
}
</script>
<style lang='scss' scoped>
.replenishment-start-quick{
    display: -webkit-box;
    -webkit-box-orient: vertical;
    height: 100vh;
    .list-panel{
        -webkit-box-flex: 1;
        position: relative;
        >.kitbox{
            height: 100%;
            width: 100%;
            position: absolute;
        }
    }
    .drug-item{
        img{
            width: 60px;
            border-radius: 5px;
        }
        .stepper{
            -webkit-box-align: end;
            position: relative;
            .text{
                position: absolute;
                background: #f2f3f5;
                width: 30px;
                text-align: center;
                left: 50%;
                transform: translateX(-50%);
                bottom: 0;
                line-height: 27px;
            }
        }
    }
    .list{
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        .item{
            margin-left: 5px;
            margin-bottom: 5px;
            height: 80px;
            .components-product-item{
                width: 90px;
            }
        }
        
    }
    .left-list, .list{
        height: 100%;
        overflow-y: auto;
    }
    .color-block{
        background: #ff9526;
        width: 10px;
        height: 10px;
        display: inline-block;
        margin-left: 20px;
        border-radius: 2px;
        &.red{
            background: #ff5e6c;
        }
    }
    .bot-banner{
        padding: 10px 5px;
        position: relative;
        bottom: 0;
        width: 100%;
        left: 0;
        background: #fff;
        z-index: 3;
        >div{
            -webkit-box-flex: 1;
            .van-button{
                padding: 0;
                font-size: 13px;
                height: 36px;
            }
        }
    }
}
</style>

<style lang="scss">
.mainNobotHasTop{
    .replenishment-start-quick{
        height: calc(100vh - 46px);
    }
}
@supports(bottom: env(safe-area-inset-bottom)){
    .replenishment-start-quick{
        .bot-banner{
            &::after{
                content: "";
                height: env(safe-area-inset-bottom);
                width: 100%;
                display: block;
            }
        }
    }
}
</style>