<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="GoodsTransferForm" ref="ruleFormRef" :rules="rules" label-width="auto"
            style="max-width: 600px">
            <el-form-item prop="inventory_time" label="调拨时间:" class="change-form-item">
                <span>{{ GoodsTransferForm.transfer_time }}</span>
                <!-- <el-date-picker v-model="GoodsTransferForm.inventory_time" style="width: 170px" size="small"
                    type="datetime" placeholder="Select date and time" :default-time="defaultTime" /> -->
            </el-form-item>
            <el-form-item prop="out_warehouse_id" label="调出仓库:" class="change-form-item">
                <span>{{ warehouseName(GoodsTransferForm.out_warehouse_id) }}</span>
            </el-form-item>
            <el-form-item label="调入仓库:" prop="in_warehouse_id" class="change-form-item">
                <span> {{ warehouseName(GoodsTransferForm.in_warehouse_id) }}</span>
            </el-form-item>
            <el-form-item label="配送方式:" prop="creator_id" class="change-form-item">
                <span>{{ getadminList(GoodsTransferForm.send_type) }}</span>
            </el-form-item>
            <el-form-item label="备注:" prop="remark" class="change-form-item">
                <span>{{ GoodsTransferForm.remark }}</span>
            </el-form-item>
            <el-table :data="GoodsTransferForm.product_list" style="width: 100%">
                <el-table-column prop="goods_vo.name" label="商品名称" />
                <el-table-column prop="product_vo.sku" label="SKU" />
                <el-table-column prop="use_able_num" label="库存数量" />
                <el-table-column prop="num" label="调拨数量" />
            </el-table>
        </el-form>
        <div class="flex justify-center mt-4">

            <el-button type="primary" size="large" @click="goBack()">返回</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, allocationAPI } from '@/api/api'
//引入
import Vue3Barcode from 'vue3-barcode'
//定义要生成条形码的值
import { ElMessage, FormRules, FormInstance } from 'element-plus'
const appointment_time = ref('')
const defaultTime = new Date()
let dialogVisible = ref(false)
const tableData = ref([])
let barcodeValue = ref('')
const router = useRouter();
const route = useRoute()
const activeTab = ref('basic-info');
const id = ref(route.params.id);
const GoodsTransferForm: any = reactive({
    out_warehouse_id: '',
    in_warehouse_id: '',
    product_list: [],
    send_type: '',
    remark: '',
    transfer_time: '',
})
interface RuleForm {
    out_warehouse_id: string,
    type: string
}
const ruleFormRef = ref<FormInstance>()
//校验表单
const rules = reactive<FormRules<RuleForm>>({
    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 deliveryTypeList:any=ref('')
const adminList: any = ref([])
watch(activeTab, (newValue, oldValue) => {
    console.log(`Tab changed from ${oldValue} to ${newValue}`);
    // 这里可以添加一些逻辑，但要确保不会再次修改 activeTab
});


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

const scanCode = () => {
    dialogVisible.value = true
    nextTick(() => {
        if (inputRef.value && inputRef.value.focus) {
            inputRef.value.focus();
        } else {
            console.error('Input reference is not available');
        }
    });
};
// 格式化日期时间为本地格式
function formatDate(date) {
    const y = date.getFullYear();
    const m = date.getMonth() + 1; // 月份是从0开始的
    const d = date.getDate();
    const hr = date.getHours();
    const min = date.getMinutes();
    const sec = date.getSeconds();
    return `${y}-${pad(m)}-${pad(d)} ${pad(hr)}:${pad(min)}:${pad(sec)}`;
}

// 补零函数
function pad(n) {
    return n < 10 ? '0' + n : n;
}
/* const getOrderNumber = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (!GoodsTransferForm.product_list.length) {
                ElMessage.error("请选择商品！");
                return;
            }
            GoodsTransferForm.product_list.map(el => {
                el.diff_num = el.usable_stock - el.inventory_num
            })
            GoodsTransferForm.inventory_time = formatDate(GoodsTransferForm.inventory_time)
            inventoryAPI.editInventory(id.value, GoodsTransferForm).then(res => {
                ElMessage.success("保存成功！");
                router.replace({
                    name: 'Inventory',
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}; */

const ship = () => {
    console.log('发货');
};
const init = async () => {
    try {
        const res: any = await allocationAPI.getstockTransfer(id.value);
        /*  res.data.product_list.map(el => {
             if (!el.sn_code_list) {
                 el.sn_code_list = []
             }
         }) */
        GoodsTransferForm.out_warehouse_id = res.data.out_warehouse_id;
        GoodsTransferForm.in_warehouse_id = res.data.in_warehouse_id;
        GoodsTransferForm.send_type = res.data.send_type;
        GoodsTransferForm.remark = res.data.remark;
        GoodsTransferForm.transfer_time = res.data.transfer_time;
        GoodsTransferForm.product_list = res.data.product_list;
        console.log(GoodsTransferForm);
    } 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) {
        const type = warehouseList.value.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) {
        const type = typeList.value.find(type => type.id === 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 getadminList = (value) => {
    if (value && deliveryTypeList.value && deliveryTypeList.value.data && deliveryTypeList.value.data.data) {
        // Access orderTypeList directly from the component's data
        const type = deliveryTypeList.value.data.data.find(type => type.id === value);
        return type ? type.name : '未知类型';
    }
}
/* 获取仓库,字典,客户信息 */
const getInforList = async () => {
    const warehouseData: any = await infoApi.warehouseList({})//获取仓库列表
    warehouseList.value = warehouseData.data
    customerList.value = await infoApi.customer({})//获取客户列表
    adminList.value = await infoApi.getAdmin({
        page_no: 1,
        page_size: 9999,
        user_state: 0
    })//获取管理员列表
    console.log(adminList);
    collectingAccountList.value = await infoApi.collectingAccount({})//获取支付方式列表
    const typeData: any = await dictionaryAPI.getPage({ dictType: "inventory_type" })//获取配送方式
    typeList.value = typeData.data.data
    orderTypeList.value = await dictionaryAPI.getPage({ dictType: "Sale_order_send_status" })//获取订单状态
    deliveryTypeList.value=await infoApi.getExpressList({//获取物流公司
        page_no: 1,
        page_size: 9999,
    })
}
</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>