<template>
    <div class="p-4 bg-white">
        <el-button type="text" @click="goBack">返回</el-button>
        <!-- <h2 class="text-center my-4">发货管理</h2> -->
        <div class="text-center my-4">
            <!--  <Vue3Barcode v-if="barcodeValue" :value='barcodeValue' width="1" height='30'></Vue3Barcode> -->
            <!--  <p>RYKS_DDD-20240527-00201</p> -->
        </div>
        <el-form :model="goodsExchangeAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
            style="max-width: 600px">
            <el-form-item prop="warehouse_id" label="出库仓库" class="change-form-item">

                <el-select v-model="goodsExchangeAddForm.warehouse_id" clearable>
                    <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="type" class="change-form-item">
                <el-select v-model="goodsExchangeAddForm.type" filterable allow-create clearable default-first-option
                    :disabled="goodsExchangeAddForm.type == 'SALE_AFTER' || goodsExchangeAddForm.type == 'HAIL_ENTRY'">
                    <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.value"
                        :disabled="item.value == 'TRANSFER_ENTRY' || item.value == 'HAIL_ENTRY' || item.value == 'SALE_AFTER'" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="change_desc" class="change-form-item" style="width: 100%">
                <el-input style="flex: 1" v-model="goodsExchangeAddForm.notes" type="textarea"
                    :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入"></el-input>
            </el-form-item>
            <el-button type="primary" size="large" @click="scanCode">扫码出库</el-button>
            <el-table :data="goodsExchangeAddForm.product_list" style="width: 100%;font-size: 12px;">
                <el-table-column prop="goods_vo.name" label="商品名称" />
                <el-table-column prop="product_vo.sku" label="SKU" />
                <el-table-column prop="out_num" label="出库数量">
                    <template #default="scope">
                            <span :style="{ color: scope.row.out_num > 0 ? 'red' : 'black' }">
                                {{ scope.row.out_num }}
                            </span>
                        </template>
                </el-table-column>
                <el-table-column prop="orderNum" label="待出库数量" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="mini" type="danger" @click="
                            goodsExchangeAddForm.product_list.splice(scope.$index, 1)
                            ">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <el-dialog v-model="dialogVisible" :modal=false title="扫码出库" :close-on-click-modal="false" top="80px"
            width="90%" style="height: 200px" :before-close="handleClose">
            <el-form :model="snCodeForm" label-width="auto" style="max-width: 600px">
                <el-form-item label="SKU">
                    <el-input v-model="snCodeForm.bar_code" ref="inputRef" clearable :inputmode="inputmode" @keyup.enter="toSearch()" >
                        <template #append> <img src="../../assets/images/JP.png" @click="getInfo" class="w-8 h-8" /> </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="序列号">
                    <el-input v-model="snCodeForm.sn_code" ref="snInputRef" clearable :inputmode="inputmode"
                        @keyup.enter="toSnCode()" />
                </el-form-item>
            </el-form>
            <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false"></el-button>
                    <el-button type="primary" @click="dialogVisible = false">
                        Confirm
                    </el-button>
                </div>
            </template> -->
        </el-dialog>
        <div class="flex justify-center mt-4">
            <el-button type="primary" size="large" @click="save(ruleFormRef)">保存</el-button>
            <el-button type="primary" size="large" @click="getOrderNumber(ruleFormRef)">出库</el-button>
            <!-- <el-button type="primary" size="large" @click="ship">发货</el-button> -->
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, reactive, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { orderApi, infoApi, dictionaryAPI, entryOutAPI } from '@/api/api'
//引入
import Vue3Barcode from 'vue3-barcode'
//定义要生成条形码的值
import { ElMessage, FormRules, FormInstance } from 'element-plus'
const appointment_time = ref('')
const defaultTime = new Date(2000, 1, 1, 12, 0, 0)
let dialogVisible = ref(false)
const tableData = ref([])
let inputmode = ref('text')
let barcodeValue = ref('')
const router = useRouter();
const route = useRoute()
const activeTab = ref('basic-info');
const id = ref(route.params.id);
const goodsExchangeAddForm: any = reactive({
    warehouse_id: '',
    type: '',
    notes: '',
    product_list: []
})
interface RuleForm {
    warehouse_id: string,
    type: string
}
const ruleFormRef = ref<FormInstance>()
//校验表单
const rules = reactive<FormRules<RuleForm>>({
    warehouse_id: [
        {
            required: true,
            message: 'Please select Activity zone',
            trigger: 'change',
        },
    ],
    type: [
        {
            required: true,
            message: 'Please select Activity count',
            trigger: 'change',
        },
    ],
})
//表单
const snCodeForm = reactive({
    bar_code: "",
    sn_code: '',
})
const inputRef = ref<any>(null);
const snInputRef = ref<any>(null)
const customerList: any = ref([])//初始化客户列表
const warehouseList: any = ref([])//初始化客户列表
const collectingAccountList: any = ref([])//初始化客户列表
const typeList: any = ref([])//初始化客户列表
const orderTypeList: any = ref([])//初始化客户列表
const index = ref(-1);
let sku = ref('');
const currentTimeStamp = ref(Date.now());
watch(activeTab, (newValue, oldValue) => {
    console.log(`Tab changed from ${oldValue} to ${newValue}`);
    // 这里可以添加一些逻辑，但要确保不会再次修改 activeTab
});
const getInfo = () => {
    if (inputmode.value == 'none') {
        inputmode.value = 'text'
        inputRef.value.focus();
    } else {
        inputmode.value = 'none'
        inputRef.value.focus();
    }
}
/* 扫sku */
const toSearch = async () => {
    activeTab.value = 'product-info'
    try {
        const res: any = await orderApi.getProduct(
            goodsExchangeAddForm.warehouse_id,
            snCodeForm.bar_code.replace(/\s+/g, '')
        );
        res.data.sn_code_list = [];
        sku.value = res.data.product_vo.sku;
        // 查找当前商品是否已存在于列表中
        const indexs = goodsExchangeAddForm.product_list.findIndex(
            (el) => {
                console.log("Comparing with:", el);
                return (
                    el.goods_vo.id === res.data.goods_id &&
                    el.product_id === res.data.product_id &&
                    el.product_vo.sku === res.data.product_vo.sku
                );
            }
        );
        // 如果商品不存在，则添加到列表
        if (indexs === -1) {
            index.value = goodsExchangeAddForm.product_list.length;
            goodsExchangeAddForm.product_list.push(res.data);
        } else {
            index.value = indexs;
        }
        if (res.data.product_vo.have_sn) {
            nextTick(() => {
                snInputRef.value.focus();
            });
        } else {
            if (goodsExchangeAddForm.order_item_vos[index.value].out_num >= goodsExchangeAddForm.order_item_vos[index.value].orderNum) return ElMessage.warning('待出库数量不能大于出库数量!')
            goodsExchangeAddForm.product_list[index.value].out_num += 1
            /* this.scanDialogVisible = false; */
        }
    } catch (error) {
        console.error('Error fetching product:', error);
    }
};
//扫描序列号
const toSnCode = async () => {
    if(!sku.value) return  ElMessage.error('请先扫描sku!')
    try {
        const res: any = await orderApi.getsnCode(
            "out",
            sku.value,
            snCodeForm.sn_code.replace(/\s+/g, '')
        );

        snCodeForm.sn_code = "";
        const exists = goodsExchangeAddForm.product_list[index.value].sn_code_list.find(
            item => item.sn_code === res.sn_code && item.sku === res.sku
        );

        if (!exists) {
            await infoApi.skuRedis({ send_order_id: id.value, item_id: goodsExchangeAddForm.product_list[index.value].id, sku: res.data }).then((respons: any) => {
                goodsExchangeAddForm.product_list[index.value].sn_code_list.push(res.data);
            })
        }
        goodsExchangeAddForm.product_list[index.value].out_num = goodsExchangeAddForm.product_list[index.value].sn_code_list.length;
        snCodeForm.bar_code = "";
        nextTick(() => {
            inputRef.value.focus();
        });
    } catch (error) {
        console.error('Error fetching SN code:', error);
    }
}

//关闭弹窗
const handleClose = (done: () => void) => {
    done()
}
onMounted(async () => {
    await getInforList();
    init();
});
const goBack = () => {
    router.push({ name: 'InoutStorage' });
};

const scanCode = () => {
    dialogVisible.value = true
    nextTick(() => {
        if (inputRef.value) {
            try {
                inputRef.value.focus(); // 先尝试聚焦 input 元素
                setTimeout(() => {
                    if (inputRef.value) {
                        inputRef.value.select();
                        inputmode.value='none'
                    }
                }, 100);
            } catch (error) {
                console.error('Failed to select input:', error);
            }
        }
    });
};
const getOrderNumber = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            goodsExchangeAddForm.out_time = Date.now()
            goodsExchangeAddForm.save_or_submit = "submit"
            if (!goodsExchangeAddForm.product_list.length) {
                ElMessage.error("请选择商品！");
                return;
            }
            goodsExchangeAddForm.product_list.map((el) => {
                el.product_stock_id = el.id;
                el.product_id = el.product_vo.id;
                el.id = "";
            });
            entryOutAPI.addWarehouseOut(id.value, goodsExchangeAddForm).then(res => {
                ElMessage.success("出库成功！");
                router.replace({
                    name: 'InoutStorage',
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};
const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            goodsExchangeAddForm.out_time = Date.now()
            goodsExchangeAddForm.save_or_submit = "save"
            if (!goodsExchangeAddForm.product_list.length) {
                ElMessage.error("请选择商品！");
                return;
            }
            goodsExchangeAddForm.product_list.map((el) => {
                el.product_stock_id = el.id;
                el.product_id = el.product_vo.id;
                el.id = "";
            });
            entryOutAPI.addWarehouseOut(id.value, goodsExchangeAddForm).then(res => {
                ElMessage.success("保存成功！");
                router.replace({
                    name: 'InoutStorage',
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};
const ship = () => {
    console.log('发货');
};
const init = async () => {
    try {
        const res: any = await entryOutAPI.warehouseOut(id.value);
        await infoApi.skuRedis({ send_order_id: id.value, type: 'enter' }).then((response: any) => {
            res.data.product_list.map(el => {
                el.orderNum = el.out_num
                el.out_num = 0
                Object.keys(response.data).map(item => {
                    if (el.id == item) {
                        el.sn_code_list = response.data[item]
                        el.out_num = el.sn_code_list.length
                    }
                })
                if (!el.sn_code_list) {
                    el.sn_code_list = []
                }
            })
        })
        goodsExchangeAddForm.warehouse_id = res.data.warehouse_id;
        goodsExchangeAddForm.type = res.data.type;
        goodsExchangeAddForm.notes = res.data.notes;
        goodsExchangeAddForm.product_list = res.data.product_list;
        console.log(goodsExchangeAddForm);
    } catch (error) {
        console.error("Failed to fetch order details:", error);
    }
}
/* 处理客户名称 */
const customerName = (value) => {
    if (value && customerList.value && customerList.value.data && customerList.value.data.data) {
        const type = customerList.value.data.data.find(type => type.id === value);
        return type ? type.name : '';
    }
}
/* 仓库名称 */
const warehouseName = (value) => {
    if (value && warehouseList.value && warehouseList.value.data) {
        const type = warehouseList.value.data.find(type => type.id === value);
        return type ? type.name : '';
    }
}
/* 支付列表*/
const collectingAccountName = (value) => {
    if (value && collectingAccountList.value && collectingAccountList.value.data && collectingAccountList.value.data.data) {
        const type = collectingAccountList.value.data.data.find(type => type.id === value);
        return type ? type.name : '';
    }
}
/* 配送方式*/
const deliveryName = (value) => {
    if (value && typeList.value && typeList.value.data && typeList.value.data.data) {
        const type = typeList.value.data.data.find(type => type.value === value);
        return type ? type.label : '';
    }
}
/* 订单状态*/
const orderTypeName = (value) => {
    if (value && orderTypeList.value && orderTypeList.value.data && orderTypeList.value.data.data) {
        const type = orderTypeList.value.data.data.find(type => type.value === value);
        return type ? type.label : '';
    }
}
/* 获取仓库,字典,客户信息 */
const getInforList = async () => {
    const warehouseData: any = await infoApi.warehouseList({})//获取仓库列表
    warehouseList.value = warehouseData.data
    customerList.value = await infoApi.customer({})//获取客户列表
    collectingAccountList.value = await infoApi.collectingAccount({})//获取支付方式列表
    const typeData: any = await dictionaryAPI.getPage({ dictType: "out_warehouse_type" })//获取配送方式
    typeList.value = typeData.data.data
    console.log(typeList.value);
    orderTypeList.value = await dictionaryAPI.getPage({ dictType: "Sale_order_send_status" })//获取订单状态
}
</script>

<style scoped>
.text-center {
    text-align: center;
}

.my-4 {
    margin-top: 1rem;
    margin-bottom: 1rem;
}

.mx-auto {
    margin-left: auto;
    margin-right: auto;
}

.p-4 {
    padding: 1rem;
}
</style>