<template>
    <div>
        <mt-header title="人工网点申领">
            <div  slot="left" @click="goBack">
                <mt-button icon="back"></mt-button>
            </div>
        </mt-header>

        <div>
            <div class="flex_center top_info" >
            <div>
            <div class="netType_div"
                 :style="{background: (dataInfo.netType == 1 ? '#13C2C2': '#1890FF')}"
            >
                <span style="margin: 0 auto">{{routerDetail.netTypeName}}</span>
            </div>
            <div class="netNameTitle">{{routerDetail.netName || '未知'}}</div>
            </div>

            <div>
                <div><span class="manualPel">申领人</span></div>
                <div class="netNameTitle"><span>{{routerDetail.telephone || '未知'}}</span></div>
            </div>
            </div>

            <div class="listTitle"><span class="listTitle_span">药具申领</span></div>

            <div
                    class="list-data"
                    v-infinite-scroll="loadMore"
                    :infinite-scroll-disabled="loading"
                    infinite-scroll-distance="10"
                    v-if="!noDataShow"
            >
                <div class="content" v-for="item in detailInfo" :key="item.id">
                    <div class="title_bor">
                        <div class="title">
                            {{item.medicalName}}
                        </div>
                        <!--<div class="leftManual">
                            还可申领
                            <span style="color: #1890FF;margin: 0px 2px">{{item.available}}</span>
                            <span>{{item.unit}}</span>
                        </div>-->
                    </div>
                    <div class="details">
                        <div class="item">
                            <label class="item-left">生产厂家</label>
                            <label class="item-right">{{item.factoryName || '--'}}</label>
                        </div>
                        <div class="item">
                            <label class="item-left">类型</label>
                            <label class="item-right">{{item.breedName || '--'}}</label>
                        </div>
                        <div class="item">
                            <label class="item-left">规格</label>
                            <label class="item-right">{{item.specs || '--'}}</label>
                        </div>
                        <div class="item">
                            <label class="item-left">库存数量</label>
                            <label class="item-right">{{item.unit || '0'}} </label>
                        </div>
                        <div class="flex_center">
                        <div class="item">
                            <label class="item-left">已申领</label>
                            <label class="item-right">{{item.received}} {{item.receivedUnit}}</label>
                        </div>
                        <div class="item">
                            <div class="item-left del" @click="delSingleNumber(item)">-</div> <!--@click="delNumber(item)"-->
                            <input type="number" class="item_input" v-model="item.number" > <!--@keyup="changeNumber(item)"-->
                            <div class="item-right add" @click="addSingleNumber(item)">+</div> <!--@click="addNumber(item)"-->
                        </div>
                        </div>
                        <!--class="item-right add sub"-->
                        <div class="sub"  @click="singleSub(item)" v-log="['药具领取', '确定按钮']">申请领取</div>
                    </div>
                </div>
            </div>
            <div class="loading" v-if="loading">
                <span id="load-text">{{loadText}}</span>
            </div>
          <!--  <div class="sumi_medical" v-if="!noDataShow">
                <mt-button type="primary" style="width: 200px" @click="onSubmit">申领药具</mt-button>
            </div>-->
            <div v-if="noDataShow">
                <NoData>
                    <template v-slot:content>
                        <span>该网点暂时没有可领用的药具，请与网点管理员联系</span>
                    </template>
                </NoData>
            </div>
        </div>

    </div>
</template>

<script>
    import {
        addManualMedicalRecord,
        getManualNetworkMedical,
        addSingleManualMedicalRecord
    } from "../../utils/api";
    import NoData from '../component/noData';
    import { Toast,Indicator } from 'mint-ui';
    import {receiveWay} from "../../utils/dictionaries";

    export default {
        components: {NoData},
        data() {
            return {
                loading: false,
                detailInfo: [],
                loadText:'加载中...',
                noDataShow: false,
                sessionInfo: {},
                routerDetail: {},
                param: {
                    pageIndex: 0,
                    pageSize: 10
                },
                dataInfo: {}
            }
        },
        created() {
            this.routerDetail = this.$route.query
            // this.sessionInfo = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
        },
        methods: {
            getRecordInfo(callBack) {
                let par = {
                    relationId: this.routerDetail.id,
                    telephone: this.routerDetail.telephone,
                    ...this.param
                }
                getManualNetworkMedical(par).then(({data = {}}) => {
                    const {dataList = []} = data.data
                    dataList.forEach(item => {
                        item['number'] = 0
                        item['availableCopy'] = item.available
                    })
                    this.detailInfo = this.detailInfo.concat(dataList)
                    if (this.detailInfo.length == 0) {
                        this.noDataShow = true
                    } else {
                        this.noDataShow = false
                    }
                    if (dataList.length < this.param.pageSize) {
                        this.loadText = '暂无更多数据'
                    } else {
                        this.loading = false
                    }
                    // callBack && callBack()
                }).catch(res => {
                    Toast({
                        message: '系统异常，请联系客服！',
                        duration: 2000
                    });
                    this.loading = false
                }).finally(() => {
                    this.loading = false
                })
            },
            loadMore() {
                this.loading = true
                this.param.pageIndex += 1
                this.getRecordInfo()
            },
            delNumber(val) {
                this.detailInfo.forEach(item => {
                    if (item.id == val.id) {
                        if (item.number > 0) {
                            item.number --
                        } else {
                            item.number = 0
                        }
                    }
                })

                let ava = 0
                let availab = 0
                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        ava += (+item.number)
                        if (val.id != item.id) {
                            availab+= (+item.number)
                        }
                    }
                })

                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        item.available = val.availableCopy - ava
                        if(item.available <= 0) {
                            item.available = 0
                            if (val.id == item.id) {
                                item.number = val.availableCopy - availab
                            }
                        }
                    }
                })

            },
            delSingleNumber(val) {
                this.detailInfo.forEach(item => {
                    if (item.id == val.id) {
                        if (item.number > 0) {
                            item.number --
                        }
                    }
                })
            },
            addNumber(val) {
                this.detailInfo.forEach(item => {
                    if (item.id == val.id ) {
                        if (item.number < val.availableCopy) {
                            item.number ++
                        } else {
                            item.number = val.availableCopy
                        }
                    }
                })
                let ava = 0
                let availab = 0
                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        ava += (+item.number)
                        if (val.id != item.id) {
                            availab+= (+item.number)
                        }
                    }
                })

                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        item.available = val.availableCopy - ava
                        if(item.available <=0) {
                            item.available = 0
                            if (val.id == item.id) {
                                item.number = val.availableCopy - availab
                            }
                        }
                    }
                })

            },
            addSingleNumber(val) {
                this.detailInfo.forEach(item => {
                    if (item.id == val.id ) {
                            item.number ++
                    }
                })
            },
            changeNumber(val) {
                this.detailInfo.forEach(item => {
                    if (item.id == val.id ) {
                        if (item.number > val.availableCopy) {
                            item.number = val.availableCopy
                        }
                        if (item.number < 0) {
                            item.number = 0
                        }
                    }
                })

                let ava = 0
                let availab = 0
                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        ava += (+item.number)
                        if (val.id != item.id) {
                            availab += (+item.number)
                        }
                    }
                })
                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        item.available = val.availableCopy - ava
                        if(item.available <=0) {
                            item.available = 0
                            if (val.id == item.id) {
                                item.number = val.availableCopy - availab
                            }
                        }
                    }
                })

            },
            onSubmit() {
                let avali = 0
                let info = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
                const {phone = '', userId =''} = info
                this.detailInfo.forEach(item => {
                    avali += (+item.number)
                    item['telephone'] = phone
                    item['networkId'] = this.routerDetail.id
                    item['receiveWay'] = receiveWay[1].id
                    item['produceDate'] = item.produceDate + ' '+'00:00:00'
                    item['expireDate'] = item.expireDate + ' '+'00:00:00'

                })
                let result = []
                for (let i= 0; i< this.detailInfo.length; i++) {
                    if (this.detailInfo[i].number != '' &&
                        this.detailInfo[i].number != null &&
                        typeof this.detailInfo[i].number != 'undefined' &&
                        this.detailInfo[i].number != '0'
                    ) {
                        result.push(this.detailInfo[i])
                    }
                }
                if (avali == 0) {
                    return  Toast({
                        message: '请先输入数量！',
                        duration: 2000
                    });
                }
                let par = {
                   dataList: result
                }
                addManualMedicalRecord(par).then(({data}) => {
                    if (data.code == 'SUCCESS') {
                        this.$uweb.trackEvent('药具领取结果', '成功')
                        this.$router.push({path:"/manualSuccess",query:{info: data.data}});
                    } else {
                        this.$uweb.trackEvent('药具领取结果', '失败')
                        Toast({
                            message: `${data.msg}`,
                            duration: 2000
                        });
                    }
                })
            },
            //单条确认申领
            singleSub(record) {
                if (+record.number >0) {
                    Indicator.open()
                    // let info = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
                    // const {phone = '', userId =''} = info
                    let par = {
                        ...record,
                        phone: this.routerDetail.telephone,
                        networkId: this.routerDetail.id,
                        receiveWay: receiveWay[0].id,
                        number: +record.number,
                        produceDate: record.produceDate + ' '+'00:00:00',
                        expireDate: record.expireDate + ' '+'00:00:00',
                        residentName: this.routerDetail.residentName,
                        resource: this.routerDetail.resource
                    }
                    // console.log(JSON.stringify(par))
                    addSingleManualMedicalRecord(par).then(({data}) => {
                        if (data.code == 'SUCCESS') {
                            Indicator.close()
                            this.$router.push({path:"/manualSuccess",query:{info: data.data}});
                        } else {
                            Indicator.close()
                            Toast({
                                message: `${data.msg}`,
                                duration: 2000
                            });
                        }
                    }).catch(() => {
                        Indicator.close()
                    })
                } else {
                    Toast({
                        message: `请输入领取数量`,
                        duration: 2000
                    });
                }
            },
            goBack() {
                window.history.go(-1)
            },
        },
        beforeDestroy() {
            this.detailInfo = []
        }
    }
</script>

<style scoped lang="less">
    .content {
        width: 90%;
        margin: 20px auto 0px;
        padding: 10px;
        border: 1px solid #F3F3F3;
        border-radius: 1rem;
        box-shadow: darkgrey 0px 2px 20px -10px;
        .title {
            font-weight: bold;
            line-height: 1.5;
            font-size: 14px!important;
            padding: 0px 0px 3px 0px;
            /*width: 70%;*/

        }
        .leftManual {
            font-size: 12px;
            color: #595959;
        }
        .sub {
            background: #1bd09f;
            /*width: 70px;*/
            color: #F3F3F3!important;
            padding: 5px 10px;
            border-radius: 5px;
            text-align: center;
            margin: 10px 0px 0px 0px;
        }
    }

    .manualPel {
        color: #595959;
        font-size: 12px;
    }
    .content .title_bor {
        border-bottom: 1px solid #F3F3F3;
    }

    .content .details .item {
        line-height: 24px;
        .del {
            font-size: 26px;
            display: inline-block;
            padding: 0px 8px;
        }
        .item_input {
            width: 40px;
            background: #F5F5F5;
            border-radius: 4px;
            border: 0px;
            line-height: 24px;
            text-align: center;
        }
        .add {
            font-size: 26px;
            display: inline-block;
            /*padding: 0px 8px;*/
        }
        .sub {
          margin-left: 60px!important;
            background: #26a2ff;
            color: #F3F3F3!important;
            padding: 3px 10px;
            border-radius: 5px;
        }
    }

    .content .details .item .item-right {
        /*float: right;*/
        font-size: 12px;
        margin-left: 8px;
        color: #262626;
    }
    .content .details .item .item-left {
        color: #595959;
        font-size: 12px;
    }
    .list-data{
        /*height: calc(100% - 40px);*/
        max-height: calc(100vh - 180px);
        overflow-y: auto;
        margin-bottom: 10px;
    }
    .loading{
        height: 80px;
        width: 100%;
        text-align: center;
    }

    .listTitle {
        margin: 20px 0px 0px 12px;
        .listTitle_span {
            font-weight: 600;
            font-size: 16px;
        }
    }
    .top_info {
        border: 1px solid #F3F3F3;
        border-radius: 0px 0px 16px 16px;
        padding: 12px;
        box-shadow: darkgrey 0px 2px 20px -10px;
    }
    .netType_div {
        text-align: center;
        color: white;
        border-radius: 8px 2px;
        padding: 4px 9px;
        width: 95px;
        font-size: 10px
    }
    .netNameTitle {
        font-size: 14px!important;
        font-weight: 500;
        margin-top: 11px
    }

    .sumi_medical {
        position: fixed;
        z-index: 2;
        left: calc(50% - 100px);
        bottom: 20px;
    }
</style>
