<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-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane label="基础信息" name="info">
                        <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="product_type">
                            <el-radio-group
                                v-model="formData.product_type"
                                :disabled="mode != 'add'"
                            >
                                <el-radio :label="0">普通产品</el-radio>
                                <el-radio :label="1">供销系列产品</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="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="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-tab-pane>
                    <el-tab-pane label="商品规格" name="spec">
                        <el-form-item label="规格类型">
                            <el-radio-group v-model="formData.spec_type">
                                <el-radio :label="0">单规格</el-radio>
                                <el-radio :label="1">多规格</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <template v-if="formData.spec_type == 0">
                            <el-form-item label="规格名称" prop="sku_name">
                                <el-input
                                    v-model="productData.sku_name"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入规格名称"
                                    :readonly="false"
                                />
                            </el-form-item>
                            <el-form-item label="商品单位" prop="unit">
                                <el-cascader
                                    class="w-[500px]"
                                    v-model="productData.unit"
                                    :options="unitList"
                                    :props="{
                                        value: 'id',
                                        label: 'name',
                                        emitPath: false
                                    }"
                                    placeholder="请选择商品单位"
                                />
                            </el-form-item>
                            <el-form-item label="供货价" prop="purchase">
                                <el-input
                                    v-model="productData.purchase"
                                    type="number"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入供货价"
                                    :readonly="false"
                                />
                            </el-form-item>
                            <el-form-item label="商户价" prop="cost">
                                <el-input
                                    v-model="productData.cost"
                                    type="number"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入商户价"
                                    :readonly="false"
                                />
                            </el-form-item>
                            <el-form-item label="会员价" prop="vip_price">
                                <el-input
                                    v-model="productData.vip_price"
                                    type="number"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入会员价"
                                    :readonly="false"
                                />
                            </el-form-item>
                            <el-form-item label="终端零售价" prop="price">
                                <el-input
                                    v-model="productData.price"
                                    type="number"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入终端零售价"
                                    :readonly="false"
                                />
                            </el-form-item>
                            <el-form-item label="零售起批量" prop="batch">
                                <el-input
                                    v-model="productData.batch"
                                    type="number"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入零售起批量"
                                    :readonly="false"
                                />
                            </el-form-item>
                            <el-form-item label="门店起批量" prop="store_batch">
                                <el-input
                                    v-model="productData.store_batch"
                                    type="number"
                                    class="w-[500px]"
                                    clearable
                                    placeholder="请输入门店起批量"
                                    :readonly="false"
                                />
                            </el-form-item>
                        </template>
                        <template v-if="formData.spec_type == 1">
                            <el-form-item>
                                <el-button @click="addRow" class="mb-2">添加规格</el-button>
                                <el-table :data="tableData" style="width: 100%">
                                    <!-- 下拉选择列 -->
                                    <el-table-column label="单位" width="180">
                                        <template v-slot="scope">
                                            <el-select
                                                v-model="scope.row.unit"
                                                placeholder="请选择单位"
                                                v-if="scope.row.editable"
                                            >
                                                <el-option
                                                    v-for="item in unitList"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                />
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        v-for="(column, index) in columns"
                                        :key="index"
                                        :prop="column.prop"
                                        :label="column.label"
                                        :width="column.width"
                                    >
                                        <template v-slot="scope">
                                            <el-input
                                                v-model="scope.row[column.prop]"
                                                v-if="scope.row.editable"
                                            />
                                            <span v-else>{{ scope.row[column.prop] }}</span>
                                        </template>
                                    </el-table-column>

                                    <el-table-column label="操作" width="100">
                                        <template v-slot="scope">
                                            <el-button type="text" @click="deleteRow(scope.$index)"
                                                >删除</el-button
                                            >
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>
                        </template>
                    </el-tab-pane>
                    <el-tab-pane label="适用门店" name="store">
                        <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-tab-pane>
                </el-tabs>
                <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'
import type { TabsPaneContext } from 'element-plus'

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

const { removeTab } = useMultipleTabs()
const mode = ref('add')
const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}
const filterStockName = (e: any) => {
    let str = '库存'
    if (e == 1) str = '供销库存'
    if (e == 2) str = '兑换库存'
    if (e == 3) str = '赠品库存'
    return str
}

const tableData = ref([])
const productData = ref([])
const columns = ref([
    { label: '规格名称', prop: 'sku_name', width: '180' },
    { label: '供货价', prop: 'purchase', width: '180' },
    { label: '商户价', prop: 'cost', width: '180' },
    { label: '零售价', prop: 'price', width: '180' },
    { label: '条码', prop: 'bar_code', width: '180' }
])

const addRow = () => {
    tableData.value.push({
        sku_name: '',
        purchase: 0,
        cost: 0,
        price: 0,
        bar_code: '',
        editable: true
    })
}

const deleteRow = (index) => {
    tableData.value.splice(index, 1)
}
// 表单数据
const formData = reactive({
    id: '',
    image: '',
    store_name: '',
    store_info: '',
    product_type: 0,
    cate_arr: [],
    cate_id: '',
    swap: '',
    batch: 1,
    store_batch: 1,
    manufacturer_information: '',
    rose: '0',
    is_return: 1, // 1支持退货,2不支持退货
    is_store_all: 1, //门店类型 1 全部门店 2 部分门店,
    spec_type: 0
})

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']
        }
    ],
    store_info: [
        {
            required: true,
            message: '请输入商品规格',
            trigger: ['blur']
        }
    ],
    cate_id: [
        {
            required: true,
            message: '请输入商品分类',
            trigger: ['blur', 'change']
        }
    ],
    cate_arr: [
        {
            required: true,
            message: '请选择商品分类',
            trigger: ['blur', 'change']
        }
    ],
    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]
    delete data.cate_arr
    const product_arr = ref([])
    if (formData.spec_type == 0) {
        product_arr.value = productData.value
    } else {
        product_arr.value = tableData.value.map((item: any) => {
            return {
                sku_name: item.sku_name,
                unit: item.unit,
                purchase: item.purchase,
                cost: item.cost,
                price: item.price,
                bar_code: item.bar_code
            }
        })
    }
    data.product_arr = product_arr.value
    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>
