<!--
@name 公用组件：一、二级联动-仓库信息选择
@desc 基于 vant-ui IndexBar
【必填入参】：
    @param {Object} [selectedModel] - 当前选中的对象(选填)
        @example: {locacode:"",locaname:"",stoargecode:"",stoargename:""}      - 一条仓库与仓位
    @param {Array} [modelArray]   - 原始数据
        @example: [{locacode:"",locaname:"",stoargecode:"",stoargename:""}...] - 多条仓库与仓位
    @param {Object} [fieldsMap]   - 数据命名，如果父级不开启，无需声明pnameField和pnameField，或填入空字符
        @example: fieldsMap: {
                codeField: "locacode"      - modelArray 编码字段名 <string>
                nameField: "locaname"      - modelArray 名称字段名(选填) <string>
                // 有父级内容就二级选择 code+pcode为主键
                pcodeField: "stoargecode"  - 父级编码字段名(选填) <string>选项数据类型string
                pnameField: "stoargename"  - 父级名称字段名(选填) <string>选项数据类型string
                useStrict: ""  - 二级必填(选填) <string>选项数据类型string
                locaStyle: ""  - 二级模式0：不使用、1：自由选填、2：严格选择(选填) <string>选项数据类型string
            }

【选填入参】：
    @param {String} [inputPho]    - 占位符文本
    @param {String} [pInputPho]   - 父级占位符文本

【回调出参】：
    @function {out} confirm(selectedModel) - 确认事件
    @function {out} closed() - 已关闭回调事件

【父组件控制方法】：
    @function {in} - 开启：open(isOpenSecond)  -- this.$refs.modle.open(isOpenSecond)
        @param {Boolean} [isOpenSecond]是否开启第二列表;
    @function {in} - 关闭：close() -- this.$refs.modle.close();
Hock
validating(param) - param.selectedModel:当前选中对象 param.IsValid:验证是否通过(需要设置)

@example 调用示例
    <lj-storage ref="modle" :fieldsMap="fieldsMap" :selectedModel="selectedModel" :modelArray="list" @confirm="handleStorageCfm"></lj-storage>
@time 2020年9月11日 -- design by Yj_cHen
-->
<template>
    <van-popup
        v-model="showStorage"
        position="bottom"
        :style="{ height: '80%' }"
        get-container="body"
        class="lj-storage-popup"
        @closed="handleCloseWidget"
    >
        <div class="lj-storage-wrapper">
            <div class="control-box">
                <div class="control-box-main">
                    <van-field
                        class="pda-input"
                        v-model="firstInput"
                        :placeholder="firstPho"
                        label-width="45"
                        :clearable="true"
                        clear-trigger="always"
                        @focus="handleFocus($event)"
                        @clear="handleClearFirst"
                        @input="handleInputingFirst"
                        @keyup.enter.native="handleConfirm"
                    />
                    <van-field
                        class="pda-input"
                        v-if="secondVisible"
                        v-model="secondInput"
                        :placeholder="secondPho"
                        label-width="45"
                        :clearable="true"
                        clear-trigger="always"
                        @focus="handleFocus($event)"
                        @clear="handleClearSecond"
                        @input="handleInputingSecond"
                        @keyup.enter.native="handleConfirm"
                    />
                </div>
                <div class="control-box-confirm">
                    <van-button class="confirm-btn" size="small" type="info" @click="handleConfirm">
                        确定
                    </van-button>
                </div>
            </div>

            <div>
                <span class="suggestion" v-if="suggestStr.length">{{suggestStr}}</span>
            </div>

            <div class="indexbar-box">
                <van-loading class="loading-box" v-if="searchState" color="#1989fa" size="24px" vertical>查找中...</van-loading>
                <van-index-bar ref="vanIndexBar" :sticky="false" :index-list="indexList" v-if="modelList.length">
                    <template v-for="(items, index) in modelList">
                        <div :key="index">
                            <van-index-anchor :index="items.letter" />
                            <template v-for="(item, idx) in items.data">
                                <van-cell :key="idx" @click="handleSelVal(item)">
                                    <template slot="icon" v-if="firstId == item.code || secondId == item.code">
                                        <svg class="icon svg-icon" aria-hidden="true">
                                            <use xlink:href="#icon-zhengque1"></use>
                                        </svg>
                                    </template>
                                    <template slot="title">
                                        <span style="padding-right: 15px">{{ item.code }}</span>
                                        <span>{{ item.name }}</span>
                                    </template>
                                </van-cell>
                            </template>
                        </div>
                    </template>
                </van-index-bar>
                <van-empty v-else image="search" description="暂无匹配数据">
                    <van-button round type="info" size="small" @click="handleResetSearch">
                        重置搜索条件
                    </van-button>
                </van-empty>
            </div>
        </div>
    </van-popup>
</template>

<script>
import { IndexBar, IndexAnchor } from "vant"
import { ConvertPinyin } from "./py.js"

export default {
    name: "lj-storage",
    components: {
        "van-index-bar": IndexBar,
        "van-index-anchor": IndexAnchor,
    },
    data() {
        return {
            showStorage: false,
            secondVisible: false,
            searchState: false,
            hasParentStatus: false,
            firstId: "", // 一级id
            firstState: "", // 一级的值
            firstInput: "", // 一级状态
            firstlist: [], // 一级处理后的数据
            secondId: null, // 二级id
            secondState: null, // 二级的值
            secondInput: "", // 二级状态
            secondlist: [], // 二级处理后的数据
            modelList: [], // 展示列表
            indexList: [], // 索引列表
            step: 0,
            parentCodeText: "",
            parentNameText: "",
            childCodeText: "",
            childNameText: "",
            // lastSecond: []
        };
    },
    props: {
        inputPho: {
            type: String,
            default: "请选择，或输入关键字搜索"
        },
        pInputPho: {
            type: String,
            default: "请选择，或输入关键字搜索"
        },
        fieldsMap: {
            required: true,
            type: Object,
            default: function () {
                return {
                    codeField: "",
                    nameField: "",
                    pcodeField: "",
                    pnameField: "",
                    useStrict: "",
                    locaStyle: ""
                }
            }
        },
        // 选中值
        selectedModel: {
            type: Object,
            default: function () {
                return {}
            }
        },
        // 原始数据
        // modelArray: {
        //     required: true,
        //     type: Array,
        //     default: function () {
        //         return []
        //     }
        // },
        errormsg: {
            type: String,
            default: "仓库数据获取失败"
        },

        //建议说明
        suggestStr:{
            type: String,
            default: ""
        },
        // 一级数组-原始数据转化
        fatherList: {
            required: true,
            type: Array,
            default: function () {
                return []
            }
        },
        // 二级数组-原始数据转化
        childList: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 仅限于仓位一级列表时使用，仓库信息的载体
        onlyLocation: {
            type: Object,
            default: function () {
                return {}
            }
        },
    },
    computed: {
        firstPho() {
            return this.hasParentStatus ? this.pInputPho : this.inputPho;
        },
        secondPho() {
            return this.hasParentStatus ? this.inputPho : "";
        }
    },
    methods: {
        /**组件保存事件 */
        handleConfirm() {
            let mustCheckout = true;
            let freeStyle = 2; // 2严格模式，1自由模式，0不使用
            let hasIndex = -1;

            console.log("开始this.firstId==》", this.firstId);
            console.log("开始this.firstState==》", this.firstState);
            console.log("开始this.firstInput==》", this.firstInput);
            console.log("开始this.this.onlyLocation==》", JSON.stringify(this.onlyLocation));
            if (JSON.stringify(this.onlyLocation) != "{}") {
                // 仅限于仓位一级列表时运行
                let useStrict = null;
                useStrict = this.fieldsMap.useStrict && this.onlyLocation[this.fieldsMap.useStrict];
                freeStyle = this.fieldsMap.locaStyle && this.onlyLocation[this.fieldsMap.locaStyle];
                mustCheckout = Boolean(Number(useStrict));
            } else if (this.firstId && this.fieldsMap.useStrict || this.firstId && this.fieldsMap.locaStyle) {
                // 读取一级基础信息，根据仓库属性，使用自由模式
                let useStrict = null;
                // hasIndex = this._fnCheckIndex(this.modelArray, this.parentCodeText, this.firstId);
                hasIndex = this._fnCheckIndex(this.fatherList, this.parentCodeText, this.firstId);
                if (hasIndex > -1) {
                    // useStrict = this.fieldsMap.useStrict && this.modelArray[hasIndex][this.fieldsMap.useStrict];
                    // freeStyle = this.fieldsMap.locaStyle && this.modelArray[hasIndex][this.fieldsMap.locaStyle];
                    useStrict = this.fieldsMap.useStrict && this.fatherList[hasIndex][this.fieldsMap.useStrict];
                    freeStyle = this.fieldsMap.locaStyle && this.fatherList[hasIndex][this.fieldsMap.locaStyle];
                }
                console.log("hasIndex==>", hasIndex);
                console.log("useStrict==>", useStrict);
                mustCheckout = Boolean(Number(useStrict));
            }
            if ( freeStyle != 1 && !this.modelList.length){
                this.$toast({
                    position: "bottom",
                    message: "查询失败",
                });
                return false;
            } else if (this.modelList.length == 1 && this.modelList[0].data.length == 1) {
                // 当筛选只有一个时的判断
                let item = this.modelList[0].data[0];
                if (this.hasParentStatus) {
                    // 二级
                    if (this.step == 0) {
                        this.handleSelVal(item);
                        return false;
                    } else {
                        if (freeStyle == 1) {
                            if (this.secondInput == item.code || this.secondInput == item.name) {
                                // 当自由选填时，匹配文字与仓位相同时
                                this.secondId = item.code;
                                this.secondInput = item.name;
                                this.secondState = item.name;
                            }
                        } else {
                            // 非自由选填
                            this.secondId = item.code;
                            this.secondInput = item.name;
                            this.secondState = item.name;
                        }
                    }
                } else {
                    // 一级
                    this.firstId = item.code;
                    this.firstState = item.name;
                    this.firstInput = item.name;
                    this.secondInput = null;
                    this.secondState = null;
                }
            }

            if (mustCheckout) {
                if (JSON.stringify(this.onlyLocation) != "{}") {
                    console.log("freeStyle == 1 && !this.firstInput", JSON.stringify(freeStyle == 1 && !this.firstInput));
                    if (freeStyle == 1 && !this.firstInput) {
                        this.$toast({
                            position: "bottom",
                            message: "请输入，或选择下列选项",
                        });
                        return false;
                    } else if (this.firstState == "" || this.firstState != this.firstInput) {
                        this.$toast({
                            position: "bottom",
                            message: "请选择下列选项",
                        });
                        return false;
                    }
                } else {
                    if (freeStyle == 1) {
                        if (!this.secondInput) {
                            this.$toast({
                                position: "bottom",
                                message: "请输入，或选择下列选项",
                            });
                            return false;
                        }
                    } else if (
                        (this.firstState == "" || this.firstState != this.firstInput) ||
                        (this.secondState == "" || this.secondInput != this.secondState)
                    ) {
                        this.$toast({
                            position: "bottom",
                            message: "请选择下列选项",
                        });
                        return false;
                    }
                }
            }
            console.log("this.hasParentStatus", this.hasParentStatus);
            console.log("this.firstId", this.firstId);
            console.log("this.firstState", this.firstState);
            console.log("this.firstInput", this.firstInput);
            let rtModel = {};
            if (this.hasParentStatus) {
                // 二级
                let storage = $lj.getStorage("storageInfo").storageList;
                let warehouse = storage.find(wh => wh[this.parentCodeText] === this.firstId);
                if(warehouse && warehouse.children) {
                    let childList = warehouse.children.localist;

                    for (let i = 0; i < childList.length; i++) {
                        if (childList[i][this.parentCodeText] == this.firstId && childList[i][this.childCodeText] == this.secondId) {
                            rtModel = childList[i];
                            break;
                        }
                    }
                }

                console.log("JSON.stringify(rtModel)==>", JSON.stringify(rtModel));

                /** 无法匹配已有仓位数据 */
                if (JSON.stringify(rtModel) =="{}") {
                    if (this.firstId) {
                        /** 有父级-仓库id */
                        /** 有设置仓位必填，且仓位必填 */
                        if (this.fieldsMap.useStrict && this.fatherList[hasIndex][this.fieldsMap.useStrict]) {
                            if (freeStyle != 1) {
                                /** 仓位必填，且非自由选填，清空二级属性 */
                                let obj = JSON.parse(JSON.stringify(this.fatherList[hasIndex]));
                                obj[this.childCodeText] = null;
                                obj[this.childNameText] = null;
                                rtModel = obj;

                                this.$emit("confirm", rtModel);
                                return;
                            }
                        }
                        if (this.fieldsMap.locaStyle) {
                            /** 有设仓位 */
                            if (freeStyle == 1) {
                                /** 自由选填 */
                                let obj = JSON.parse(JSON.stringify(this.fatherList[hasIndex]));
                                obj[this.childCodeText] = this.secondInput;
                                obj[this.childNameText] = this.secondInput;
                                rtModel = obj;

                                this.$emit("confirm", rtModel);
                                return;
                            } else {
                                /** 严格选填与不使用仓位，清空二级属性 */
                                let obj = JSON.parse(JSON.stringify(this.fatherList[hasIndex]));
                                obj[this.childCodeText] = null;
                                obj[this.childNameText] = null;
                                rtModel = obj;

                                this.$emit("confirm", rtModel);
                            }
                        }
                        /** 仓位可空 */
                            
                    }
                    // if (this.firstId && this.fieldsMap.useStrict && this.fatherList[hasIndex][this.fieldsMap.useStrict]) {
                    //     // 二级必填
                    //     if (!this.secondState && freeStyle != 1) {
                    //         // 当没选二级时
                    //         // let obj = JSON.parse(JSON.stringify(this.modelArray[hasIndex]));
                    //         let obj = JSON.parse(JSON.stringify(this.fatherList[hasIndex]));
                    //         obj[this.childCodeText] = null;
                    //         obj[this.childNameText] = null;
                    //         rtModel = obj;

                    //         this.$emit("confirm", rtModel);
                    //         return;
                    //     }
                    // }
                    // if (this.firstId && this.fieldsMap.locaStyle && this.fatherList[hasIndex][this.fieldsMap.locaStyle] && freeStyle == 1) {
                    //     // 当自由选填时，匹配文字与仓位相同时
                    //     // let obj = JSON.parse(JSON.stringify(this.modelArray[hasIndex]));
                    //     let obj = JSON.parse(JSON.stringify(this.fatherList[hasIndex]));
                    //     obj[this.childCodeText] = this.secondInput;
                    //     obj[this.childNameText] = this.secondInput;
                    //     rtModel = obj;

                    //     this.$emit("confirm", rtModel);
                    //     return;
                    // }
                    // if (this.firstId && this.fieldsMap.locaStyle && !this.fatherList[hasIndex][this.fieldsMap.locaStyle]){
                    //     // 开启二级选项，没有二级菜单时，返回仓库信息

                    //     let obj = JSON.parse(JSON.stringify(this.fatherList[hasIndex]));
                    //     obj[this.childCodeText] = null;
                    //     obj[this.childNameText] = null;
                    //     rtModel = obj;

                    //     this.$emit("confirm", rtModel);
                    //     return;
                    // }
                }
            } else {
                // 一级
                let fatherIndex = this._fnCheckIndex(this.fatherList, this.parentCodeText, this.firstId);
                if (fatherIndex > -1) {
                    rtModel = this.fatherList[fatherIndex];
                }
                console.log("JSON.stringify(rtModel)/ 金凯奇==>", JSON.stringify(rtModel));

                // 仅限于仓位一级列表时使用
                if (JSON.stringify(this.onlyLocation) != "{}" && JSON.stringify(rtModel) == "{}") {
                    if (freeStyle == 1) {
                        // 自由选填
                        //let obj = JSON.parse(JSON.stringify(this.fatherList[0]));
                        let obj = {};
                        obj[this.parentCodeText] = this.firstInput;
                        obj[this.parentNameText] = this.firstInput;
                        rtModel = obj;

                        this.$emit("confirm", rtModel);
                        return;
                    }
                }


            }
            // this.lastSecond = JSON.parse(JSON.stringify(this.secondlist));
                console.log("JSON.stringify(rtModel)/ 正常选择==>", JSON.stringify(rtModel));
            this.$emit("confirm", rtModel);
        },
        /**点击选择索引 */
        handleSelVal(item) {
            console.log("item", JSON.stringify(item));
            if (!this.hasParentStatus) {
                // 一级
                this.firstId = item.code;
                this.firstState = item.name;
                this.firstInput = item.name;

                this._fnClearSecond();
                this.secondInput = null;
                this.secondState = null;
                this.handleConfirm();
                return false;
            }
            if (this.step == 0) {
                // 第一级
                this.step++;
                this.firstId = item.code;
                this.firstState = item.name;
                this.firstInput = item.name;
                $lj.getLocaList(this.firstId,"scode").then(result => {
                    this.secondlist = this._autoLetterSort(result, this.childCodeText, this.childNameText);

                    let freeStyle = 2; // 2严格模式，1自由模式，0不使用
                    let hasIndex = -1;
                    hasIndex = this._fnCheckIndex(this.fatherList, this.parentCodeText, this.firstId);
                    if (hasIndex > -1) {
                        freeStyle = this.fieldsMap.locaStyle && this.fatherList[hasIndex][this.fieldsMap.locaStyle];
                    }

                    if (freeStyle > 0) {
                        // 当仓库有仓位时
                        this.secondInput = "";
                        this.secondState = "";
                        this.secondVisible = true;
                        this._fnSetValue(this.secondlist);
                    } else {
                        // 没有子列表
                        this._fnClearSecond();
                        this.secondInput = null;
                        this.secondState = null;
                        this.handleConfirm();
                    }
                })
            } else {
                // 第二级
                this.secondId = item.code;
                this.secondInput = item.name;
                this.secondState = item.name;
                this.handleConfirm();
            }
        },
        /**输入监听-一级 */
        handleInputingFirst(val) {
            console.log("输入监听:", val);
            let self = this;
            this.searchState = true;
            this.firstId = "";
            this.firstState = "";
            this.step = 0;
            this._fnClearSecond();
            this.firstlist = [];
            this._fnSearchList(val, this.fatherList, this.parentCodeText, this.parentNameText, function() {
                self.searchState = false;
            });
            this._fnSetValue(this.firstlist);
        },
        /**输入监听-二级 */
        handleInputingSecond(val) {
            let self = this;
            this.searchState = true;
            this.secondId = "";
            this.secondState = "";
            this.secondlist = [];
            this.step = 1;
            $lj.getLocaList(this.firstId,"scode").then(result => {
                this._fnSearchList(val, result, this.childCodeText, this.childNameText, function() {
                    self.searchState = false;
                });
                this._fnSetValue(this.secondlist);
            })
        },
        /**聚焦input */
        handleFocus(ev) {
            // this.$refs.vanIndexBar.onScroll();
            ev.currentTarget.select();
        },
        /**点击清除-一级input */
        handleClearFirst() {
            this.firstId = null;
            this.firstState = "";
            this._fnReset();
            this._fnClearSecond();
        },
        /**点击清除-二级input */
        handleClearSecond() {
            this._fnResetSecond()
        },
        /**点击重置 */
        handleResetSearch() {
            if (!this.firstlist.length) {
                // 重置一级列表
                this.firstInput = "";
                this.firstState = "";
                this.handleInputingFirst("");
            } else if (!this.secondlist.length) {
                // 重置二级列表
                this.secondInput = "";
                this.secondState = "";
                this.handleInputingSecond("");
            }
        },
        open(isOpenSecond, callback) {
            console.time("组件开启用时==》");

            this._autoCheckPropData();
            let fId = this.selectedModel[this.parentCodeText] || null;
            let sId = this.selectedModel[this.childCodeText] || null;
            console.log("fId：", fId);
            console.log("sId：", sId);

            if (Boolean(sId)) {
                // 当仓库有仓位时
                let storage = $lj.getStorage("storageInfo").storageList;
                let warehouse = storage.find(wh => wh[this.parentCodeText] === fId);
                if(warehouse && warehouse.children) {
                    let childList = warehouse.children.localist;

                    this.secondVisible = true;
                    this.secondId = sId;
                    this.secondInput = getStr(sId, childList, this.childCodeText, this.childNameText);
                    if (this.fieldsMap.locaStyle && this.selectedModel[this.fieldsMap.locaStyle] == 1 && !this.secondInput) {
                        this.secondInput = sId;
                    }
                    this.secondState = this.secondInput;
                }
            } else if (sId == null) {
                // 当仓库没有设置仓位时
                this.secondId = sId;
                this.secondInput = null;
                this.secondState = null;
            }
            if (fId) {
                this.firstId = fId;
                this.firstInput = getStr(fId, this.fatherList, this.parentCodeText, this.parentNameText);
                this.firstState = this.firstInput;
            }

            if (isOpenSecond && fId && sId != null) {
                // 当仓库有仓位时
                $lj.getLocaList(fId,"scode").then(result => {
                    this.secondlist = this._autoLetterSort(result, this.childCodeText, this.childNameText);
                    this.step = 1;
                    this._fnSetValue(this.secondlist);
                })
            } else {
                this._fnReset();
            }
            // let self = this;
            this.$nextTick(() => {
                this.showStorage = true;
                callback && callback();
                // self.searchState = false;
            });
            console.timeEnd("组件开启用时==》");

            function getStr(id, l, p1, p2) {
                let str = "";
                for (let i = 0; i < l.length; i++) {
                    if (id == l[i][p1]) {
                        str = l[i][p2];
                        break;
                    }
                }
                return str;
            }

        },
        handleCloseWidget() {
            this.step = 0;
            this.firstId = "";
            this.firstInput = "";
            this.firstState = "";

            this.secondInput = "";
            this.secondVisible = false;
            this.secondId = null;
            this.secondInput = "";
            this.secondState = null;

            this.firstlist = []; // 一级处理后的数据
            this.secondlist = []; // 二级处理后的数据
            this.modelList = []; // 展示列表
            this.indexList = []; // 索引列表
            this.$emit("closed");
        },
        close() {
            this.showStorage = false;
        },
        /**检测数据 */
        _autoCheckPropData() {
            if (!this.fatherList.length) {
                this.$toast({
                    position: "middle",
                    message: this.errormsg,
                });
                this.close();
                return false;
            }
             if (this.fieldsMap.hasOwnProperty("pcodeField") && this.fieldsMap.pcodeField!="") {
                // 二级
                this.hasParentStatus = true;
                console.time("整合父级数组");
                this.parentCodeText = this.fieldsMap.pcodeField;
                this.parentNameText = this.fieldsMap.pnameField;
                this.childCodeText = this.fieldsMap.codeField;
                this.childNameText = this.fieldsMap.nameField;

                console.timeEnd("整合父级数组");
            } else {
                // 一级
                this.hasParentStatus = false;
                this.parentCodeText = this.fieldsMap.codeField;
                this.parentNameText = this.fieldsMap.nameField;
            }
            console.log("this.fatherList", this.fatherList);
            console.log("this.childList", this.childList);
        },
        _fnSearchList(val, list, property1, property2, callback) {
            let alist = getList(val.trim(), list, property1, property2);
            if (!this.firstlist.length) {
                if (alist.length) {
                    this.firstlist = this._autoLetterSort(alist, property1, property2);
                    console.log("this.firstlist==>", this.firstlist);
                }
            } else if (!this.secondlist.length) {
                if (alist.length) {
                    this.secondlist = this._autoLetterSort(alist, property1, property2);
                    console.log("this.firstlist==>", this.secondlist);
                }
            }
            callback();

            function getList(v, l, p1, p2) {
                let rlist = [];
                for (let i = 0; i < l.length; i++) {
                    if (l[i][p1].indexOf(v) > -1 || l[i][p2].indexOf(v) > -1 ) {
                        rlist.push(l[i]);
                    }
                }
                return rlist;
            }
        },
        _fnResetSecond() {
            this.step = 1;
            // let rtList = this._autoCreateSecondList(this.firstId);
            $lj.getLocaList(this.firstId,"scode").then(result => {
                this.secondlist = this._autoLetterSort(result, this.childCodeText, this.childNameText);
                // 当仓库有仓位时

                this._fnSetValue(this.secondlist);
                this.secondId = "";
                this.secondInput = "";
                this.secondState = "";
            })
        },
        _fnClearSecond() {
            this.secondVisible = false;
            this.secondId = "";
            this.secondInput = "";
            this.secondState = "";
        },
        _fnReset() {
            this.step = 0;
            this._autoCreateFirstList();
            this._fnSetValue(this.firstlist);
        },
        _fnSetValue(list) {
            this.modelList = list;
            this.indexList = this._autoData(this.modelList);
        },
        /**提取右侧悬浮索引数据 */
        _autoData(arr) {
            let rArr = [];
            for (let i = 0; i < arr.length; i++) {
                rArr.push(arr[i].letter);
            }
            return rArr;
        },
        _autoLetterSort(arr, noLabel, nameLabel) {
            if (!arr.length) return false;
            var letters = "*0123456789abcdefghijklmnopqrstvwxyz".split('');
            var segs = [];
            var curr;
            let arrCope = JSON.parse(JSON.stringify(arr));
            console.time("制数用时==>");
            for (let i = arrCope.length - 1; i >= 0; i--) {
                let fLetter = arrCope[i][noLabel].toString().split('');
                let target = arrCope[i][noLabel];
                // 如果首字符是中文，就进行转化
                if (escape(fLetter[0]).indexOf("%u") > -1) {
                    //汉字转英文
                    target = ConvertPinyin(arrCope[i][noLabel]);
                }
                arrCope[i].target = target;
            }
            letters.forEach(function(item, i) {
                curr = {letter: item.toUpperCase(), data:[]};
                for (let j = arrCope.length - 1; j >= 0; j--) {
                    let target = arrCope[j].target;
                    if(letters[i].localeCompare(target) <= 0 && (!letters[i+1] || target.localeCompare(letters[i+1]) == -1)) {
                        let obj = {};
                        obj.code = arrCope[j][noLabel];
                        obj.name = arrCope[j][nameLabel];
                        obj.ifmy = arrCope[j].ifmy;
                        obj.storageid = arrCope[j].storageid || 0;
                        curr.data.push(obj);
                        arrCope.splice(j, 1);
                    }
                }
                if(curr.data.length) {
                    segs.push(curr);
                }
            });
            // 按code排序
            for (let i = 0; i < segs.length; i++) {
                if (segs[i].data.length > 1) {
                    segs[i].data.sort(function(a,b){
                        if(a.ifmy && b.ifmy) return a.ifmy > b.ifmy ? -1 : a.ifmy === b.ifmy ? 0 : 1;
                        if(a.ifmy && !b.ifmy) return -1;
                        if(!a.ifmy && b.ifmy) return 1;
                        return a.code.localeCompare(b.code);
                    });
                }
            }
            // 按ifmy排序
            for (let i = 0; i < segs.length; i++) {
                if (segs[i].data.length > 1) {

                };
            }
            console.timeEnd("制数用时==>");
            console.log(`segs:${JSON.stringify(segs)}`);
            return segs;
        },
        _autoCreateFirstList() {
            if (this.firstlist.length) return false;
            this.firstlist = this._autoLetterSort(this.fatherList, this.parentCodeText, this.parentNameText);
        },
        _autoCreateSecondList(fId) {
            console.log("selectedModel  ===》",JSON.stringify(this.selectedModel));
            console.time("_autoCreateSecondList制数用时===》");
            let rArr = [];
            for (let i = 0; i < this.childList.length; i++) {
                if (fId == this.childList[i][this.parentCodeText]) {
                    rArr.push(this.childList[i]);
                }
            }
            console.timeEnd("_autoCreateSecondList制数用时===》");
            return rArr;
        },
        /**计算是否含有某条码 */
        _fnCheckIndex(aList, value, target) {
            if (!aList.length) return -1;
            if (target == "" || target == null || target == undefined) return -1;

            let hasValue = -1;
            for (let i = 0; i < aList.length; i++) {
                if (target.toString().trim() == aList[i][value].toString().trim()) {
                    hasValue = i;
                    break;
                }
            }
            return hasValue;
        },
    },
    beforeDestroy() {
        this.firstlist = null; // 一级处理后的数据
        this.secondlist = null; // 二级处理后的数据
        this.modelList = null; // 展示列表
        this.indexList = null; // 索引列表
    }
}
</script>

<style lang="less" scoped>
@import "~assets/css/lj-style-variable.less";
.lj-storage-wrapper {
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
    .control-box {
        flex-shrink: 0;
        display: flex;
        position: relative;
        margin: 0 5px;
        z-index: 2;
        border-bottom: 1px solid #ccc;
        background-color: #fff;
        .control-box-main {
            flex: 1;
            margin-left: 10px;
        }
        .control-box-confirm {
            flex-shrink: 0;
        }
        .confirm-btn {
            display: block;
            margin: 10px;
        }
    }
    .suggestion{
        margin: 5px 10px;
        color: @musePrimary;
        font-size: 14px;
    }
    .indexbar-box {
        flex: 1;
        overflow: auto;
        .loading-box {
            margin-top: 15px;
        }
        .icon {
            display: inline-block;
            margin: auto 0;
            margin-right: 5px;
            width: 22px;
            height: 22px;
        }
    }
}
.van-index-bar__sidebar {
    top: 60%!important;
}
.pda-input {
    margin: 10px 0;
    padding: 5px 5px;
    background-color: #f2f2f2;
    border-radius: 15px;
    > .van-field__value {
        padding-left: 10px;
        padding-right: 10px;
    }
}
</style>
