import { onLoad, onShow } from '@dcloudio/uni-app'
import { getStorage } from '@/utils/storage'
import { computed, onBeforeUnmount, ref } from 'vue'
import { store } from '@/store'
import { timeFormatD, timeFormatHMS } from '@/utils/tools'
import toast from '@/utils/toast'
import merchant from "@/api/https/merchant"
import shopping from "@/api/https/shopping"
/*************************************************
 * 商品管理
*/
function shoppingMangerFn() {
    /*************************************************
     * 数据归位，元神显现
    */
    function dataHoming() {
        skuNames.value = []
        page.value = 1
        totalCount.value = 0
    }

    /*************************************************
     * 下拉刷新数据重现
    */
    const leftBarRef = ref<any>(null)
    let onPullDownRefreshTimer: any = ''
    const triggered = ref<boolean>(false)
    function refresherrefresh() {
        triggered.value = true
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(() => {
            triggered.value = false
            dataHoming()
            oneMenuClick(isFilter.value)
            if (isFilter.value == 'hot') return
            leftBarRef.value.GetStoreCategoryMap()
        }, 500)
    }

    /*************************************************
     * 获取数据
    */
    let oldStoreID: any = 0
    onShow(() => {
        if (oldStoreID != getStorage('storeID') && oldStoreID != 0) {
            triggered.value = true
        }
        oldStoreID = getStorage('storeID')
    })

    /*************************************************
     * 默认数据
     */
    const dafauleData: Array<AnyObject> = [
        {
            categoryID: 'all',
            children: [],
            level: 1,
            name: '所有分类',
        },
        {
            categoryID: 'act',
            children: [],
            level: 1,
            name: '活动商品',
        },
        {
            categoryID: 'hot',
            children: [],
            level: 1,
            name: '畅销推荐',
        },
        {
            categoryID: 'audit',
            children: [],
            level: 1,
            name: '待审商品',
        },
    ]

    /*************************************************
     * @info 右侧主体数据
     * 获取商品数据
    */
    const statusBarHeight = ref<string>('0px') // 状态栏高度
    onLoad(async () => {
        // 获取状态栏高度
        uni.getSystemInfo({
            success: (res: any) => {
                statusBarHeight.value = res.statusBarHeight + 'px'
            }
        })
        await getSkuNames()
    })
    const keyword = ref<string>('')
    const categoryID = ref<string>('')          // 分类id
    const isAct = ref<boolean>(false)           // 是否是活动商品
    const totalCount = ref<number>(0)           // 总条数
    const skuNames = ref<Array<AnyObject>>([])  // 商品数据
    const isAudit = ref<boolean>(false)         // 商品列表判断条件
    const isHot = ref<boolean>(false)           // 商品列表判断条件
    async function getSkuNames() {
        isLoad.value = true
        let data:AnyObject = {
            categoryID: categoryID.value,
            isFocus: true,
            keyword: keyword.value,
            offset: pageSize.value * (page.value - 1),
            pageSize: pageSize.value,
            isAct: isAct.value,
            status: -1,
            storeID: getStorage('storeID')
        }
        
        if(allSaleStatus.value && allSaleStatus.value.name !== 'all')  data[allSaleStatus.value.name] = allSaleStatus.value.status

        keyFilter(data)
        let res = await shopping.get_stores_skus_for_store(data)
        if (res.code == 0) {
            totalCount.value = res.data.totalCount
            let filterData = mapskuName(res.data.skuNames || [])
            skuNames.value = skuNames.value.concat(filterData)
            if (filterData.length == 0) return toast('该分类未找到商品')
        } else {
            dataHoming()
            toast('分类查询错误')
        }
        isLoad.value = false
    }

    /*************************************************
     * 过滤对象空字段
     */
    function keyFilter(obj: AnyObject) {
        for (let key in obj) {
            if ('' + obj[key] == "" || '' + obj[key] == undefined) {
                delete obj[key]
            }
        }
        return obj
    }

    /*************************************************
     * 列表判断条件
    */
    const isNewPriceDisplay = ref<boolean>(
        store.getters['storeInfo/isNewPriceDisplay']
    )

    /*************************************************
     * 格式化数据
    */
    function mapskuName(skuNames: Array<AnyObject>) {
        let arr = skuNames.map((skuName) => {
            skuName.auditUnitPrice = skuName.auditUnitPrice
            // 是否全部不可售
            if (skuName.skus.some((item: AnyObject) => item.storeSkuStatus)) {
                skuName.skuAllnoSale = false
            } else {
                skuName.skuAllnoSale = true
            }
            // skus
            skuName.skus = skuName.skus.map((sku: AnyObject) => {
                // 价格异常请参考老版本或者在git进行查看
                sku.comparePrice = sku.price
                sku.autoSaleAt =
                    +new Date(sku.autoSaleAt) > 0 ? timeFormatHMS(sku.autoSaleAt) : 0
                return sku
            })
            return skuName
        })
        return arr
    }

    /*************************************************
     * 页面触底，加载更多数据
    */
    const page = ref<number>(1)    // 第几页
    const pageSize = ref<number>(20) // 每页条数
    const isLoad = ref<boolean>(false)  // 加载图
    function scrolltolower() {
        page.value++
        if (pageSize.value * (page.value - 1) > totalCount.value || totalCount.value < pageSize.value) {
            isLoad.value = false
        } else {
            if (isLoad.value) return
            if (isFilter.value == 'hot') return
            if (isFilter.value == 'audit') return GetStoreSkuAudit()
            getSkuNames()
        }
    }

    /*************************************************
     * 点击菜单获取数据
    */
    const isCheckoutFilter = ref<boolean>(false)
    const isFilter = ref<string | number>('')
    function oneMenuClick(catID: string | number) {
        isAct.value = false
        isHot.value = false
        isCheckoutFilter.value = false
        categoryID.value = ''
        keyword.value = ''
        isFilter.value = catID
        isAudit.value = false
        dataHoming()
        if (catID == 'all') {       // 全部商品
            isAct.value = false
            getSkuNames()
        } else if (catID == 'act') {    // 活动商品
            isAct.value = true
            getSkuNames()
        } else if (catID == 'hot') {    // 畅销商品
            isHot.value = true
            isCheckoutFilter.value = true
            getTopSkus()
        } else if (catID == 'audit') {  // 待审核商品
            isCheckoutFilter.value = true
            isAudit.value = true
            GetStoreSkuAudit()
        } else {
            categoryID.value = catID as string
            getSkuNames()
        }
    }

    /*************************************************
     * 畅销推荐
    */
    async function getTopSkus() {
        isLoad.value = true
        let data = {
            storeID: getStorage('storeID')
        }
        let res = await shopping.get_top_skus_by_city_code(data)
        if (res.code == 0) {
            let data = res.data || []
            if (data.length > 0) {
                totalCount.value = data.length
                skuNames.value = mapskuName(data)
            } else {
                dataHoming()
                toast('暂无畅销商品')
            }

        } else {
            toast('分类查询错误')
            dataHoming()
        }
        isLoad.value = false
    }

    /*************************************************
     * 待审核商品
    */
    async function GetStoreSkuAudit() {
        isLoad.value = true
        let data = {
            storeIDs: JSON.stringify([getStorage('storeID')]),
            applyTimeStart: timeFormatD(+new Date() - 1000 * 60 * 60 * 24 * 30) + ' 00:00:00',
            applyTimeEnd: timeFormatD(+new Date()) + ' 23:59:59',
            statuss: JSON.stringify([0]),
            types: JSON.stringify([1, 2]),
            offset: pageSize.value * (page.value - 1),
            pageSize: pageSize.value,
        }
        let res = await shopping.get_store_sku_audit(data)
        if (res.code == 0) {
            totalCount.value = res.data.totalCount
            let newData = res.data.data || []
            let filterSkuName = mapAuditSkuName(newData)
            skuNames.value = skuNames.value.concat(filterSkuName)
            if (newData.length == 0) return toast('暂无待审核商品')
        } else {
            toast('分类查询错误')
            dataHoming()
        }
        isLoad.value = false
    }


    /*************************************************
     * 过滤待审核商品
    */
    function mapAuditSkuName(data: AnyObject) {
        let arr = data.map((item: any) => ({
            auditUnitPrice: item.unitPrice,
            unitPrice: item.originPrice,
            skuAllnoSale: false,
            nameID: item.nameID,
            img: item.img,
            unit: item.unit,
            type: item.type,
            prefix: item.prefix,
            name: item.skuName,
        }))
        return arr
    }


    /*************************************************
     * @info 过滤类数据
    */
    const showMountTab = ref<boolean>(false)


    /*************************************************
     * 头部数据过滤
    */
    const allSaleStatus = ref<AnyObject>()
    async function updateIsSale(data: AnyObject) {
        allSaleStatus.value = data
        data.lable == 3
            ? (showMountTab.value = true)
            : (showMountTab.value = false)
        if (data.lable == 3) return
        dataHoming()
        await getSkuNames()
    }
    async function updateTowFilter(data: AnyObject) {
        if (data.lable == 3) {
            return showMountTab.value = true
        } else {
            showMountTab.value = false
        }
        if (isFilter.value == 'hot') {
            oneMenuClick(isFilter.value)
        }

        if (isFilter.value == 'audit') {
            oneMenuClick(isFilter.value)
        }
    }

    /*************************************************
     * @info  搜索框操作
    */
    async function serachShopping(text: string) {
        dataHoming()
        keyword.value = text
        await getSkuNames()
    }
    async function clearInpu() {
        dataHoming()
        keyword.value = ''
        await getSkuNames()
    }

    /*************************************************
     * 批量操作
    */
    let picked: Array<AnyObject> = []
    function handleSale(skuName: AnyObject) {
        if (picked && picked.some((item) => item.nameID == skuName.id)) {
            picked = picked.filter((item) => {
                return item.nameID != skuName.id
            })
        } else {
            picked.push({ nameID: Number(skuName.id) })
            picked = distinct(picked, 'nameID')
        }
    }
    function distinct(arr: any, key: string) {
        let set = new Set()
        return arr.reduce(
            (p: any, c: any) => (set.has(c[key]) ? p : (set.add(c[key]), [...p, c])),
            []
        )
    }

    /*************************************************
     * 批量可售与不可售
    */
    let handleChangeSaleTimer: any = null
    const updateStateOk = ref<boolean>(false)
    async function handleChangeSale(type: number) {
        if (picked.length == 0) return toast('未选择商品')
        picked.forEach((item: AnyObject) => {
            item['isSale'] = type
        })
        let data = {
            storeIDs: JSON.stringify([getStorage('storeID')]),
            payload: JSON.stringify(picked),
        }
        let res = await shopping.update_stores_skus(data)
        if (res.code == 0) {
            toast('修改成功')
            let data = {
                status: -1,
                lable: 2,
            }
            updateStateOk.value = true
            handleChangeSaleTimer = setTimeout(() => {
                updateIsSale(data)
                clearTimeout(handleChangeSaleTimer)
            }, 1000)
        } else {
            toast('修改失败', 2)
            updateStateOk.value = false
        }
    }

    /*************************************************
     * 去创建商品
    */
    function createGoods() {
        uni.navigateTo({ url: '/subPages/shoppingChild/createGoods/createGoods' })
    }

    /*************************************************
     * 改价还是折扣（从vuex 里面读取）
     */
    const isPointStore = computed(() => {
        return store.getters['storeInfo/isPointStore']
    })
    // skuName
    const skuName = ref<AnyObject>({
        unit: '',
        auditUnitPrice: ''
    })
    function openPriceDialog(skuNames: AnyObject) {
        skuName.value = skuNames
        popup.value.open()
    }
    // 当前修改价格
    const currentValue = ref<string>('')
    // 审核价格
    const auditUnitPrice = computed(() => {
        let price = skuName.value.auditUnitPrice
        if (price) {
            return +((price * 1) / 100).toFixed(2)
        } else {
            return +'0.00'
        }
    })
    // 弹窗实例
    const popup = ref<any>(null)
    // 确定修改价格
    function handleConfirm() {
        if (isNaN(+currentValue.value)) return toast('请输入格式正确的价格')
        if (+currentValue.value < 0.01) return toast('请输入大于等于1分钱的价格')
        if (
            currentValue.value.toString().indexOf('.') > -1 &&
            currentValue.value.toString().split('.')[1].length > 2
        ) {
            return toast('最多只能有两位小数')
        }
        let updatePrice = Math.round(+currentValue.value * 100)
        if (updatePrice == skuName.value.unitPrice) {
            return toast('没有修改价格')
        }
        if (updatePrice > skuName.value.unitPrice * 1.3 ||
            updatePrice < skuName.value.unitPrice * 0.7) {
            uni.jxConfirm({
                title: '提示',
                content: `修改幅度超过30%，新价格为¥${(updatePrice / 100).toFixed(2)}，是否确定修改？`,
                success: () => {
                    updatePriceFn(updatePrice, skuName.value.id, skuName.value.unitPrice)
                }
            })
        } else {
            updatePriceFn(updatePrice, skuName.value.id, skuName.value.unitPrice)
        }
    }
    /**
     * 验证通过开始修改价格
     */
    let updatePriceFnTimer: any = null
    async function updatePriceFn(price: string | number, id: number, originalUnitPrice: number) {
        let data = {
            storeIDs: JSON.stringify([+getStorage('storeID')]),
            payload: JSON.stringify([
                {
                    nameID: skuName.value.id,
                    unitPrice: price,
                },
            ]),
        }
        popup.value.close() // 关闭 popup
        // 修改价格
        let updatePrice = await shopping.update_stores_skus(data)

        if (updatePrice.code == 0) {
            // 获取单个门店serverSkuName
            let storeData = {
                storeIDs: JSON.stringify([+getStorage('storeID')]),
                isFocus: true,
                nameIDs: JSON.stringify([id]),
                fromStatus: 0,
                toStatus: 1,
            }
            const serverSkuName = await merchant.get_stores_skus(storeData)
            if (serverSkuName.code == 0) {
                let skuNameData = serverSkuName.data.skuNames || []
                if (skuNameData.length > 0) {
                    let index = skuNames.value.findIndex((item: any) => item.id == id)
                    if (index !== -1) skuNames.value[index] = mapskuName(skuNameData)[0]
                }
            }
            // 判断提示
            if (isPointStore.value || store.state.storeInfo.allStoreInfo.storeLevel == 'E') {
                toast('修改成功')
                currentValue.value = ''
            } else {
                currentValue.value = ''
                toast(+price < originalUnitPrice ? '修改成功' : '提交成功, 请等待审核')
            }
        } else {
            toast('修改失败', 2)
        }
    }

    
    /*************************************************
     * 修该库存或货架码
    */
    const popupDialog = ref<any>(null)
    const skuNameItem = ref<AnyObject>({
        payload:{
            nameID:0,
            Skus:[],
        },
        name:'',
        type:'price'
    })
    const stockOrCode = ref('')

    // 打开dialog 修改库存以及货架码
    function openDialog(payload: AnyObject) {
        skuNameItem.value = payload
        const sku = payload.payload.Skus[0]
        if(payload.type === 'stock') stockOrCode.value = sku.stock  + ''
        if(payload.type === 'locationCode') stockOrCode.value = sku.locationCode
        popupDialog.value.open()
    }
    async function sureStockOrCode() {
        const nameID = skuNameItem.value.payload.nameID
        const skuID = skuNameItem.value.payload.Skus[0].skuID
        let data:AnyObject = {
            storeIDs: JSON.stringify([+getStorage('storeID')])
        }
        if(skuNameItem.value.type === 'stock') {
            data.payload = JSON.stringify([{
                nameID: nameID,
                Skus:[
                    {
                        skuID: skuID,
                        stock: +stockOrCode.value
                    }
                ]
            }])
        }else{
             data.payload = JSON.stringify([{
                nameID: nameID,
                Skus:[
                    {
                        skuID:skuID,
                        locationCode: ''+ stockOrCode.value ? '' + stockOrCode.value : 'EMPTY_VALUE'
                    }
                ]
            }])
        }
        popupDialog.value.close() // 关闭 popupDialog
        let res = await shopping.update_stores_skus(data)
        if (res.code == 0) {
            let storeData = {
                storeIDs: JSON.stringify([+getStorage('storeID')]),
                isFocus: true,
                nameIDs: JSON.stringify([skuNameItem.value.payload.nameID]),
                fromStatus: 0,
                toStatus: 1,
            }
            const serverSkuName = await merchant.get_stores_skus(storeData)
            if (serverSkuName.code == 0) {
                let skuNameData = serverSkuName.data.skuNames || []
                if (skuNameData.length > 0) {
                    let index = skuNames.value.findIndex((item: any) => item.id == skuNameItem.value.payload.nameID)
                    if (index !== -1) {
                        skuNames.value[index] = mapskuName(skuNameData)[0]
                    }
                }
            }
            toast('修改成功')
        }
    }

    /*************************************************
     * 删除商品
    */
    function handleDelete() {
        uni.jxConfirm({
            title: '提示',
            content: `确认删除《${skuName.value.name}》吗?`,
            confirmText: '确认',
            success: async () => {
                popup.value.close() // 关闭 popup
                let data = {
                    storeIDs: JSON.stringify([getStorage('storeID')]),
                    payload: JSON.stringify([{ nameID: skuName.value.id, isFocus: -1 }]),
                }
                let res = await shopping.update_stores_skus(data)
                if (res.code == 0) {
                    toast('删除成功')
                    skuNames.value = skuNames.value.filter((item) => item.id != skuName.value.id)
                    if (skuNames.value.length == 0) return dataHoming()
                } else {
                    toast('删除失败', 2)
                }
            }
        })
    }


    const toExamineData = ref<AnyObject>({})    // 审核商品数据
    const toExaminePopup = ref<any>(null)   // 审核弹窗实例
    const toExamineValue = ref<string | number>('')  // 审核输入框
    /*************************************************
     * 审核商品
    */
    function toExamine(res: AnyObject) {
        toExamineData.value = res
        if (res.status == 1) {
            toExamineValue.value = res.auditPrice / 100
        } else {
            toExamineValue.value = ''
        }
        toExaminePopup.value.open()
    }

    /*************************************************
     * 改价审核操作
    */
    async function toExamineConfirm() {
        toExaminePopup.value.close()
        let data = {
            status: toExamineData.value.status,
            isAsync: false,
            isContinueWhenError: true,
            payload: JSON.stringify([{
                storeID: toExamineData.value.storeID,
                nameID: toExamineData.value.nameID,
                ...(toExamineData.value.status == 1
                    ? { auditPrice: Math.floor(+toExamineValue.value * 100) }
                    : { remark: toExamineValue.value })
            }])
        }
        let res = await shopping.store_sku_price_audit(data)
        if (res.code == 0) {
            toast('操作成功')
            skuNames.value = skuNames.value.filter((item) => item.nameID != toExamineData.value.nameID)
            if (skuNames.value.length == 0) return dataHoming()
        } else {
            toast(res.desc || res.data)
        }
    }


    /*************************************************
     * 善后工作
    */
    onBeforeUnmount(() => {
        clearTimeout(handleChangeSaleTimer)
        clearTimeout(updatePriceFnTimer)
        clearTimeout(onPullDownRefreshTimer)
    })

    return {
        dafauleData,          // 左侧tablist 数据
        totalCount,           // 商品总条数
        skuNames,             // 商品列表数据
        skuNameItem,          // 商品数据2
        isAudit,              // 商品列表判断条件
        isHot,                // 商品列表判断条件
        showMountTab,         // 批量操作判断
        scrolltolower,        // 页面触底
        isLoad,               // 加载动画
        updateIsSale,         // 过滤筛选
        updateTowFilter,      // 过滤筛选
        serachShopping,       // 搜索框确定
        clearInpu,            // 清空搜索框
        oneMenuClick,         // 一级菜单点击事件
        isCheckoutFilter,     // 切换过滤选项
        isFilter,             // 判断条件
        handleSale,           // 批量可售与不可售
        handleChangeSale,     // 批量可售与不可售
        updateStateOk,        // 批量操作成功
        createGoods,          // 去创建商品
        isPointStore,         // 判断扣点还是折扣
        skuName,              // 当前修改的价格
        auditUnitPrice,       // 正在审核的价格
        currentValue,         // 当前修改价格
        popup,                // 弹窗实例
        stockOrCode,          // stock locationCode
        popupDialog,          // 弹窗 stock locationCode
        handleConfirm,        // 确定修改价格
        openPriceDialog,      // 获取修改数据
        openDialog,           // 获取修改数据2
        sureStockOrCode,      // 确认框 stock locationCode
        handleDelete,         // 删除商品
        refresherrefresh,     // 下拉刷新
        triggered,            // 下拉刷新标识
        leftBarRef,           // 右侧导航栏实例
        statusBarHeight,      // 状态栏高度
        toExamine,            // 审核商品
        toExamineData,        // 审核商品数据
        toExaminePopup,       // 改价审核实例
        toExamineConfirm,     // 确定操作审核
        toExamineValue,       // 审核输入内容
    }
}

export default shoppingMangerFn