<template>
    <el-card>
        <div class="mb-4 text-lg font-bold">
            {{ mode == 'add' ? '添加商品' : '编辑商品' }}
        </div>
        <div>
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="商品图片" prop="image">
                    <material-picker v-model="formData.image" :limit="1" />
                </el-form-item>
                <el-form-item label="商品名称" prop="store_name">
                    <el-input
                        v-model="formData.store_name"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入商品名称"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="商品条码" prop="bar_code">
                    <el-input
                        v-model="formData.bar_code"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入商品条码"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="商品规格" prop="store_info">
                    <el-input
                        v-model="formData.store_info"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入商品规格"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="商品类型" prop="product_type">
                    <el-radio-group v-model="formData.product_type" :disabled="mode != 'add'">
                        <el-radio :label="0">普通产品</el-radio>
                        <el-radio :label="4">活动产品</el-radio>
                        <el-radio :label="5">批发产品</el-radio>
                        <el-radio :label="2">兑换产品</el-radio>
                        <el-radio :label="3">赠品</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品分类" prop="cate_arr">
                    <el-cascader
                        class="w-[500px]"
                        v-model="formData.cate_arr"
                        filterable
                        clearable
                        :before-filter="beforeFilter"
                        :props="props"
                        placeholder="请选择商品分类"
                    />
                </el-form-item>
                <el-form-item label="商品单位" prop="unit">
                    <el-cascader
                        class="w-[500px]"
                        v-model="formData.unit"
                        :options="unitList"
                        :props="{
                            value: 'id',
                            label: 'name',
                            emitPath: false
                        }"
                        placeholder="请选择商品单位"
                    />
                </el-form-item>
                <!-- <el-form-item :label="filterStockName(formData.product_type)" prop="stock">
                    <el-input
                        v-model="formData.stock"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入库存"
                        :readonly="false"
                    />
                </el-form-item> -->
                <!-- <el-form-item label="兑换库存" prop="swap">
                <el-input v-model="formData.swap" type="number" class="w-[500px]" clearable placeholder="请输入库存" :readonly="false" />
            </el-form-item> -->
                <el-form-item label="供货价" prop="purchase">
                    <el-input
                        v-model="formData.purchase"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入供货价"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="商户价" prop="cost">
                    <el-input
                        v-model="formData.cost"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入商户价"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="会员价" prop="vip_price">
                    <el-input
                        v-model="formData.vip_price"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入会员价"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="终端零售价" prop="price">
                    <el-input
                        v-model="formData.price"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入终端零售价"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="起批量" prop="batch">
                    <el-input
                        v-model="formData.batch"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入零售起批量"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="厂家备注" prop="manufacturer_information">
                    <el-input
                        v-model="formData.manufacturer_information"
                        type="textarea"
                        autosize
                        class="w-[500px]"
                        clearable
                        :placeholder="`厂家名称\n联系人姓名\n联系电话`"
                        :readonly="false"
                    />
                </el-form-item>
                <el-form-item label="毛利率" prop="rose">
                    <el-input-number
                        v-model="formData.rose"
                        type="number"
                        class="w-[500px]"
                        clearable
                        placeholder="请输入毛利率"
                        :readonly="false"
                    >
                        <template #suffix>%</template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="退货" prop="is_return">
                    <el-radio-group v-model="formData.is_return">
                        <el-radio :label="1">支持</el-radio>
                        <el-radio :label="0">不支持</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="is_show">
                    <el-radio-group v-model="formData.is_show">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="所属门店" prop="store_id" v-if="mode == 'add'">
                    <el-radio-group v-model="formData.is_store_all">
                        <el-radio :label="1">全部门店</el-radio>
                        <el-radio :label="0">部分门店</el-radio>
                    </el-radio-group>
                    <div class="w-full" style="color: #64748b">可选择将商品同步到哪些门店使用</div>
                    <div class="mb-2">
                        <el-button
                            type="primary"
                            v-if="formData.is_store_all == 0"
                            @click="showStore = true"
                            >添加门店</el-button
                        >
                    </div>
                    <el-table :data="storeList" v-if="formData.is_store_all == 0">
                        <el-table-column label="ID" prop="id" show-overflow-tooltip />
                        <el-table-column label="门店名称" prop="name" show-overflow-tooltip />
                        <el-table-column label="手机号码" prop="phone" show-overflow-tooltip />
                        <el-table-column
                            label="详细地址"
                            prop="detailed_address"
                            show-overflow-tooltip
                        />
                        <el-table-column label="门店logo" prop="image" show-overflow-tooltip>
                            <template #default="{ row }">
                                <el-image
                                    :src="row.image"
                                    class="w-[50px] h-[50px]"
                                    :preview-teleported="true"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="营业状态" prop="is_show" show-overflow-tooltip>
                            <template #default="{ row }">
                                {{ row.is_show ? '营业' : '打烊' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120" fixed="right">
                            <template #default="{ row }">
                                <el-button
                                    v-perms="['system_store.system_store/delete']"
                                    type="danger"
                                    link
                                    @click="handleDelete(row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="handleSubmit" type="primary" class="w-40">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-dialog v-model="showStore" title="选择门店" width="70%">
            <store-pop @onBindStore="onBindStore"></store-pop>
        </el-dialog>
    </el-card>
</template>

<script lang="ts" setup name="storeProductEdit">
import { ElMessage, type FormInstance } from 'element-plus'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import { apiStoreProductAdd, apiStoreProductEdit, apiStoreProductDetail } from '@/api/store_product'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiStoreCategoryLists } from '@/api/store_category'
import { apiStoreProductUnitLists } from '@/api/store_product_unit'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const { removeTab } = useMultipleTabs()
const mode = ref('add')

const filterStockName = (e: any) => {
    let str = '库存'
    if (e == 1) str = '供销库存'
    if (e == 2) str = '兑换库存'
    if (e == 3) str = '赠品库存'
    return str
}

// 表单数据
const formData = reactive({
    id: '',
    image: '',
    store_name: '',
    bar_code: '',
    store_info: '',
    product_type: 0,
    cate_arr: [],
    cate_id: '',
    price: '',
    vip_price: '',
    unit: '',
    stock: '',
    swap: '',
    cost: '',
    purchase: '',
    batch: 1,
    store_batch: 1,
    manufacturer_information: '',
    rose: '0',
    is_return: 1, // 1支持退货,2不支持退货
    is_store_all: 1, //门店类型 1 全部门店 2 部分门店
    is_show: 1
})

// 定义验证输入的函数
// const validateInput = () => {
//     // 获取输入框的当前值
//     const inputValue = formData.bar_code

//     // 使用正则表达式仅保留英文和数字
//     const filteredValue = inputValue.replace(/[^a-zA-Z0-9]/g, '')

//     // 更新输入框的值
//     formData.bar_code = filteredValue
// }

const showStore = ref(false) // 选择门店列表是否显示
// 门店列表
const storeList = ref([])
// 删除已有门店
const handleDelete = (id: number) => {
    storeList.value = storeList.value.filter((item: any) => item.id !== id)
}
// 选择门店
const onBindStore = (e: any[]) => {
    e.forEach((item: any) => {
        if (!storeList.value.find((t: any) => t.id == item.id)) {
            storeList.value.push(item)
        }
    })
    showStore.value = false
}

let resolves
let nodes
const flag = ref(false)
let name
onMounted(() => {
    // setTimeout(() => {
    //     let dom = document.getElementsByClassName('caser')[0]
    //     let ipt = dom.getElementsByClassName('el-input__inner')[0]
    //     ipt.addEventListener('input', (e) => {
    //         beforeFilter(e.target.value)
    //     })
    // })
})

const beforeFilter = (value) => {
    name = value
    flag.value = true
    props.lazyLoad(nodes, resolves)
    return false
}
const props = {
    value: 'id',
    label: 'name',
    lazy: true,
    lazyLoad(node, resolve) {
        if (!resolves) resolves = resolve
        if (!nodes) nodes = node
        const pid = node.value || 0
        let data = {}
        if (flag.value) {
            data = { name: name }
            if (!name) {
                data = {
                    pid: pid,
                    page_size: 10000
                }
            }
        } else {
            data = {
                pid: pid,
                page_size: 10000
            }
        }
        apiStoreCategoryLists({
            ...data
        }).then((res) => {
            resolve(
                res.lists.map((item: any) => {
                    item.leaf = item.is_children == 0
                    flag.value = false
                    return item
                })
            )
        })
    }
}

const unitList = ref([])
const getUnitList = () => {
    apiStoreProductUnitLists({}).then((res) => {
        unitList.value = res.lists
    })
}
getUnitList()

// 表单验证
const formRules = reactive<any>({
    store_name: [
        {
            required: true,
            message: '请输入商品名称',
            trigger: ['blur']
        }
    ],
    bar_code: [
        {
            required: true,
            message: '请输入商品条码',
            trigger: ['blur']
        }
    ],
    store_info: [
        {
            required: true,
            message: '请输入商品规格',
            trigger: ['blur']
        }
    ],
    cate_id: [
        {
            required: true,
            message: '请输入商品分类',
            trigger: ['blur', 'change']
        }
    ],
    cate_arr: [
        {
            required: true,
            message: '请选择商品分类',
            trigger: ['blur', 'change']
        }
    ],
    price: [
        {
            required: true,
            message: '请输入终端零售价',
            trigger: ['blur']
        }
    ],
    vip_price: [
        {
            required: true,
            message: '请输入会员价',
            trigger: ['blur']
        }
    ],
    unit: [
        {
            required: true,
            message: '请输入商品单位',
            trigger: ['blur', 'change']
        }
    ],
    stock: [
        {
            required: true,
            message: '请输入售卖库存',
            trigger: ['blur']
        }
    ],
    swap: [
        {
            required: true,
            message: '请输入兑换库存',
            trigger: ['blur']
        }
    ],
    cost: [
        {
            required: true,
            message: '请输入门店零售',
            trigger: ['blur']
        }
    ],
    purchase: [
        {
            required: true,
            message: '请输入供货价',
            trigger: ['blur']
        }
    ],
    batch: [
        {
            required: true,
            message: '请输入起批量',
            trigger: ['blur']
        }
    ],
    image: [
        {
            required: true,
            message: '请输入商品图片',
            trigger: ['blur', 'change']
        }
    ]
})

// 获取详情
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]
        }
    }
    if (formData.cate_arr[0]) {
        formData.cate_arr = formData.cate_arr.map((item: any) => Number(item))
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiStoreProductDetail({
        id: row.id
    })
    setFormData(data)
}

const router = useRouter()
const route = useRoute()

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }
    if (formData.is_store_all == 0 && mode.value == 'add') {
        data.store_arr = storeList.value.map((item: any) => item.id)
    } else if (mode.value == 'edit') data.is_store_all = 0
    if (!data.cate_arr.length) return ElMessage.error('请选择商品分类')
    data.cate_id = data.cate_arr[data.cate_arr.length - 1]
    mode.value == 'edit' ? await apiStoreProductEdit(data) : await apiStoreProductAdd(data)
    // tabsStore.removeTab('/store/store_product?page_no' + route.query.page, router)

    // removeTab()
    router.push({
        path: '/store/store_product?=',
        query: {
            page_no: route.query.page
        }
    })
}

if (route.query.id && route.query.mode == 'edit') {
    mode.value = 'edit'
    getDetail({
        id: route.query.id
    })
}
</script>

<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
</style>
