<template>
    <div>
        <van-pull-refresh v-model="isLoading"
                          success-text="刷新成功"
                          @refresh="onRefresh"
                          :disabled="isRefreshDisable"
        >
        <mt-header title="人工网点申领" v-if="showNav()">
            <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-show="!noDataShow"
                    ref="mc1"
            >
                <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="flex_center">
                            <div class="item">
                                <label class="item-left">库存数量</label>
                                <label class="item-right">{{item.unit || '0'}} </label>
                            </div>
                        <!--<div class="item">
                            <label class="item-left">已申领</label>
                            <label class="item-right">{{item.received || 0}} {{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.applyNumber" > <!--@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>
                <van-dialog v-model="showForm"  show-cancel-button @confirm="confireForm" @cancel="closeForm">
                    <div style="padding: 8px">
                        <div style="font-weight: bold;padding: 7px" slot="title">输入领取人信息</div>
                       <!-- @change="changeIdCard"-->
                        <van-form  ref="pform" :show-error-message="true">
                            <van-field
                                    v-model="formData.idCard"
                                    name="idCard"
                                    class="res_input"
                                    placeholder="请输入领取人身份证号码(必填)"
                                    :rules="[
                                    { required: true, message: '请输入身份证号' },
                                    { validator: idCardValidator, message: '请输入正确的身份证号' }
                                    ]"
                            />
                            <van-field
                                    v-model="formData.residentName"
                                    name="residentName"
                                    class="res_input"
                                    placeholder="请输入领取人姓名(必填)"
                                    :rules="[{ required: true, message: '请填写姓名' }]"
                            />
                        </van-form>
                    </div>
                </van-dialog>
            </div>

        </div>
        </van-pull-refresh>
    </div>
</template>

<script>
    import {
        addManualMedicalRecord,
        addLossReport,
        getUserInfoByIdCard, getReClaimList
    } from "../utils/api";
    import NoData from './component/noData';
    import { Toast,Indicator } from 'mint-ui';
    import {receiveWay} from "../utils/dictionaries";
    import {idCardValidator} from '../utils/common'

    export default {
        components: {NoData},
        data() {
            return {
                loading: false,
                detailInfo: [],
                loadText:'加载中...',
                noDataShow: false,
                sessionInfo: {},
                routerDetail: {},
                param: {
                    pageIndex: 0,
                    pageSize: 10
                },
                dataInfo: {},
                showForm: false,
                hasError: false,
                formData:{
                    idCard: undefined,
                    residentName: undefined
                },
                isLoading: false,
                isRefreshDisable: false,
                scrollTop: 0
            }
        },
        watch: {
            scrollTop(newval) {
                if (newval> 0) {
                    this.isRefreshDisable = true
                } else {
                    this.isRefreshDisable = false
                }
            }
        },
        mounted() {
            this.$nextTick(() => {
                const list = this.$refs.mc1
                list.addEventListener('scroll', () => {
                    this.scrollTop = list.scrollTop
                })
            })
        },
        created() {
            this.routerDetail = this.$route.query
            // if (this.routerDetail.resource == 1) {
            //     this.showForm = true
            //     let AppPeople = JSON.parse(window.localStorage.getItem('AppPeople'))
            //     if (AppPeople) {
            //         this.formData.residentName = AppPeople.residentName
            //         this.formData.idCard = AppPeople.idCard
            //     }
            // } else {
            //     this.showForm = false
            // }
            // this.sessionInfo = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
        },
        methods: {
            idCardValidator,
            //刷新
            onRefresh() {
                this.isLoading = true
                this.loading = true
                this.param.pageIndex = 1
                this.getRecordInfo()
            },
            getRecordInfo(callBack) {
                let par = {
                    id: this.routerDetail.id,
                    ...this.param
                }
                getReClaimList(par).then(({data = {}}) => {
                    const {dataList = []} = data.data
                    dataList.forEach(item => {
                        item['applyNumber'] = 0
                        item['availableCopy'] = item.available
                    })
                    if (this.isLoading) { //刷新时先赋空
                        this.detailInfo = []
                    }
                    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
                    }
                    this.isLoading = false
                    // callBack && callBack()
                }).catch(res => {
                    Toast({
                        message: '系统异常，请联系客服！',
                        duration: 2000
                    });
                    this.loading = false
                }).finally(() => {
                    this.loading = false
                    this.isLoading = false
                })
            },
            loadMore() {
                this.loading = true
                this.param.pageIndex += 1
                this.getRecordInfo()
            },
            changeIdCard() {
                let result = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(this.formData.idCard)
                if (result) {
                    let par = {
                        idCard: this.formData.idCard
                    }
                    getUserInfoByIdCard(par).then(({data}) => {
                        this.formData.residentName = data.data.residentName
                    })
                }
            },
            confireForm() {
                this.$refs.pform.validate(['residentName', 'idCard']).then(() => {
                    window.localStorage.setItem('AppPeople', JSON.stringify(this.formData))
                }).catch((err) => {
                    this.showForm = true
                    console.log(err)
                })
            },
            closeForm() {
                this.$router.push({path:'/'})
            },
            delNumber(val) {
                this.detailInfo.forEach(item => {
                    if (item.id == val.id) {
                        if (item.applyNumber > 0) {
                            item.applyNumber --
                        } else {
                            item.applyNumber = 0
                        }
                    }
                })

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

                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.applyNumber = val.availableCopy - availab
                            }
                        }
                    }
                })

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

                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.applyNumber = val.availableCopy - availab
                            }
                        }
                    }
                })

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

                let ava = 0
                let availab = 0
                this.detailInfo.forEach(item => {
                    if (val.breedId == item.breedId) {
                        ava += (+item.applyNumber)
                        if (val.id != item.id) {
                            availab += (+item.applyNumber)
                        }
                    }
                })
                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.applyNumber = 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.applyNumber)
                    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].applyNumber != '' &&
                        this.detailInfo[i].applyNumber != null &&
                        typeof this.detailInfo[i].applyNumber != 'undefined' &&
                        this.detailInfo[i].applyNumber != '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.applyNumber >0) {
                    Indicator.open()
                    // let info = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
                    // const {phone = '', userId =''} = info
                    // let  res = {idCard: undefined, residentName: undefined}
                    // if (this.routerDetail.resource == 1) {
                    //     res.idCard = this.formData.idCard
                    //     res.residentName = this.formData.residentName
                    // } else {
                    //     res.idCard = this.routerDetail.idCar
                    //     res.residentName = this.routerDetail.residentName
                    // }
                    const {updated, applyNumber, id, ...others} = record
                    let par = {
                        ...others,
                        telephone : this.routerDetail.telephone,
                        idCar: this.routerDetail.idCar,
                        networkId: this.routerDetail.networkId,
                        receiveWay: receiveWay[0].id,
                        anewNumber: +record.applyNumber,
                        number: this.routerDetail.number,
                        produceDate: record.produceDate,
                        expireDate: record.expireDate,
                        residentName: this.routerDetail.residentName,
                        createDate: this.routerDetail.createDate,
                        resource: 1,
                        lossAuditStatus: 0,
                        id: this.routerDetail.id
                    }
                    console.log(JSON.stringify(par))
                    addLossReport(par).then(({data}) => {
                        if (data.code == 'SUCCESS') {
                            Indicator.close()
                            this.$notify({ type: 'success', message: '申请成功！' ,className: 'toastIndex',});
                            this.$router.push({path:"/collectRecords",query:{}});
                            // 成功通知
                        } else {
                            Indicator.close()
                            this.$notify({ type: 'danger', message: '申请失败！' , className: 'toastIndex',});
                        }
                    }).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>
<style lang="less">
    .res_input {
        input[type=text], input[type=date] {
            background: #fff;
            padding: 1.375rem 0.75rem!important;
        }
    }
</style>

<style lang="less">
    .van-pull-refresh__track {
        height: 100vh!important;
    }
</style>
