import shopping from "@/api/https/shopping"
import { getStorage } from "@/utils/storage";
import toast from "@/utils/toast";
import { clearList } from "@/utils/tools";
import { onLoad } from "@dcloudio/uni-app";
import { onBeforeUnmount, ref } from "vue";

/*************************************************
 * 创建商品
*/
function createGoodsFn() {

    /*************************************************
     * 默认数据
     */
    const dafauleData: Array<AnyObject> = [
        {
            categoryID: 'all',
            children: [],
            level: 1,
            name: '所有分类',
        }
    ]

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

    /*************************************************
     * 数据归位，empty显现
    */
    function dataHoming() {
        offset.value = 0
        totalCount.value = 0
        skuNames.value = []
    }

    /*************************************************
     * 点击列表
    */
    const isCategoryID = ref<boolean>(false)
    function oneMenuClick(catID: string | number) {
        if (catID == 'all') {
            isCategoryID.value = false
            categoryID.value = ''
            dataHoming()
            getSkuNames()
        } else {
            isCategoryID.value = true
            categoryID.value = catID
            dataHoming()
            getSkuNames()
        }
    }

    onLoad(async () => {
        await getSkuNames()
    })

    /*************************************************
     * 获取商品数据
    */
    const skuNames = ref<Array<AnyObject>>([])  // 商品数据
    const isFocus = ref<boolean>(false)     // 是否关注
    const keyword = ref<string>('')         // 关键字搜索
    const fromStatus = ref<number>(0)
    const toStatus = ref<number>(1)
    const offset = ref<number>(0)
    const pageSize = ref<number>(30)
    const totalCount = ref<number>(0)
    const focusArr = ref<Array<AnyObject>>([])
    const categoryID = ref<string | number>('')
    async function getSkuNames() {
        isLoad.value = true
        let data = {
            storeID: getStorage('storeID'),
            isFocus: isFocus.value,
            keyword: keyword.value,
            fromStatus: fromStatus.value,
            toStatus: toStatus.value,
            offset: offset.value,
            pageSize: pageSize.value,
            status: -1,
            categoryID: categoryID.value
        }
        keyFilter(data)
        let res = await shopping.get_stores_skus_for_store(data)
        if (res.code == 0) {
            let oldSkuNames: Array<AnyObject> = []
            totalCount.value = res.data.totalCount
            oldSkuNames = mapskuName(res.data.skuNames || [])
            focusArr.value.forEach((item: AnyObject) => {
                let arr = oldSkuNames.filter((skuName: AnyObject) => skuName.id === item.nameID)
                if (arr.length > 0) {
                    arr[0].skuNameCheckedStatus = true
                }
            })
            skuNames.value = skuNames.value.concat(oldSkuNames)
        } else {
            dataHoming()
        }
        isLoad.value = false
    }

    /*************************************************
     * 格式化数据
    */
    function mapskuName(skuNames: Array<AnyObject>) {
        let arr = skuNames.map(skuName => {
            skuName.price = (skuName.unitPrice / 100).toFixed(2)
            skuName.skuNameCheckedStatus = false
            skuName.skus = skuName.skus.map((sku: any) => {
                return {
                    ...sku,
                    price: skuName.unit === '份' ? (computedPrice(skuName.price, sku) / 100).toFixed(2) : skuName.price
                }
            })
            return skuName
        })
        return arr
    }

    /*************************************************
     * 计算sku价格
    */
    function computedPrice(price: any, item: any) {
        let skuNamePrice = Math.round(price * 100) // 一斤的价格
        let specQuality = item.specQuality // 质量
        let specUnit = item.specUnit.toLowerCase() // 单位
        if (specUnit === 'kg' || specUnit === 'l') {
            specQuality = specQuality * 1000
        }
        let temPrice = Math.round(skuNamePrice * specQuality / 500)
        return temPrice
    }

    /*************************************************
     * 更新条件筛选
    */
    function updateTowFilter(type: number) {
        if (type == 0) {
            isFocus.value = false
        } else {
            isFocus.value = true
        }
        keyword.value = ''
        rightMainRef.value.createSuccess()
        dataHoming()
        getSkuNames()
    }

    /*************************************************
     * 搜索商品
    */
    function serachShopping(text: string) {
        dataHoming()
        keyword.value = text
        getSkuNames()
    }
    function clearInpu() {
        dataHoming()
        keyword.value = ''
        getSkuNames()
    }

    const isSearchGoods = ref<boolean>(false)
    const scanData = ref<AnyObject>({})
    /*************************************************
     * 扫描二维码
    */
    async function scanCode(text: string) {
        let data = {
            keyword: text,
            status:-1
        }
        // 先从京西商品库查询
        let res = await shopping.get_sku_names_new(data)
        let obj: AnyObject = {}
        if (res.data.skuNames) {
            const skuName = res.data.skuNames[0]
            const sku = skuName.skus[0]
            // _this.keyword = skuName.name 商品名字
            obj.originalName = computedName(skuName, sku)
            obj.name = skuName.name
            obj.imgList = [skuName.img]
            obj.upcCode = skuName.Upc
            obj.specQuality = sku.specQuality
            obj.specUnit = sku.specUnit
            obj.unit = skuName.unit
            obj.weight = sku.weight
            obj.isJx = true
            isSearchGoods.value = true
        } else {
            // 请求京东仓库
            let data = {
                upcCode: text
            }
            const res = await shopping.get_jd_upc_code_by_name(data)
            if (res.data != null) {
                obj = res.data[0]
                obj.isJx = false
                isSearchGoods.value = true
            } else {
                uni.jxAlert({
                    title: '提示',
                    content: '未查询到商品，请联系运营创建'
                })
            }
        }
        scanData.value = obj
    }

    /*************************************************
     * 扫码创建商品
    */
    async function scanGoodConfirm(obj: AnyObject) {
        isSearchGoods.value = false
        let data = {
            ...obj,
            storeID: getStorage('storeID')
        }
        const res = await shopping.create_skus_and_focus_from_wx(data)
        if (res.code == 0) {
            uni.jxAlert({
                title: '提示',
                content: "创建成功"
            })
        } else {
            uni.jxAlert({
                title: '提示',
                content: "创建失败,请联系运营进行创建"
            })
        }
    }

    /*************************************************
     * 格式化商品单位
    */
    function computedName(skuName: any, sku: any) {
        let name = ''
        if (skuName.prefix) name += `[${skuName.prefix}]`
        name += skuName.name
        if (skuName.unit === '份') name += '约'
        name += +sku.specQuality
        name += sku.specUnit
        name += '/' + skuName.unit
        if (sku.comment) name += `(${sku.comment})`
        return name
    }

    /*************************************************
     * 下拉刷新
    */
    const leftBarRef = ref<any>(null)
    let onPullDownRefreshTimer: any = null
    const triggered = ref<boolean>(false)
    function refresherrefresh() {
        triggered.value = true
        clearTimeout(onPullDownRefreshTimer)
        onPullDownRefreshTimer = setTimeout(() => {
            triggered.value = false
            leftBarRef.value.GetStoreCategoryMap()
            dataHoming()
            getSkuNames()
        }, 1000)
    }

    /*************************************************
     * 页面触底加载更多
    */
    const isLoad = ref<boolean>(false)  // 加载图
    function scrolltolower() {
        offset.value++
        if (pageSize.value * (offset.value - 1) > totalCount.value || totalCount.value < pageSize.value) {
            isLoad.value = false
        } else {
            if (isLoad.value) return
            getSkuNames()
        }
    }

    /*************************************************
     * 新建可售商品
    */
    let newFocusArr: Array<AnyObject> = []
    const newGoodsNum = ref<number>(0)
    function newCreateGoods(data: Array<AnyObject>) {
        newGoodsNum.value = data.length
        newFocusArr = data
    }

    /*************************************************
     * 创建商品（关注商品）
    */
    const rightMainRef = ref<any>(null)
    async function handleFocus(type: number) {
        if (newGoodsNum.value == 0) return toast('未选择商品')
        uni.jxConfirm({
            title: '提示',
            content: `本次操作一共${isFocus.value ? '删除' : '创建'}《${newGoodsNum.value}》个商品，确定操作吗`,
            success: async () => {
                if (type == 1) {
                    let data = {
                        storeIDs: JSON.stringify([getStorage('storeID')]),
                        payload: JSON.stringify(newFocusArr)
                    }
                    let res = await shopping.update_stores_skus(data)
                    if (res.code == 0) {
                        isFocus.value ? toast('删除成功', 1) : toast('创建成功，请等待审核', 1)
                        newFocusArr = []
                        rightMainRef.value.createSuccess()
                        newGoodsNum.value = 0
                        dataHoming()
                        getSkuNames()
                    } else {
                        isFocus.value ? toast('删除失败', 2) : toast('创建失败', 2)
                    }
                }
            }
        })
    }


    /*************************************************
     * 收尾工作
    */
    onBeforeUnmount(() => {
        clearList()
    })

    return {
        dafauleData,        // 列表默认数
        oneMenuClick,       // 点击列表项
        skuNames,           // 商品数据
        isFocus,            // 是否关注
        totalCount,         // 未关注条数
        updateTowFilter,    // 更新筛选条件
        serachShopping,     // 输入框搜索
        clearInpu,          // 清空输入框
        scanCode,           // 扫码
        refresherrefresh,   // 下拉刷新
        triggered,          // 动态显示加载
        leftBarRef,         // 右侧tab实例
        scrolltolower,      // 页面触底
        isLoad,             // 加载动画
        newCreateGoods,     // 新建可售商品
        newGoodsNum,        // 新建商品数量
        handleFocus,        // 创建和移除商品
        rightMainRef,       // 主体内容实例
        isSearchGoods,      // 是否查询到了商品
        scanData,           // 查询到的商品详情
        scanGoodConfirm,    // 创建商品
    }
}

export default createGoodsFn