import { computed, ref } from 'vue'
import { onLoad } from "@dcloudio/uni-app";
import { getStorage } from '@/utils/storage';
import merchant from '@/api/https/merchant';
import { timeFormatD } from "@/utils/tools";
import useGlobalFunc from '@/composables/useGlobalFunc';
import { store } from '@/store'
import toast from "@/utils/toast";
export default {
    setup() {
        const businessStatusList = ref([
            { id: 1, name: '营业' },
            { id: 0, name: '临时休息' },
            { id: -1, name: '休息' }
            // { id: -2, name: '禁用' },
        ])
        const businessHours = ref<AnyObject>({})    // 营业时间段
        const businessStatus = ref(1)    // 营业状态，默认营业
        const newAutoEnableAt = ref<string>('')
        const popupTime = ref()          // 临时休息的时间弹框
        const dayList = ref(["休息到明天", "休息到后天"]);  // 临时休息时间段
        const currentTime = ref(0)
        const storeName = ref('')   // 门店名称
        const logoUrl = ref('https://image.jxc4.com/image/9b9436561e7ff7d8d764787b1aa5182e.jpg')

        // const { isTxd } = useGlobalFunc()

        onLoad(async () => {
            store.commit('storeInfo/jxLoadingFn', true)
            if (getStorage('terrace') === 'jxgy') logoUrl.value = 'https://image.jxc4.com/image/9e26e6d4e8646d340c21dfe595ac4d08.jpg'
            else if (getStorage('terrace') === 'gblm') logoUrl.value = 'https://image.jxc4.com/image/5cd356df441a32295798f78a39491464.png'
            await getStores()
            store.commit('storeInfo/jxLoadingFn', false)
        })


        const switchOpenTime = computed(() => {
            if (newAutoEnableAt.value) {
                let now = +new Date(timeFormatD(+new Date()));
                let time = +new Date(timeFormatD(newAutoEnableAt.value));
                let num = time - now;
                if (num < 0) {
                    return "营业时间错误请联系运营";
                } else {
                    let day = num / 1000 / 3600 / 24;
                    if (day < 1) return "门店将在今天自动营业";
                    else if (day >= 1 && day < 2) return "门店将在明天自动营业";
                    else if (day >= 2 && day < 3) return "门店将在后天自动营业";
                    else return `将在 ${timeFormatD(newAutoEnableAt.value)} 自动营业`;
                }
            } else {
                return "";
            }
        })

        /**
         * 获取门店数据
         */
        async function getStores() {
            await store.dispatch('storeInfo/getOneStore',getStorage("storeID"))
            const stateData = store.state.storeInfo.allStoreInfo
            storeName.value = stateData.name    // 门店名
            businessStatus.value = stateData.status // 营业状态
            newAutoEnableAt.value = stateData.autoEnableAt  // 手机门店休息时间
            businessHours.value = store.getters['storeInfo/businessHours']  // 营业时间
        }


        /*************************************************
         * 去修改营业时间
        */
        function setTime() {
            uni.navigateTo({ url: `/subPages/merchantChild/setBusinessTime/setBusinessTime` })
        }

        /*************************************************
         * 修改营业状态
        */
        function setStatus(item: AnyObject) {
            if (item.id === businessStatus.value) return
            // console.log('修改营业状态', item)

            if (item.id === 1) {
                uni.jxConfirm({
                    title: '提示',
                    content: '确定要将此门店设置为营业吗?',
                    success: async () => {
                        let data = {
                            storeID: getStorage("storeID"),
                            payload: JSON.stringify({
                                status: 1,
                            }),
                        };
                        await merchant.update_store(data);
                        // setTxdIngState(1)
                        newAutoEnableAt.value = ''
                        toast("操作成功", 1)
                        // state.value = 1;
                        // businessStatus.value = item.id
                        await getStores()
                        // uni.navigateBack()
                    },
                })
            } else if (item.id === 0) {
                // console.log('设置门店为临时休息')
                popupTime.value.open()
                // businessStatus.value = item.id
            } else if (item.id === -1) {
                uni.jxConfirm({
                    title: '提示',
                    content: '确定要将此门店设置为休息吗?',
                    success: async () => {
                        let data = {
                            storeID: getStorage("storeID"),
                            payload: JSON.stringify({
                                status: -1,
                            }),
                        };
                        await merchant.update_store(data);
                        // setTxdIngState(-1)
                        newAutoEnableAt.value = ''
                        // businessStatus.value = item.id
                        toast("操作成功", 1)
                        await getStores()
                        // uni.navigateBack()
                    },
                })
            } else {
                // 禁用
            }
        }

        /**
         * 设置第三方平台
         */
        // async function setTxdIngState(type: number) {
        //     // if (isTxd()) {
        //     //     let data = {
        //     //         vendorOrgCode: 34402634,
        //     //         txdStores: JSON.stringify({
        //     //             flag: [1],
        //     //             txdStoreID: `JX${getStorage('storeID')}`,
        //     //             status: type
        //     //         })
        //     //     }
        //     //     await merchant.update_txd_store(data)
        //     // }

        //     // 更新线上平台的营业状态
        //     let arr = store.state.storeInfo.allStoreInfo.StoreMaps.map((item: AnyObject) => {
        //         if (item.isSync) return item.vendorID + ''
        //     })

        //     arr = arr.filter((item: string) => item !== '9')
        //     if (arr.length > 0) {
        //         let data = {
        //             storeID: getStorage('storeID'),
        //             vendorIDs: arr.join(','),
        //             status: type
        //         }
        //         await merchant.update_vendors_store_states(data);
        //     }
        //     // uni.navigateBack()
        // }

        async function storeRest() {
            let autoEnableAt = currentTime.value
                ? timeFormatD(+new Date() + 2 * 24 * 3600 * 1000)
                : timeFormatD(+new Date() + 1 * 24 * 3600 * 1000)
            let data = {
                storeID: getStorage("storeID"),
                payload: JSON.stringify({
                    status: 0,
                    autoEnableAt,
                }),
            };
            await merchant.update_store(data);
            // setTxdIngState(0)
            toast("操作成功", 1);
            popupTime.value.close()
            businessStatus.value = 0;
            newAutoEnableAt.value = autoEnableAt
            getStores()
        }

        function radioChange(e: any) {
            let findIndex = dayList.value.findIndex(item => item === e.detail.value)
            if (findIndex !== -1) currentTime.value = findIndex
        }

        return {
            businessStatusList,             // 营业时间列表
            businessHours,                  // 营业时间段
            businessStatus,                 // 营业状态
            switchOpenTime,                 // 临时休息 多久后自动回复营业
            setTime,                        // 去修改营业时间
            setStatus,                      // 修改营业状态
            popupTime,                      // 临时休息的时间弹框
            dayList,                        // 临时休息时间段
            currentTime,                    // 临时休息时间 动态index
            storeRest,                      // 临时休息的时间弹框 确认
            radioChange,                    // 临时休息的时间弹框 change事件
            storeName,                      // 门店名
            logoUrl                         // logoUrl
        }
    }
}