<template>
    <view class="mx3">
        <my-add-button @handleClick="openSpare" />
        <view class="main-color-bg main-bg-future"></view>
        <view class="p3 bg-color-white form-view">
            <u-form :model="form" :error-type="['message']" ref="uForm" >
                <view class="main-color-text f-size-32 f-weight-6">出库信息</view>
                <u-form-item label="仓库名称" prop="storeId" required label-width="150">
                    <my-select
                        :list="storeList"
                        :value-name="'id'"
                        :label-name="'name'"
                        v-model="form.storeId"
                        placeholder="请选择仓库"
                        @selected="storeSelect"
                    />
                </u-form-item>

                <u-form-item label="备品用途" prop="type" required label-width="150">
                    <my-select
                        :list="reasonList"
                        v-model="form.type"
                        @selected="typeSelect"
                        placeholder="请选择备品用途" />
                </u-form-item>

                <u-form-item label="出库说明" label-width="150">
                    <u-input type="textarea" v-model="form.remark" />
                </u-form-item>

            </u-form>
        </view>

        <view class="p3 bg-color-white form-view mt-3-imt" v-if="receiveDetailFormList && receiveDetailFormList.length>0">
            <!-- <view class="main-color-text f-size-32 f-weight-6">出库明细</view> -->
            <u-form
                :error-type="['message']"
                v-for="(item,index) in receiveDetailFormList"
                :key="index"
                :model="receiveDetailFormList[index]"
                :ref="item.formName"
            >
                <view class="main-color-text f-size-32 f-weight-6 d-flex j-between" @tap="del(index)">
                    出库明细
                    <u-icon name="close-circle" color="red"></u-icon>
                </view>
                <u-form-item label="名称" prop="spareId" required label-width="150">
                    <u-input
                        v-model="item.spareName"
                        disabled
                        @click="handleSelect(item.formName)"
                        placeholder="请选择"
                        type="select"
                    />
                </u-form-item>

                <u-form-item label="数量" prop="num" required label-width="150">
                    <u-input type="number" v-model="item.num" />
                </u-form-item>

            </u-form>
        </view>
        <view class="mt-3">
            <u-button @click="submit" type="primary" shape="circle">提交</u-button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            typeMap: {},
            form: {
                storeId: '',
                type: '',
                reason: '',
                storeName: null
            },
            receiveDetailFormList: [

            ],
            backSpareId: '',
            backSpareName: '',
            backFormName: '',
            backPrice: 0,
            isRefreshDetail: true,
            sbSpareList: [],
            storeList: [],
            reasonList: [
                {
                    label: '领用出库',
                    value: '1'
                }, {
                    label: '调拨出库',
                    value: '2'
                }, {
                    label: '报废出库',
                    value: '3'
                }, {
                    label: '其他出库',
                    value: '4'
                }, {
                    label: '盘点校准',
                    value: '5'
                }
            ],
            rules: {
                type: [
                    {
                        required: true,
                        message: '请选择备品用途',
                        trigger: ['change']
                    }
                ],
                storeId: [
                    {
                        required: true,
                        message: '请选择仓库',
                        trigger: ['change']
                    }
                ]
            },
            detailFormRules: {
                spareId: [
                    {
                        required: true,
                        message: '请选择备品',
                        trigger: ['change']
                    }
                ],
                num: [
                    {
                        required: true,
                        message: '请填写数量',
                        trigger: ['change', 'blur']
                    }
                ]
            },
            id: '', // 列表 id
            aId: 0
        };
    },
    created () {
        this.typeMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.OUT_STORE_FORM_TYPE)
    },
    onShow() {
        // 获取设备与仓库
        this.initData();
    },
    onLoad(options) {},
    methods: {
        del(index) {
            console.log(this.receiveDetailFormList);
            this.receiveDetailFormList.splice(index, 1)
            console.log(this.receiveDetailFormList);
        },
        handleSelect(formName) {
            const spareId = '121'
            this.$Http.getSpareStorePage({ storeId: this.form.storeId, spareId: spareId, pageNum: 1, pageSize: 1 })
                .then(res => {
                    const spareList = res.data.rows
                    if(spareList ==null || spareList.length == 0){
                        uni.showToast({
                            title: "该仓库无此备件，请重新扫描",
                            icon: "none",
                        });
                    }
                    const scanSpare = spareList[0]
                    this.receiveDetailFormList.forEach(spare => {
                        if (spare.formName === formName) {
                            spare.spareId = scanSpare.spareId;
                            spare.spareName = scanSpare.spareName;
                            spare.price = scanSpare.price;
                        }
                    })
                })
        },
        // 扫码出库
        handleSelectScan(formName) {
            // #ifdef H5
            uni.showToast({
                title: "暂不支持该功能",
                icon: "none"
            });
            // #endif
            // #ifndef H5
            uni.scanCode({
                success(e) {
                    if (e.result) {
                        const spareId = e.result;
                        this.$Http.getSpareStorePage({ storeId: 2, spareId: spareId, pageNum: 1, pageSize: 1 })
                            .then(res => {
                                const spareList = res.data.rows
                                if(spareList ==null || spareList.length == 0){
                                    uni.showToast({
                                        title: "该仓库无此备件，请重新扫描",
                                        icon: "none",
                                    });
                                }
                                const scanSpare = spareList[0]
                                this.receiveDetailFormList.forEach(spare => {
                                    if (spare.formName === formName) {
                                        spare.spareId = scanSpare.spareId;
                                        spare.spareName = scanSpare.spareName;
                                        spare.price = scanSpare.price;
                                    }
                                })
                            })
                    }
                },
            });
            // #endif
        },
        initData() {
            if(this.storeList.length == 0){
                this.$Http.getStorePage({ filter: 2, pageNum: 1, pageSize: 1000 })
                    .then(res => {
                        this.storeList = res.data.rows
                    })
            }
        },
        openSpare() {
            /* if (this.$BaseTool.Object.isBlank(this.form.type)) {
                uni.showToast({
                    title: '请先选择备品用途',
                    icon: 'none'
                });
                return
            } */
            if (this.$BaseTool.String.isBlank(this.form.storeId)) {
                uni.showToast({
                    title: '请先选择仓库',
                    icon: 'none'
                });
                return
            }
            this.aId++
            const detailForm = {
                spareId: '',
                num: '',
                spareName: '',
                formName: 'form' + this.aId,
                price: '',
                item: null
            };
            if (!this.isRefreshDetail) {
                this.receiveDetailFormList.push(detailForm)
                this.$nextTick(() => {
                    this.$refs[detailForm.formName][0].setRules(this.detailFormRules);
                })
                return
            }

            if (!this.isRefreshDetail && this.sbSpareList != null && this.sbSpareList.length > 0) {
                return
            }
            this.$Http.getSpareStorePage({
                storeId: this.form.storeId,
                num: 0,
                pageNum: 1,
                pageSize: 10000,
                dataScope: {
                    sortBy: 'desc',
                    sortName: 'update_time'
                }
            }).then(res => {
                const sbSpareList = res.data.rows
                if (sbSpareList == null || sbSpareList.length === 0) {
                    this.isRefreshDetail = true;
                    uni.showToast({
                        title: '该仓库没有备品',
                        icon: 'none'
                    });
                    return
                }
                this.sbSpareList = res.data.rows
                this.receiveDetailFormList.push(detailForm)
                this.$nextTick(() => {
                    this.$refs[detailForm.formName][0].setRules(this.detailFormRules);
                })
                this.isRefreshDetail = false;
            })
        },
        storeSelect(value, item) {
            this.form.storeName = item.name;
            this.isRefreshDetail = true;
            this.receiveDetailFormList = []
        },
        typeSelect(value, item) {
            this.isRefreshDetail = true;
            //this.receiveDetailFormList = []
        },
        // 提交
        submit() {
            if (this.receiveDetailFormList == null || this.receiveDetailFormList.length === 0) {
                uni.showToast({
                    title: '请添加出库明细',
                    icon: 'none'
                });
                return
            }
            const promiseList = []
            promiseList.push(
                new Promise((resolve, reject) => {
                    this.$refs.uForm.validate().then(valid => {
                        if (valid) {
                            resolve(valid);
                        } else {
                            reject(valid);
                        }
                    })
                })
            );
            this.receiveDetailFormList.forEach(item => {
                promiseList.push(
                    new Promise((resolve, reject) => {
                        this.$refs[item.formName][0].validate(valid => {
                            if (valid) {
                                resolve(valid);
                            } else {
                                reject(valid);
                            }
                        })
                    })
                );
            })
            Promise.all(promiseList).then(res => {
                // 执行
                const params = { ...this.form }
                const detailList = []
                this.receiveDetailFormList.forEach(item => {
                    const space = item.item;
                    const detail = {
                        spareId: item.spareId,
                        num: item.num,
                        price: item.price,
                        spareName: item.spareName,
                        storeNum: item.num,
                        totalPrice: this.$BaseTool.Number.mul(item.num, item.price)
                    }
                    detailList.push(detail);
                })
                params.detailList = detailList;
                console.log(33, params)
                this.$Http.addOutStoreForm(params).then(res => {
                    uni.redirectTo({
                        url: '/pages/out-store/out-store-detail?id=' + res.data.id
                    });
                })
            }, err => {
                console.log(err)
            })
        }
    },
    onReady() {
        console.log(4444, this.$refs.uForm)
        this.$refs.uForm.setRules(this.rules);
    }
};
</script>

<style lang="less">
page {
    background-color: #f4f4f4;
}
.mt-3-imt {
    margin-top: 30rpx;
}
</style>
