import shopping from "@/api/https/shopping"
import { store } from "@/store"
import { getStorage } from "@/utils/storage"
import toast from "@/utils/toast"
import { jx_throttles, timeFormatD } from "@/utils/tools"
// import { computed } from "@vue/reactivity"
import configCms from "@/utils/configCms"
import { computed } from "vue"

interface propType {
    skuName: AnyObject
    isAudit: boolean
    isHot: boolean
    showMountTab: boolean
}
/*************************************************
 * 商品列表
*/
function goodsListFn(props: Readonly<propType>) {

    /*************************************************
     * 列表判断条件
    */
    const isNewPriceDisplay: any = computed(() => {
        store.getters['storeInfo/isNewPriceDisplay']
    })

    /*************************************************
     * 获取userType
    */
    const userType = computed(() => {
        return +getStorage('userType')
    })

    /*************************************************
     * 修改商品售卖状态
    */
    function updateSaleStatus(sku: AnyObject, skuName: AnyObject, status: number) {
        if (+sku.storeSkuStatus === +status && !sku.autoSaleAt) return false
        let data = {
            sku,
            skuName,
            status
        }
        updateSaleStatusThrottles(data)
    }
    const updateSaleStatusThrottles = jx_throttles({
        time: 500,
        success: async (e: AnyObject) => {
            let data = {
                storeIDs: JSON.stringify([getStorage('storeID')]),
                payload: JSON.stringify([
                    {
                        nameID: e.skuName.id,
                        skus: [
                            {
                                skuID: e.sku.id,
                                isSale: +e.status === 0 ? -1 : +e.status,
                            },
                        ],
                    },
                ]),
            }
            let res = await shopping.update_stores_skus(data)
            if (res.code == 0) {
                changeSaleStatus(e.sku, e.skuName, e.status)
                if (e.sku.autoSaleAt) e.sku.autoSaleAt = 0
            } else {
                toast('修改失败', 2)
            }
        },
        fail: (t: number) => {
            toast(`操作太快`)
        }
    })

    /*************************************************
     * 修改商品临时不可售
    */
    function tmpSaleNo(sku: AnyObject, skuName: AnyObject) {
        if (sku.storeSkuStatus === 0 && sku.autoSaleAt) return false
        let data = {
            sku,
            skuName,
        }
        tmpSaleNoThrottles(data)
    }
    const tmpSaleNoThrottles = jx_throttles({
        time: 500,
        success: async (e: AnyObject) => {
            let autoSaleAt = computedAutoSaleAt()
            let data = {
                storeIDs: JSON.stringify([getStorage('storeID')]),
                payload: JSON.stringify([{
                    skuID: e.sku.id,
                    isSale: -1,
                    isAsync: false,
                }]),
                autoSaleAt: autoSaleAt
            }
            let res = await shopping.update_stores_skus_sale(data)
           
            //  let res:AnyObject = {
            //     code: "-105",
            //     desc: "本地数据修改成功，但同步失败，请根据错误提示处理！，同步错误信息：[{\"商品ID\":0,\"分类名\":\"\",\"门店ID\":804947,\"平台名\":\"抖店平台\",\"平台商品ID\":\"\",\"商品nameID\":0,\"平台价\":0,\"同步类型\":\"异常同步错误\",\"错误信息\":\"门店:804947，修改没有创建的商品:22807\"},{\"商品ID\":22807,\"分类名\":\"\",\"门店ID\":804947,\"平台名\":\"京东到家\",\"平台商品ID\":\"2792687352\",\"商品nameID\":8643,\"平台价\":0,\"同步类型\":\"更新商品状态\",\"错误信息\":\"未查询到到家商品编码\"}]",
            //     data: ""
            // }

            // if (res.code === '0') {
            //     changeSaleStatus(e.sku, e.skuName, 0)
            //     e.sku.autoSaleAt = autoSaleAt
            // } else {
            //     if(res.code === '-105' && res.desc.includes('本地数据修改成功，但同步失败，请根据错误提示处理')) toast(res.desc)
            //     else toast('修改失败', 2)
            // }
            
            if (res.code == 0) {
                changeSaleStatus(e.sku, e.skuName, 0)
                e.sku.autoSaleAt = autoSaleAt
            } else {
                let findIndex = res.desc.indexOf('[')
                let str = ''
                if(findIndex!== -1){
                    JSON.parse(res.desc.substring(findIndex)).forEach((element:AnyObject) => {
                        str = str.length >0 ? str + '；\n' + element['平台名'] + ':【' +  element['错误信息'] + '】': str + element['平台名'] +'：【'  +  element['错误信息']+'】'
                    });
                }
                if(res.code === '-105' && res.desc.includes('本地数据修改成功，但同步失败，请根据错误提示处理')) toast(`${str}`)
                else toast('修改失败', 2)
            }
        },
        fail: (t: number) => {
            toast(`操作太快`)
        }
    })

    /*************************************************
     * 计算自动可售时间
    */
    function computedAutoSaleAt() {
        let now = +new Date()
        let autoTime = +new Date(`${timeFormatD(+new Date())} ${autoSaleAt.value}`)
        if (now < autoTime) {
            return `${timeFormatD(+new Date())} ${autoSaleAt.value}`
        } else {
            return `${timeFormatD(+new Date() + 24 * 3600 * 1000)} ${autoSaleAt.value}`
        }
    }

    // 自动可售时间
    const autoSaleAt = computed(() => {
        let { autoSaleAt = '' } = configCms.serveInfo
        return autoSaleAt
    })

    /*************************************************
     * 修改商品可售状态
    */
    async function changeSaleStatus(sku: AnyObject, skuName: AnyObject, status: number) {
        if (props.isAudit) return false
        sku.storeSkuStatus = +status
        // 计算可售不可售图标
        if (skuName.skus.some((item: AnyObject) => item.storeSkuStatus)) {
            skuName.skuAllnoSale = false
        } else {
            skuName.skuAllnoSale = true
        }
    }

    return {
        isNewPriceDisplay,          // 列表判断条件
        userType,                   // 获取userType
        updateSaleStatus,           // 修改商品售卖状态
        tmpSaleNo,                  // 临时不可售
    }
}

export default goodsListFn