<template>
    <div class="edit-popup">
        <el-drawer title="商品详情" :size="1200" v-model="isOpen">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="基础信息" name="first">
                    <el-descriptions class="margin-top" :column="2" border>
                        <el-descriptions-item label="商品名称">
                            {{ formData.store_name }}
                        </el-descriptions-item>
                        <el-descriptions-item label="商品分类">{{
                            formData.cate_name
                        }}</el-descriptions-item>
                        <el-descriptions-item label="商品图片" :span="2">
                            <el-image
                                :src="formData.image"
                                class="w-20 h-20"
                                :preview-teleported="true"
                            />
                        </el-descriptions-item>
                        <el-descriptions-item label="商品条码">
                            {{ formData.bar_code }}
                        </el-descriptions-item>
                        <el-descriptions-item label="商品售价">{{
                            formData.price
                        }}</el-descriptions-item>
                        <el-descriptions-item label="商品单位">{{
                            formData.unit_name
                        }}</el-descriptions-item>
                        <el-descriptions-item label="库存">{{
                            formData.stock
                        }}</el-descriptions-item>
                        <el-descriptions-item label="成本">{{
                            formData.cost
                        }}</el-descriptions-item>
                        <el-descriptions-item label="供货价">{{
                            formData.purchase
                        }}</el-descriptions-item>
                        <el-descriptions-item label="上浮比例" :span="2">{{
                            formData.rose
                        }}</el-descriptions-item>
                        <el-descriptions-item label="厂家备注" :span="2">
                            <div style="white-space: pre">
                                {{ formData.manufacturer_information }}
                            </div>
                            <!-- <div style="white-space: pre;">{{ cMark(formData.manufacturer_information) }}</div> -->
                        </el-descriptions-item>
                    </el-descriptions>
                </el-tab-pane>
                <el-tab-pane label="适用门店" name="second">
                    <el-table :data="pager.lists" border>
                        <el-table-column
                            label="门店名称"
                            prop="system_store_name"
                            min-width="200"
                        />
                        <el-table-column
                            label="商品图"
                            prop="image"
                            width="80"
                            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="store_name" min-width="150" />
                        <el-table-column label="商品库存" prop="stock" show-overflow-tooltip />
                        <el-table-column label="商品价格" prop="price" show-overflow-tooltip />
                        <el-table-column label="商品销量" prop="sales" show-overflow-tooltip />
                        <el-table-column label="操作" fixed="right" v-if="isEidt">
                            <template #default="{ row }">
                                <el-button
                                    v-perms="['store_product.store_product/delete']"
                                    type="danger"
                                    link
                                    @click="handleDelete(row.store_id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="分配库存"
                            fixed="right"
                            v-if="isEidtStock"
                            min-width="150"
                        >
                            <template #default="{ row }">
                                <el-input-number
                                    v-model="row.new_stock"
                                    :min="1"
                                    @change="handleChange(row)"
                                />
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="操作" fixed="right" v-if="!isEidt && !isEidtStock">
                            <template #default="{ row }">
                                <el-button v-perms="['store_product.store_product/update']" type="primary" link
                                    @click="updatePrice(row)">
                                    修改价格
                                </el-button>
                            </template>
                        </el-table-column> -->
                    </el-table>
                    <div class="flex mt-4 justify-end" v-if="pager.count > pager.lists.length">
                        <pagination v-model="pager" @change="getLists" />
                    </div>
                </el-tab-pane>
                <el-tab-pane label="仓库" name="warehouse">
                    <el-table :data="warehouseProductList">
                        <el-table-column label="仓库" prop="warehouse_name" min-width="150" />
                        <el-table-column
                            label="商品图"
                            prop="image"
                            width="80"
                            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="store_name" min-width="150" />
                        <el-table-column label="商品库存" prop="nums" show-overflow-tooltip />
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-drawer>
        <el-dialog v-model="showStore" title="选择门店" width="70%">
            <store-pop @onBindStore="onBindStore"></store-pop>
        </el-dialog>
        <el-dialog v-model="dialogFormVisible" title="编辑价格" width="500">
            <el-form :model="formPrice">
                <el-form-item label="价格">
                    <el-input
                        v-model="formPrice.price"
                        placeholder="请输入价格"
                        autocomplete="off"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="onUpdatePrice"> 确认 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="storeProductDETAILS">
import { usePaging } from '@/hooks/usePaging'
import { ElMessage, type FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiStoreProductAdd, apiStoreProductEdit, apiStoreProductDetail } from '@/api/store_product'
import { timeFormat } from '@/utils/util'
import {
    apiSourceProductStoreLists,
    apiSourceProductUpdateStore,
    apiStoreBranchProductEdit,
    apiStoreBranchProductEditPrice
} from '@/api/system_store'
import { apiWarehouseProductStoregeLists } from '@/api/warehouse_product_storege'
import type { PropType } from 'vue'
import feedback from '@/utils/feedback'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const isOpen = ref(false)
const activeName = ref('first')
const handleClick = (tab: any) => {
    if (tab.paneName == 'second') getLists()
    if (tab.paneName == 'warehouse') getWarehouseProductList()
}

// 表单数据
const formData = reactive({
    id: '',
    image: '',
    store_name: '',
    bar_code: '',
    cate_id: '',
    cate_name: '',
    price: '',
    unit: '',
    unit_name: '',
    stock: '',
    cost: '',
    purchase: '',
    rose: '0',
    manufacturer_information: ''
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    queryParams.product_id = data.id
    if (activeName.value == 'second') getLists()
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const cMark = (str: any) => {
    if (str) {
        return str.replace(/(\d{5,})/g, (match: string) => {
            let replacement
            // 判断数字长度，执行不同替换逻辑
            if (match.length >= 11) {
                // 对于11位以上的连续数字，替换倒数第四到倒数第八位为星号
                replacement = match.slice(0, -8) + '****' + match.slice(-4)
            } else {
                // 对于5到11位的数字，替换最后四位为星号
                replacement = match.slice(0, -4) + '****'
            }
            return replacement
        })
    }
    return '-'
}

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

//打开弹窗
const open = () => {
    isOpen.value = true
    addList.clear()
    removeList.clear()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

// 查询条件
const queryParams = reactive({
    product_id: ''
})
// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiSourceProductStoreLists,
    params: queryParams
})

const addList = new Map() // 添加列表
const removeList = new Map() // 删除列表
const isEidt = ref(false) //正在编辑
const showStore = ref(false)
const onBindStore = (e: any) => {
    e.filter((item: any) => {
        return !pager.lists.find((t) => t.store_id == item.id)
    }).map((item: any) => {
        pager.lists.unshift({
            store_id: item.id,
            system_store_name: item.name,
            stock: 0,
            cost: 0,
            price: 0,
            sales: 0
        })
        addList.set(item.id, (addList.get(item.id) || 0) + 1)
        removeList.set(item.id, (removeList.get(item.id) || 0) - 1)
    })
    showStore.value = false
}

const handleDelete = (store_id: number) => {
    pager.lists = pager.lists.filter((item) => item.store_id != store_id)
    addList.set(store_id, (addList.get(store_id) || 0) - 1)
    removeList.set(store_id, (removeList.get(store_id) || 0) + 1)
}

// 修改适用门店
const submitStore = () => {
    feedback
        .confirm('确定修改适用门店吗?')
        .then(async () => {
            const add = Array.from(addList.entries())
                .filter(([k, v]) => v == 1)
                .map(([key]) => key)
            const remove = Array.from(removeList.entries())
                .filter(([k, v]) => v == 1)
                .map(([key]) => key)
            console.log(add, remove)
            if (add.length == 0 && remove.length == 0) return ElMessage.warning('没有更改门店')
            apiSourceProductUpdateStore({
                addList: add,
                removeList: remove,
                product_id: queryParams.product_id
            }).then((res) => {
                isEidt.value = false
                addList.clear()
                removeList.clear()
            })
        })
        .catch(() => {
            // on cancel
        })
}

// 库存相关
const isEidtStock = ref(false)
const stockList = ref(new Map())
const handleChange = (row: any) => {
    stockList.value.set(row.id, row.new_stock)
}
const submitStock = () => {
    feedback
        .confirm('确定修改库存吗?')
        .then(async () => {
            const data = Array.from(stockList.value.entries()).map(([key, value]) => {
                return {
                    id: key,
                    stock: value
                }
            })
            apiStoreBranchProductEdit({
                data
            }).then((res) => {
                isEidtStock.value = false
                stockList.value.clear()
                getLists()
            })
        })
        .catch(() => {
            // on cancel
        })
}

// 编辑门店价格
const dialogFormVisible = ref(false)
const formPrice = ref({
    id: '',
    price: ''
})
const updatePrice = (row: any) => {
    formPrice.value.id = row.id
    formPrice.value.price = row.price
    dialogFormVisible.value = true
}
const onUpdatePrice = () => {
    if (!formPrice.value.price) return ElMessage.warning('请输入价格')
    apiStoreBranchProductEditPrice(formPrice.value).then(() => {
        dialogFormVisible.value = false
        getLists()
    })
}
const warehouseProductList = ref([])
const getWarehouseProductList = () => {
    apiWarehouseProductStoregeLists(queryParams).then((res) => {
        warehouseProductList.value = res.lists
    })
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
