<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="仓库" prop="warehouse_id">
                    <el-input
                        v-model="formData.warehouse_name"
                        clearable
                        placeholder="请选择仓库"
                        :readonly="false"
                        @click="showWarehouse = true"
                    />
                </el-form-item>
                <el-form-item label="商品" prop="product_id">
                    <el-input
                        v-model="formData.product_name"
                        clearable
                        placeholder="请选择商品"
                        :readonly="false"
                        @click="showProduct = true"
                    />
                </el-form-item>
                <el-form-item label="供应商" prop="supplier_id">
                    <el-select
                        v-model="formData.supplier_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="输入供应商名称搜索"
                        remote-show-suffix
                        :remote-method="remoteMethodUser"
                        :loading="userloading"
                        style="width: 240px"
                    >
                        <el-option
                            v-for="item in userList"
                            :key="item.id"
                            :label="item.mer_name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="financial_pm">
                    <el-select v-model="formData.financial_pm" clearable placeholder="请选择出入库">
                        <el-option label="入库" value="1" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="批次" prop="batch">
                    <el-input
                        v-model="formData.batch"
                        clearable
                        placeholder="请输入批次"
                        :readonly="false"
                    />
                </el-form-item> -->
                <el-form-item label="单号" prop="code">
                    <el-input
                        v-model="formData.code"
                        clearable
                        placeholder="请输入单号"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="生产日期" prop="manufacture">
                    <el-date-picker
                        :readonly="false"
                        class="flex-1 !flex"
                        v-model="formData.manufacture"
                        clearable
                        type="datetime"
                        value-format="YYYY-MM-DD"
                        placeholder="选择生产日期"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="保质期" prop="expiration_date">
                    <el-date-picker
                        :readonly="false"
                        class="flex-1 !flex"
                        v-model="formData.expiration_date"
                        clearable
                        type="datetime"
                        value-format="YYYY-MM-DD"
                        placeholder="选择保质期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="数量" prop="nums">
                    <el-input
                        v-model="formData.nums"
                        clearable
                        placeholder="请输入数量"
                        :readonly="false"
                        @change="changePrice"
                    />
                </el-form-item>
                <el-form-item>
                    <span style="color: red">注意:下面价格会同步到商品中，请仔细检查</span>
                </el-form-item>

                <el-form-item label="采购价" prop="purchase">
                    <el-input
                        v-model="formData.purchase"
                        clearable
                        placeholder="请输入采购价"
                        :readonly="false"
                        @change="changePrice"
                    />
                </el-form-item>
                <!-- <el-form-item label="商户价" prop="cost">
                    <el-input
                        v-model="formData.cost"
                        clearable
                        placeholder="请输入商户价"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="零售价" prop="price">
                    <el-input
                        v-model="formData.price"
                        clearable
                        placeholder="请输入零售价"
                        :readonly="false"
                    />
                </el-form-item> -->
                <el-form-item label="总价" prop="total_price">
                    <el-input
                        v-model="formData.total_price"
                        clearable
                        placeholder="请输入总价"
                        :readonly="false"
                    />
                </el-form-item>
            </el-form>
        </popup>
        <el-dialog v-model="showWarehouse" title="选择仓库" width="70%">
            <warehouse-pop @onBindWarehouse="onBindWarehouse"></warehouse-pop>
        </el-dialog>
        <el-dialog v-model="showProduct" title="选择商品" width="70%">
            <product-pop @onBindStore="onBindStore"></product-pop>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="warehouseProductEdit">
import { watermarkProps, type FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {
    apiWarehouseProductAdd,
    apiWarehouseProductEdit,
    apiWarehouseProductDetail
} from '@/api/warehouse_product'
import { apiSupplierLists } from '@/api/supplier'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showWarehouse = ref(false) // 选择仓库列表是否显示
const showProduct = ref(false) // 选择商品列表是否显示
// const productList = ref([])

const onBindWarehouse = (e: any[]) => {
    formData.warehouse_name = e.name
    formData.warehouse_id = e.id
    // e.forEach((item: any) => {
    //     if (!productList.value.find((t: any) => t.id == item.id)) {
    //         productList.value.push(item)
    //     }
    // })
    showWarehouse.value = false
}
const onBindStore = (e: any[]) => {
    formData.product_name = e[0].store_name
    formData.product_id = e[0].id
    formData.purchase = e[0].purchase
    formData.cost = e[0].cost
    formData.price = e[0].price
    showProduct.value = false
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑商品仓储信息' : '新增商品仓储信息'
})

// 表单数据
const formData = reactive({
    id: '',
    warehouse_id: '',
    product_id: '',
    supplier_id: '',
    financial_pm: '',
    batch: '',
    nums: '',
    price: '',
    total_price: '',
    status: '',
    warehouse_name: '',
    product_name: '',
    manufacture: '',
    expiration_date: '',
    code: '',
    purchase: '',
    cost: ''
})

// 表单验证
const formRules = reactive<any>({
    warehouse_id: [
        {
            required: true,
            message: '请输入仓库ID',
            trigger: ['blur']
        }
    ],
    product_id: [
        {
            required: true,
            message: '请输入商品ID',
            trigger: ['blur']
        }
    ],
    financial_pm: [
        {
            required: true,
            message: '请选择0 = 出库 1 = 获得',
            trigger: ['blur']
        }
    ],
    batch: [
        {
            required: true,
            message: '请输入批次',
            trigger: ['blur']
        }
    ],
    nums: [
        {
            required: true,
            message: '请输入数量',
            trigger: ['blur']
        }
    ],
    price: [
        {
            required: true,
            message: '请输入零售价',
            trigger: ['blur']
        }
    ],
    purchase: [
        {
            required: true,
            message: '请输入采购价',
            trigger: ['blur']
        }
    ],
    cost: [
        {
            required: true,
            message: '请输入商户价',
            trigger: ['blur']
        }
    ],
    total_price: [
        {
            required: true,
            message: '请输入总价',
            trigger: ['blur']
        }
    ],
    status: [
        {
            required: true,
            message: '请输入状态',
            trigger: ['blur']
        }
    ]
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiWarehouseProductDetail({
        id: row.id
    })
    setFormData(data)
}
const changePrice = () => {
    if (formData.purchase > 0 && formData.nums > 0) {
        formData.total_price = formData.purchase * formData.nums
    }
}
// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData }
    mode.value == 'edit' ? await apiWarehouseProductEdit(data) : await apiWarehouseProductAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}
const userloading = ref(false)
const userList = ref([])
const remoteMethodUser = (e = '') => {
    userloading.value = true
    apiSupplierLists({})
        .then((res) => {
            userList.value = res.lists
            setTimeout(() => {
                userloading.value = false
            }, 300)
        })
        .catch((err) => {
            setTimeout(() => {
                userloading.value = false
            }, 300)
        })
}
defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
