<!-- L1新仓位组件v0.0.2 -->
<template>
    <van-popup
        v-model="visiblePopup"
        position="bottom"
        :style="{ height: '80%' }"
        get-container="body"
        class="lj-uselocation-popup"
        @closed="handleCloseWidget"
    >
        <div class="popup_body" :class="searchState ? 'searching':''">
            <van-search
                class="search-widget"
                v-model.trim="searchKeyWord"
                :placeholder="searchPlaceholder"
                show-action
                shape="round"
                @search="handleSearchNow(false, searchKeyWord)"
            >
                <template #left-icon>
                    <div class="search-icon">
                        <van-loading v-if="searchingState" type="spinner" size="18" color="#1989fa" />
                        <i v-else class="iconfont icon-search" style="font-size: 18px; margin: auto;" @click="handleSearchNow(false, searchKeyWord)"></i>
                    </div>
                </template>
                <template #right-icon v-if="!searchState">
                    <div class="search-icon">
                        <i class="iconfont icon-iconfontscan" style="font-size: 18px; margin: auto 3px; color: #1989fa" @click="hanldeScanLocation"></i>
                    </div>
                </template>
                <template #action>
                    <div class="search-right-action">
                        <div v-if="searchState" class="search-child-btn" @click="handleCancelSearch">取消</div>
                        <div v-else class="confirm-btn search-child-btn" @click="handleConfirm">确定</div>
                    </div>
                </template>
            </van-search>

            <van-notice-bar mode="closeable" v-if="suggestStr" color="#1989fa" background="#ecf9ff" left-icon="info-o">{{ suggestStr }}</van-notice-bar>

            <div class="popup-main">
                <div class="material-widget" v-if="JSON.stringify(target) != '{}'" v-show="!searchState">
                    <slot name="material" :targetname="targetName" :targetcode="targetCode"  :title="isTypeName" :total="sumSeled">
                        <van-cell
                            class="material-cell"
                            :title="targetCode"
                            :label="targetName"
                        >
                            <template #icon>
                                <i class="iconfont icon-huowu"></i>
                            </template>
                            <template #default>
                                <div class="cell-right-part">
                                    <div class="title">{{ isTypeName }}</div>
                                    <div class="num" v-if="planqty > 0">{{ planqty | thousandSeparatorFilter }}</div>
                                </div>
                            </template>
                        </van-cell>
                    </slot>
                </div>
                <lj-uselocation-list
                    ref="uselocation"
                    :waretype="waretype"
                    :searchmodel="searchState"
                    :select-list="selectList"
                    :loca-list="isShowLocaList"
                    :finished="isFinished"
                    :datatype="datatype"
                    :selected-text="isSearchSelectedTitle"
                    :selected-right-text="isSelectRightText"
                    :canchoose-text="isCanchooseText"
                    :canchoose-right-text="isSearchSelectRightText"
                    @actionLoca="handleActionLoca"
                    @loadMore="_fnOnloadMore"
                    @change="autoComputAll"
                    @showdetail="handleClickLoca"
                >
                    <template slot="choose-right" slot-scope="data">
                        <div class="cell-right-part">
                            <template v-if="Number(waretype)">
                                <template v-if="data.item[data.dtype.numberA] != 0 || data.item[data.dtype.numberB] != 0">
                                    <div class="num">{{ data.item[data.dtype.numberA] | thousandSeparatorFilter }}</div>
                                    <div class="num_label">{{ data.item[data.dtype.numberB] | thousandSeparatorFilter }}</div>
                                </template>
                            </template>
                            <template v-else>
                                <div class="num">{{ data.item[data.dtype.numberA] | thousandSeparatorFilter }}</div>
                            </template>
                        </div>
                    </template>
                </lj-uselocation-list>
            </div>

             <lj-uselocation-detail
                v-if="detailState"
                ref="uselocationDetailWidget"
                :error="detailError"
                :title="detailKeyWord"
                :datatype="detailDatatype"
                :dataList="detail_mtrllist"
                :total="detailTotal"
                :storage="detailStorage"
                @loadMore="handleOnloadDetail(1)"
            ></lj-uselocation-detail>
        </div>
    </van-popup>
</template>

<script>
import {Popup, Search, Cell, Skeleton, Stepper, Loading, NoticeBar } from "vant";
import LjUselocationList from "./lj-uselocation-list"
import LjUselocationDetail from "./lj-uselocation-detail"

export default {
    components: {
        "van-popup": Popup,
        "van-search": Search,
        "van-cell": Cell,
        "van-skeleton": Skeleton,
        "van-stepper": Stepper,
        "van-loading": Loading,
        "van-notice-bar": NoticeBar,
        LjUselocationList,
        LjUselocationDetail
    },
    data() {
        return {
            searchKeyWord: "",
            searchKW: "", // 接口提交之用
            detailKeyWord: "", // 接口提交之用
            visiblePopup: false,
            searchState: false,
            searchingState: false, // 正在搜索
            selLoading: true, // 组件等待状态
            locaLoading: true, // 组件等待状态
            selectList: [], // 已选仓库-列表
            locaList: [], // 可选仓库-列表
            search_localist: [], // 搜索可选结果-列表
            detail_mtrllist: [], // 详情物料结果-列表
            sumSeled: 0,
            pageSize: 20, // 每页展示量
            pageIndex: 1, // 页码
            searchPageIndex: 1, // 搜索页码
            detailPageIndex: 1, // 详情页码
            selectedNow: [],
            detailState: false,
            detailTotal: 0, // 仓位存储种类数
            detailStorage: 0, // 仓位总存放量
            searchError: false, // 搜索列表错误状态
            // loadmoreError: false, // 加载更多错误状态
            detailError: false, // 详情错误状态
            // planQty: 0, // 计划出仓数
            targetValue: [], // 搜索库存条件
            actionType: 0, // 1:加，0：减
            finishState: false,
            searchFinishState: false,
        }
    },
    props: {
        /**操作类型：1：进仓，0：出仓 */
        searchPlaceholder: {
            type: String,
            default: "搜索仓位编码/仓位名称"
        },
        /**操作类型：1：进仓，0：出仓 */
        waretype: {
            type: Number/String,
            default: 1
        },
        /**已选仓库 */
        selected: {
            type: String,
            default: ""
        },
        //建议说明
        suggestStr:{
            type: String,
            default: ""
        },
        /**属性名 */
        datatype: {
            type: Object,
            default: function () {
                return {
                    code: "lcode",
                    name: "locacode",
                    numberA: "notoutqty",
                    numberB: "loca_qty",
                };
            }
        },
        /**详情属性名 */
        detailDatatype: {
            type: Object,
            default: function () {
                return {
                    propA: "mtrlcode",
                    propB: "mtrlname",
                    propC: "notoutqty",
                    propD: "unit",
                    propE: "mtrltype",
                };
            }
        },
        apiName: {
            type: String,
            default: "GetL1APPNewLocation"
        },
        detailApiName: {
            type: String,
            default: "GetL1APPNewLocationDetail"
        },
        target: {
            type: Object,
            default: function () {
                return {}
            }
        },
        targetName: {
            type: String,
            default: ""
        },
        targetCode: {
            type: String,
            default: ""
        },
        storageid: {
            type: Number,
            default: 0
        },
        locationStr: {
            type: String,
            default: ""
        },
        planqty: {
            type: Number/String,
            default: 0
        },
    },
    created() {
        this.setPostCondition();
    },
    computed:{
        isTypeName() {
            return Number(this.waretype) ? '进仓' : '出仓';
        },
        isSelectRightText() {
            if (JSON.stringify(this.target) == "{}") {
                return Number(this.waretype) ? `进仓(${this.sumSeled})` : `出仓(${this.sumSeled})`;
            }
            return Number(this.waretype) ? `存放量(${this.sumSeled})` : `出仓量(${this.sumSeled})`;
        },
        isSearchSelectRightText() {
            return Number(this.waretype) ? '已存储/全部产品' : '已存储';
        },
        isCanchooseText() {
            return this.searchState ? '搜索结果-可选仓位' : '可选仓位';
        },
        isSearchSelectedTitle() {
            if (!this.searchState) return '已选仓位(' + this.selectList.length + ')';
            let num = 0;
            for (let i = 0; i < this.selectList.length; i++) {
                if (this.selectList[i].isMatch == true) {
                    num++;
                }
            }
            return '搜索结果-已选仓位(' + num + ')'
        },
        isShowLocaList() {
            return this.searchState ? this.search_localist : this.locaList;
        },
        isFinished() {
            return this.searchState ? this.searchFinishState : this.finishState
        }
    },
    methods: {
        /**设置搜索物料条件 */
        setPostCondition() {
            this.targetValue = [];
            if (JSON.stringify(this.target) == "{}") return false;

            for (const key in this.target) {
                let obj = {};
                obj.lable = key;
                obj.value = this.target[key];
                this.targetValue.push(obj);
            }
            console.log("物料条件：==》", JSON.stringify(this.targetValue));
        },
        /**外用-开启组件-数据处理 */
        autoComputAll() {
            let sum = 0;
            for (let i = 0; i < this.selectList.length; i++) {
                sum = $lj.floatAdd(sum, this.selectList[i].value)
            }
            this.sumSeled = sum;
        },
        fnGetNewLocation(apiName, requestBody, callback, errorback) {
            let self = this;
            $lj.postLJRequest(apiName, requestBody, function(ret) {
                if (ret) {
                    callback(ret);
                }
            }, function(ret) {
                if (errorback && !errorback(ret)) return false;
            }, true)
        },
        /**打开组件，数据处理 */
        open() {
            let self = this;
            this.visiblePopup = true;

            this.selectList = [];
            this.locaList = [];
            this.selectedNow = [];
            // this.planQty = Number(this.planqty);

            if (this.locationStr != "") {

                let selList = this.locationStr.split(";");
                console.log("selList==>", JSON.stringify(selList));
                let length = selList.length;
                for (let i = 0; i < length; i++) {
                    if (selList[i] == "") continue;
                    let obj = {};
                    let val = selList[i].split(":");
                    obj[this.datatype.name] = val[0];
                    // obj[this.datatype.numberA] = Number(val[1]);
                    obj.value = Number(val[1])
                    obj.isMatch = true;
                    this.selectList.push(obj);
                    this.selectedNow.push(obj[this.datatype.name]);
                }
                /**计算总数 */
                this.autoComputAll();
            }
            // let sel_str = this.selectedNow.length ? this.selectedNow : "";
            // 打开组件，首次渲染
            let requestBody = {
                token: $lj.getStorage("token"),
                locaList: this.selectedNow,
                targetList: this.targetValue,
                storageid: this.storageid,
                keyword: "",
                pageindex: this.pageIndex,
                pagesize: this.pageSize,
                waretype: this.waretype
            };
            this.fnGetNewLocation(this.apiName, requestBody, function(ret) {
                if (ret.hasOwnProperty("selectedList") && ret.selectedList.length) {
                    // 更新已选仓位信息
                    let selList = JSON.parse(JSON.stringify(ret.selectedList));
                    for (let i = 0; i < self.selectList.length; i++) {
                        for (let j = selList.length - 1; j >= 0; j--) {
                            if (self.selectList[i][self.datatype.name] == selList[j][self.datatype.name]) {
                                self.selectList[i][self.datatype.code] = selList[j][self.datatype.code];
                                self.selectList[i][self.datatype.numberA] = selList[j][self.datatype.numberA];
                                if (self.waretype) { // 进仓
                                    self.selectList[i][self.datatype.numberB] = selList[j][self.datatype.numberB];
                                }
                                selList.splice(j, 1);
                            }
                        }
                    }
                }
                self.$refs.uselocation.selFirstDone();
                if (ret.hasOwnProperty("locaList")) {
                    // 对已存量排序,预设仓位进行升序，其他仓位降序
                    ret.locaList.sort(function sortNum(a,b) {
                        return a.ifmy ? a.notoutqty - b.notoutqty : b.notoutqty - a.notoutqty;
                    })
                    for (let i = 0; i < ret.locaList.length; i++) {
                        let obj = JSON.parse(JSON.stringify(ret.locaList[i]));
                        let name = obj[self.datatype.name]
                        obj.hasSel = false;
                        // 是否已选
                        if (self.selectedNow.indexOf(name) > -1) {
                            obj.hasSel = true;
                        }
                        // 预设仓位前置
                        obj.ifmy ? self.locaList.unshift(obj) : self.locaList.push(obj);
                    }
                    if (ret.locaList.length < self.pageSize) {
                        self.$refs.uselocation && self.$refs.uselocation.loadDone(1);
                        self.finishState = true;
                    } else {
                        self.pageIndex++;
                        self.$refs.uselocation && self.$refs.uselocation.loadDone(0);
                        self.finishState = false;
                    }
                    self.$refs.uselocation.locaFirstDone();
                }
            }, function(ret) {
                self.$refs.uselocation.selFirstDone();
                self.$refs.uselocation.locaFirstDone();
                self.$refs.uselocation.loadError();
                return true;
            });
        },
        /**取消搜索 */
        handleCancelSearch() {
            this.$refs.uselocation.selFirstLoading();
            this.$refs.uselocation.locaFirstLoading();
            setTimeout(() => {
                this.searchState = false;
                this.searchKeyWord = "";
                this.searchKW = "";
                this.searchPageIndex = 1;
    
                this.selectedNow = [];
                for (let i = 0; i < this.selectList.length; i++) {
                    if (!this.selectList[i].isMatch) {
                        this.selectList[i].isMatch = true;
                    }
                    this.selectedNow.push(this.selectList[i][this.datatype.name]);
                }
                console.log('handleCancelSearch this.selectedNow :>> ', JSON.stringify(this.selectedNow));
    
                this.$nextTick(() => {
                    this.$refs.uselocation.selFirstDone();
                    this.$refs.uselocation.locaFirstDone();
                    this.$refs.uselocation.resetState();
                })
            }, 100);
        },
        /**搜索事件 */
        handleSearchNow(isScan, keyword) {
            if (keyword == "") {
                $lj.toast("请输入仓位编码或名称，进行搜索");
                return false;
            }
            let _keyWord = $lj.matchStorageQrCode(keyword);
            this.searchKW = _keyWord;
            this.searchingState = true;
            this.searchPageIndex = 1;

            this.search_localist = [];
            let name = this.datatype.name;
            let code = this.datatype.code;

            if (isScan) {
                // 扫描-先检查缓存
                let hasInSel = undefined;
                let hasIndex = -1;
                // 是否已添加在选择列表中
                let length = this.locaList.length;
                for (let i = 0; i < length; i++) {
                    if (_keyWord == this.locaList[i][name] || _keyWord == this.locaList[i][code]) {
                        hasIndex = i;
                        hasInSel = this.locaList[i].hasSel;
                        break;
                    }
                }
                console.log("hasIndex", hasIndex);
                if (hasIndex > -1) {
                    let obj = JSON.parse(JSON.stringify(this.locaList[hasIndex]));
                    // 已在缓存中，判断添加过了没
                    if (hasInSel){
                        this._autoRefreshSelected(_keyWord);
                    } else {
                        // 已下载、但未添加，马上添加
                        this.searchState = false;
                        this.locaList[hasIndex].hasSel = true;
                        this.handleActionLoca({type:1, item: obj});
                        $lj.toast(`扫描成功，已添加${obj[name]}`, 1000, "bottom")
                    }

                    this.searchingState = false;
                    return false;
                }
                if (this.selectedNow.length) {
                    // 检测是否未缓存在locaList，但系已添加的列表
                    hasIndex = this.selectedNow.indexOf(_keyWord);
                    if (hasIndex > -1) {
                        this._autoRefreshSelected(_keyWord);
                        this.searchingState = false;
                        return false;
                    }
                }
            }

            let self = this;
            // 打开组件，首次渲染
            let requestBody = {
                token: $lj.getStorage("token"),
                locaList: "",
                targetList: this.targetValue,
                storageid: this.storageid,
                keyword: _keyWord,
                pageindex: this.searchPageIndex,
                pagesize: this.pageSize,
                waretype: this.waretype
            };
            this.fnGetNewLocation(this.apiName, requestBody, function(ret) {
                self.searchingState = false;

                if (isScan && ret.locaList.length == 1) {
                    if (self.selectedNow.indexOf(ret.locaList[0][name]) > -1) {
                        $lj.toast(`${ret.locaList[0][name]}已添加`, 1000, "bottom");
                        return false;
                    }
                    self.handleActionLoca({type:1, item:ret.locaList[0]});
                    $lj.toast(`扫描成功，已添加${ret.locaList[0][name]}`, 1000, "bottom")

                    return false;
                }
                self.searchState = true;
                self.searchKeyWord = keyword;
                self.$refs.uselocation.selFirstLoading();
                self.$refs.uselocation.locaFirstLoading();

                setTimeout(() => {
                    self.$nextTick(() => {

                        for (let i = 0; i < self.selectList.length; i++) {
                            if (self.selectList[i][name].indexOf(self.searchKW) > -1 || (self.selectList[i][code] && self.selectList[i][code].indexOf(self.searchKW) > -1)) {
                                self.selectList[i].isMatch = true;
                            } else {
                                self.selectList[i].isMatch = false;
                            }
                        }
                        for (let i = 0; i < ret.locaList.length; i++) {

                            let obj = JSON.parse(JSON.stringify(ret.locaList[i]));
                            let nameVal = obj[self.datatype.name]
                            obj.hasSel = false;
                            // 是否已选
                            if (self.selectedNow.length > 0 &&  self.selectedNow.indexOf(nameVal) > -1) {
                                obj.hasSel = true;
                            }
                            self.search_localist.push(obj);
                        }
                        if (ret.locaList.length < self.pageSize) {
                            self.$refs.uselocation.loadDone(1);
                            self.searchFinishState = true;
                        } else {
                            self.searchPageIndex++;
                            self.$refs.uselocation.loadDone(0);
                            self.searchFinishState = false;
                        }

                        if (!ret.locaList.length) {
                            self.$refs.uselocation.setEmpty();
                            return false;
                        }
                        self.$refs.uselocation.selFirstDone();
                        self.$refs.uselocation.locaFirstDone();
                    });
                }, 100);

            }, function(ret) {
                self.searchingState = false;

                self.$refs.uselocation.selFirstDone();
                self.$refs.uselocation.locaFirstDone();
                self.$refs.uselocation.loadError();
                return true;
            });
        },
        /**进入搜索状态，重置已选列表匹配状态 */
        _autoRefreshSelected(kw) {
            // 已下载，已添加
            this.searchState = true;
            this.searchKeyWord = kw;

            this.$nextTick(() => {
                for (let i = 0; i < this.selectList.length; i++) {
                    if (this.selectList[i][this.datatype.name] == kw || this.selectList[i][this.datatype.code] == kw) {
                        this.selectList[i].isMatch = true;
                    } else {
                        this.selectList[i].isMatch = false;
                    }
                }
            });
        },
        /**扫描，调用摄像头 */
        hanldeScanLocation() {
            let self = this;
            $lj.openScanner((ret) => {
                setTimeout(() => {
                    self.handleSearchNow(ret.content.trim());
                }, 200);
            })
        },
        /**关闭组件后调用 */
        handleCloseWidget() {
            this.$emit("closed");
        },
        /**确定事件-保存 */
        handleConfirm() {
            let location = [];
            let sum = 0;
            let location_str = "";
            for (let i = 0; i < this.selectList.length; i++) {
                if (this.selectList[i].value > 0) {
                    let val = this.selectList[i].value.toString();
                    if (val.indexOf(".") == -1) {
                        val += ".";
                    }
                    location.push(`${this.selectList[i][this.datatype.name]}:${val}`);
                    sum += Number(val);
                }
            }
            if (location.length) {
                location_str = location.join(";") + ";";
            } else {
                location_str = "";
            }
            this.$emit("confirm", {location_str, sum})
            this.visiblePopup = false;
        },
        /**点击添加或删除 */
        handleActionLoca({type, item}) {
            let obj;
            api.notification({
                vibrate:[50,50], 
            });
            this.actionType = type;
            if (type) {
                // add
                if (this.searchState) {
                    // 正在搜索
                    /**如果已经在数据源中，则改变显示状态 */
                    let name = item[this.datatype.name];
                    let length = this.locaList.length;
                    for (let i = 0; i < length; i++) {
                        if (name == this.locaList[i][this.datatype.name]) {
                            this.locaList[i].hasSel = true;
                            // this.$set(this.locaList[i], 'hasSel', true);
                            break;
                        }
                    }
                }
                item.hasSel = true;
                obj = JSON.parse(JSON.stringify(item));
                obj.value = 0;
                obj.isMatch = true;
                this.selectList.push(obj);
                this.selectedNow.push(obj[this.datatype.name]);
            } else {
                // del
                let name = item[this.datatype.name];
                // 改变正常状态-可选仓库状态
                for (let i = 0; i < this.locaList.length; i++) {
                    if (name == this.locaList[i][this.datatype.name]) {
                        this.locaList[i].hasSel = false;
                        break;
                    }
                }
                if (this.searchState) {
                    if (!this.search_localist.length) {
                        // 只有一个已选列表中结果时，自动按取消
                        this.handleCancelSearch();
                    } else {
                        // 正在搜索
                        // 改变搜索状态-可选仓库状态
                        for (let j = 0; j < this.search_localist.length; j++) {
                            if (name == this.search_localist[j][this.datatype.name]) {
                                this.search_localist[j].hasSel = false;
                                break;
                            }
                        }
                    }
                }
                // 删除已选仓库列表
                if (this.selectedNow.length > 0 && this.selectedNow.indexOf(item[this.datatype.name]) > -1) {
                    let delIndex = this.selectedNow.indexOf(item[this.datatype.name]);
                    this.selectList.splice(delIndex, 1);
                    this.selectedNow.splice(delIndex, 1);
                }
            }
            this.autoComputAll();
        },
        _fnOnloadMore() {
            if (this.searchState) {
                // 在搜索
                this.handleOnloadSearch();
            } else {
                this.handleOnload();
            }
        },
        /**加载更多 */
        handleOnload() {
            console.log("加载正常状态数据")
            let self = this;
            // 打开组件，首次渲染
            let requestBody = {
                token: $lj.getStorage("token"),
                locaList: "",
                targetList: this.targetValue,
                storageid: this.storageid,
                keyword: "",
                pageindex: this.pageIndex,
                pagesize: this.pageSize,
                waretype: this.waretype
            };
            this.fnGetNewLocation(this.apiName, requestBody, function(ret) {
                if (ret.hasOwnProperty("locaList")) {
                    for (let i = 0; i < ret.locaList.length; i++) {
                        let obj = JSON.parse(JSON.stringify(ret.locaList[i]));
                        let name = obj[self.datatype.name]
                        obj.hasSel = false;
                        // 是否已选
                        if (self.selectedNow.indexOf(name) > -1) {
                            obj.hasSel = true;
                        }
                        self.locaList.push(obj);
                    }
                    if (ret.locaList.length < self.pageSize) {
                        self.$refs.uselocation && self.$refs.uselocation.loadDone(1);
                        self.finishState = true;
                    } else {
                        self.pageIndex++;
                        self.$refs.uselocation && self.$refs.uselocation.loadDone(0);
                        self.finishState = false;
                    }
                }
            }, function(ret) {
                $lj.toast(ret.ErrMsg);
                self.$refs.uselocation.loadError();
                return true;
            });
        },
        /**搜索-加载更多 */
        handleOnloadSearch() {
            let self = this;
            // 打开组件，首次渲染
            let requestBody = {
                token: $lj.getStorage("token"),
                locaList: "",
                targetList: this.targetValue,
                storageid: this.storageid,
                keyword: this.searchKW,
                pageindex: this.searchPageIndex,
                pagesize: this.pageSize,
                waretype: this.waretype
            };
            this.fnGetNewLocation(this.apiName, requestBody, function(ret) {
                if (ret.hasOwnProperty("locaList")) {
                    for (let i = 0; i < ret.locaList.length; i++) {
                        let obj = JSON.parse(JSON.stringify(ret.locaList[i]));
                        let name = obj[self.datatype.name]
                        obj.hasSel = false;
                        // 是否已选
                        console.log('handleOnloadSearch self.selectedNow :>> ', JSON.stringify(self.selectedNow));
                        if (self.selectedNow.indexOf(name) > -1) {
                            obj.hasSel = true;
                        }
                        self.search_localist.push(obj);
                    }
                    if (ret.locaList.length < self.pageSize) {
                        self.$refs.uselocation && self.$refs.uselocation.loadDone(1);
                        self.searchFinishState = true;
                    } else {
                        self.searchPageIndex++;
                        self.$refs.uselocation && self.$refs.uselocation.loadDone(0);
                        self.searchFinishState = false;
                    }
                }
            }, function(ret) {
                self.$refs.uselocation && self.$refs.uselocation.loadError();
                return false;
            });
        },
        /** 查看仓位详情 */
        handleClickLoca(data) {
            this.detailState = true;
            this.detailPageIndex = 1;
            this.detailKeyWord = data[this.datatype.name];
            this.detail_mtrllist = [];
            this.detailTotal = 0;
            this.detailStorage = 0;
            this.$nextTick(() => {
                this.$refs.uselocationDetailWidget.open();

                this.handleOnloadDetail(0);
            });
        },
        /**仓位存储详情列表 */
        handleOnloadDetail(type) {
            let self = this;
            // 打开组件，首次渲染
            let requestBody = {
                token: $lj.getStorage("token"),
                storageid: this.storageid,
                locacode: this.detailKeyWord,
                pageindex: this.detailPageIndex,
                pagesize: this.pageSize,
            };
            this.fnGetNewLocation(this.detailApiName, requestBody, function(ret) {
                self.detail_mtrllist = self.detail_mtrllist.concat(ret.mtrlList);
                if (ret.mtrlList.length < self.pageSize) {
                    self.$refs.uselocationDetailWidget && self.$refs.uselocationDetailWidget.loadDone(1);
                } else {
                    self.detailPageIndex++;
                    self.$refs.uselocationDetailWidget && self.$refs.uselocationDetailWidget.loadDone(0);
                }

                if (!type) {
                    self.detailTotal = ret.sum;
                    self.detailStorage = ret.loca_qty;
                }
            }, function(ret) {
                self.$refs.uselocationDetailWidget.loadError();
                return false;
            });
        }
    },
    watch: {
        selectList: {
            handler(newVal, oldVal) {
                let obj;
                // add
                if (this.planqty > 0 && this.actionType) {
                    let sum = this.planqty;
                    this.actionType = false;

                    for (let i = 0; i < newVal.length; i++) {
                        if (newVal[i].value > 0) {
                            sum = $lj.floatSub(sum, newVal[i].value);
                        } 
                        if (i == newVal.length - 1) {
                            let num = 0;
                            if (!Number(this.waretype)) {
                                // 出仓
                                num = sum > Number(obj[this.datatype.numberA]) ? Number(obj[this.datatype.numberA]) :  sum > 0 ? sum : 0;
                            } else if (Number(this.waretype)) {
                                // 进仓
                                num = sum > Number(this.planqty) ? Number(this.planqty) :  sum > 0 ? sum : 0;
                            }
                            this.$set(newVal[i], "value", num);
                            sum = 0;
                        }
                        if (sum <= 0) break;
                    }
                    this.autoComputAll();
                }
            },
            deep: false
        }
    }
}
</script>

<style lang="less">
@import "~assets/css/lj-style-variable.less";
.lj-uselocation-popup {
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;

    .popup_body {
        background-color: #f2f2f2;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        height: 100%;

        &.searching {
            background-color: #fff;
        }
    }
    .search-widget {
        flex-shrink: 0;
        position: relative;
        display: flex;
        padding: 5px 10px;

        &::after{
            content: "";
            position: absolute;
            bottom: 0;
            left: 10px;
            right: 10px;
            border-bottom: 1px solid #ddd;
        }
        .search-icon {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }

    .suggestion{
        margin: 5px 10px;
        color: @musePrimary;
        font-size: 14px;
    }

    .popup-main {
        position: relative;
        flex: 1;
        overflow: auto;
    }
    .van-search__action {
        padding: 0;
    }
    .search-right-action {
        flex-shrink: 0;
        display: flex;
        width: 50px;
        margin: 0 5px;

        .search-child-btn {
            width: 100%;
            height: inherit;
            text-align: center;
            border-radius: 8px;

            &.confirm-btn {
                background-color: @musePrimary;
                color: #ffffff;
            }
        }
    }
    .material-widget {
        padding: 5px 10px;
        .material-cell {
            padding: 5px;
            border-radius: 8px;
            // background-color: #E6F1FF;

            .iconfont {
                padding-right: 5px;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        }
    }
    .cell-right-part {
        display: flex;
        flex-direction: column;

        .title {
            color: #999999;
            flex: 1;
        }
        .num {
            font-size: 14px;
            color: #333;
            font-weight: bold;
        }
    }
}
</style>
