/**
 * 系统设置
 */

import merchant from "@/api/https/merchant"
import { store } from '@/store'
import { getStorage, setStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { onShow } from '@dcloudio/uni-app'
import { computed, nextTick, ref } from 'vue'
import useGlobalFunc from '@/composables/useGlobalFunc'

function setUp() {
    const { openWeixin, logOutFn } = useGlobalFunc()

    // 是否禁用打印机
    const printerDisabled = ref<number>(0)

    // IM单聊状态是否开启
    const imMtStoreStatus = ref<number>(0)

    // IM单聊状态是否开启-饿百
    const imEbStoreStatus = ref<number>(0)

    // 门店是否可自提
    const isDeliverSelf = ref<boolean>(false)

    // 美团门店信息
    const mtStoreInfo = ref<AnyObject>({})

    // 饿百门店信息
    const ebStoreInfo = ref<AnyObject>({})

    // 是否含有美团门店
    const isExistMtStore = ref<boolean>(false)

    // 是否含有饿百门店
    const isExistEbStore = ref<boolean>(false)

    /**
     * 获取页面初始化信息
     */
    onShow(async () => {
        await getStoreMsg()
    })
    // 打印机品牌
    const printerData = ref<AnyObject>({
        0: '未绑定',
        201: '飞鹅打印机',
        202: '外卖管家打印机',
        203: '易联云打印机',
        204: '中午云打印机',
        205: '京西云打印机',
        206: '芯烨云',
        207: '大趋智能'
    })
    const netPrinterData = ref<Array<string>>(['无', '外卖管家打印机', '易联云打印机', '中午云打印机', '京西云打印机'])
    const defultNetPrinterValue = ref<string>('')
    const netPrinter = ref()
    const recordIndex = ref('')     //  记录打印机最初的序列号
    const popup = ref<any>(null)     // 弹窗实例

    const currentNetPrinter = ref(['', '', ''])
    const bindNetPrinter = ref({
        printerSN: '',
        printerKey: ''
    })
    async function getStoreMsg() {
        // 读取vuex 中的 store 数据
        await store.dispatch('storeInfo/getOneStore', getStorage("storeID"))
        smsNotify.value = store.state.storeInfo.allStoreInfo.smsNotify
        printerDisabled.value = store.state.storeInfo.allStoreInfo.printerDisabled
        // 获取第三方美团门店
        if (JSON.stringify(store.state.storeInfo.allStoreInfo) !== '{}') {
            let mtStore = store.state.storeInfo.allStoreInfo.StoreMaps.find((item: { vendorID: number }) => item.vendorID === 1)
            if (mtStore && JSON.stringify(mtStore) !== '{}') {
                mtStoreInfo.value = mtStore
                isExistMtStore.value = true
                let mtStatus = store.state.storeInfo.imOnlineStatus.filter(item => item.vendorID === 1)
                imMtStoreStatus.value = mtStatus.length > 0 ? mtStatus[0].imStatus : 0
            }

            let ebStore = store.state.storeInfo.allStoreInfo.StoreMaps.find((item: { vendorID: number }) => item.vendorID === 3)
            if (ebStore && JSON.stringify(ebStore) !== '{}') {
                ebStoreInfo.value = ebStore
                isExistEbStore.value = true
                let ebStataus = store.state.storeInfo.imOnlineStatus.filter(item => item.vendorID === 3)
                imEbStoreStatus.value = ebStataus.length > 0 ? ebStataus[0].imStatus : 0
            }

            let jxStore = store.state.storeInfo.allStoreInfo.StoreMaps.find((item: { vendorID: number }) => item.vendorID === 9)
            if(jxStore && JSON.stringify(jxStore) !== '{}') isDeliverSelf.value = jxStore.deliverySelf === 1
        }
        // 网络打印机
        netPrinter.value = (store.state.serveInfo.serviceInfo as any).printerVendorInfo
        for (let i in netPrinter.value) {
            if (!printerData.value[i]) {
                let printerName = netPrinter.value[i][0] + '打印机'
                printerData.value[i] = printerName
                netPrinterData.value.push(printerName)
            }
        }

        if (store.state.storeInfo.allStoreInfo.printerVendorID) {
            for (let key in printerData.value) {
                if (key == store.state.storeInfo.allStoreInfo.printerVendorID) {
                    let findIndex = netPrinterData.value.findIndex(item => item === printerData.value[key])
                    if (findIndex !== -1) {
                        defultNetPrinterValue.value = findIndex + ''
                        recordIndex.value = defultNetPrinterValue.value
                    }
                }
            }
        }
        retryActive.value = (+getStorage('printerRetrySize')) + ''
        defaultPrinterValue.value = getStorage('defaultPrinter') || '2'
    }
    // // 打印机名字
    // const printerName = computed(() => {
    //     for (let key in printerData.value) {
    //         if (key == store.state.storeInfo.allStoreInfo.printerVendorID) {
    //             return printerData.value[key]
    //         }
    //     }
    // })

    /**
     * 京西版权信息
     */
    interface CopyRightType {
        id: number
        title: string
        url: string
    }
    const copyRight = ref<Array<CopyRightType>>([
        {
            id: 1,
            title: '用户协议',
            url: 'https://www.jxc4.com/managerApp/jxdjService.html',
        },
        {
            id: 2,
            title: '隐私协议',
            url: 'https://www.jxc4.com/managerApp/jxdjPrivacy.html',
        },
        {
            id: 3,
            title: '关于京西到家',
            url: '/subPages/agreement/updateVersion',
        },
    ])


    // 未拣货提醒
    const smsNotifyData = ref<Array<string>>(['不提醒', '拣货超时短信提醒', '拣货超时电话提示'])
    const smsNotify = ref<string>('0')
    function bindMultiPickerChange(item: AnyObject) {
        if (store.state.storeInfo.allStoreInfo.packageSwitch === 1) {
            let tel = store.state.storeInfo.allStoreInfo.marketManPhone ? store.state.storeInfo.allStoreInfo.marketManPhone : "18048531223"
            uni.jxAlert({
                title: '设置失败',
                content: `非常抱歉，无法设置拣货提醒，请联系运营${tel}`
            })
            return
        }
        smsNotify.value = item.detail.value
        switchSmsNotify()
    }
    // 切换未拣货提示方式
    async function switchSmsNotify() {
        let data = {
            storeID: getStorage('storeID'),
            payload: JSON.stringify({ 'smsNotify': smsNotify.value })
        }
        let res = await merchant.update_store(data)
        if (res.code != 0) return toast('切换失败')
    }


    /*************************************************
     * 默认打印机设备
    */
    const defaultPrinterValue = ref<string>('0')
    const defaultPrinter = ref<Array<string>>(['蓝牙打印机', '网络打印机', '手动选择打印机'])
    // 切换打印设备
    function defaultPrinterChange(e: AnyObject) {
        defaultPrinterValue.value = e.detail.value
        setStorage('defaultPrinter', e.detail.value)
    }

    /**
 * 选择网络打印机
 */
    async function updateNetPrinter(item: AnyObject) {
        if (item.detail.value !== '0') {
            defultNetPrinterValue.value = item.detail.value
            for (let i in netPrinter.value) {
                if (netPrinter.value[i][0] + '打印机' === netPrinterData.value[item.detail.value]) {
                    currentNetPrinter.value = netPrinter.value[i]
                    popup.value.open()
                }
            }
        } else {
            defultNetPrinterValue.value = ''
            let res = await merchant.update_store({
                storeID: store.state.storeInfo.allStoreInfo.id,
                payload: JSON.stringify({
                    printerVendorID: 0,
                    printerSN: '',
                    printerKey: ''
                })
            })
            if (res.code == '0') {
                toast("删除成功", 1);
                getStores()
            } else {
                toast("删除失败", 2);
            }

        }
    }

    /**
     * 绑定网络打印机
     */
    async function handleConfirm() {
        if (!bindNetPrinter.value.printerSN) return toast(`请输入${currentNetPrinter.value[1]}`, 2)
        if (currentNetPrinter.value[2] !== '不填' && !bindNetPrinter.value.printerKey) return toast(`请输入${currentNetPrinter.value[2]}`, 2)
        // if (this.storeInfo.printerSN) {
        //     json.isPrintCancelOrder = this.storeInfo.isPrintCancelOrder
        //     json.isPrintRefundOrder = this.storeInfo.isPrintRefundOrder
        //   }
        let printerVendorID = ''
        for (let i in printerData.value) {
            if (netPrinterData.value[+defultNetPrinterValue.value] === printerData.value[i]) printerVendorID = i
        }
        let res = await merchant.update_store({
            storeID: store.state.storeInfo.allStoreInfo.id,
            payload: JSON.stringify({
                printerVendorID,
                printerSN: bindNetPrinter.value.printerSN,
                printerKey: bindNetPrinter.value.printerKey
            })
        })
        if (res.code == '0') {
            toast("绑定成功", 1)
            getStores()
        } else {
            toast("绑定失败", 2)
        }
        bindNetPrinter.value.printerSN = ''
        bindNetPrinter.value.printerKey = ''
        popup.value.close()

    }

    /**
     * 扫码绑定打印机 易联云
     */
    function scanCode() {
        uni.jxConfirm({
            title: '相机/相册权限说明',
            content: '便于您使用该功能扫描打印机上的二维码，快速识别并绑定打印机',
            success() {
                uni.scanCode({
                    success: async ({ result }) => {
                        // emit('scanCode', result)
                        let data = {
                            storeID: store.state.storeInfo.allStoreInfo.id,
                            data: result
                        }
                        let res = await merchant.bind_net_printer(data)
                        if (res.code == 0) {
                            toast('绑定成功', 1)
                            defultNetPrinterValue.value = '2'
                            getStores()
                        } else {
                            toast('绑定失败', 2)

                        }
                    },
                    fail: (error) => {
                        toast('取消扫码', 2)
                        cancelPopup()
                    },
                })
            },
            fail() {
                defultNetPrinterValue.value = '2'
            }
        })
    }

    /**
     * 获取门店信息
     */
    async function getStores() {
        await store.dispatch('storeInfo/getOneStore',getStorage("storeID"))
        // let stateRes = await merchant.get_stores({
        //     storeID: getStorage("storeID")
        // });
        // if (stateRes.code == 0) {
        //     let stateData = stateRes.data.stores[0];
        //     store.commit('storeInfo/setAllStoreInfo', stateData)

        // } else {
        //     toast("系统异常", 2);
        // }
    }

    // /**
    //  * 绑定打印机
    //  * 没有打印机跳转到物料商城购买打印机
    //  * 有打印机切是京西云的打印机跳转到京西云打印机小程序
    //  */
    // function bindPrinter(type = '未绑定') {
    //     // ios不展示
    //     if (uni.getSystemInfoSync().platform == 'ios') return

    //     if (type == '未绑定') {
    //         if (store.state.storeInfo.storeStatus === -2) {
    //             uni.jxAlert({
    //                 title: '物料申请',
    //                 content: '门店已被禁用，请联系运营',
    //             })
    //         }
    //         openWeixin(`pages/index/index?storeID=666666&fromStoreID=${getStorage('storeID')}&storeType=c4`, 'gh_0d7e2243b51f')

    //     } else if (type == '京西云打印机') {
    //         openWeixin('pages/home/home', 'gh_d0aacb950a2a')
    //     } else {
    //         uni.jxAlert({
    //             title: type,
    //             content: `您当前使用的是【${type}】，如有问题请联系运营`,
    //         })
    //     }
    // }

    /**
     * 取消绑定打印机弹框
     */
    function cancelPopup() {
        defultNetPrinterValue.value = recordIndex.value
        bindNetPrinter.value.printerSN = ''
        bindNetPrinter.value.printerKey = ''
        popup.value.close()
    }

    /**
     * 清空打印队列
     */
    async function DeletePrinterSeq() {
        let data = {
            storeIDs: JSON.stringify([getStorage('storeID')])
        }
        let res = await merchant.delete_printer_seq(data)
        if (res.code == 0) {
            toast('清空队列成功', 1)
        } else {
            toast('清空队列失败', 2)
        }
    }


    /**
     * 网络打印机禁用开关
     */
    async function switchprinterDisabled(e: AnyObject) {
        let data = {
            storeID: getStorage('storeID'),
            payload: JSON.stringify({
                printerDisabled: e.detail.value ? 1 : 0
            })
        }
        let res = await merchant.update_store(data)
    }

    /**
     * IM单聊状态设置
     */
    async function switchImMtStoreStatus(e: AnyObject, vendorID: number) {
        let data = [{
                vendorID: vendorID,
                vendorStoreID: vendorID === 1 ? mtStoreInfo.value.vendorStoreID + '' : ebStoreInfo.value.vendorStoreID + '',
                vendorOrgCode: vendorID === 1 ? mtStoreInfo.value.vendorOrgCode + '' : ebStoreInfo.value.vendorOrgCode + '',
                imStatus: e.detail.value ? 1 : 0
            }]
        let res = await merchant.set_mt_store_im_status({ data: JSON.stringify(data) })
        if (res.code == 0) {
            let brr: any = []
            store.state.storeInfo.imOnlineStatus.forEach(item => {
                if (item.vendorID === vendorID) brr.push({
                    ...item,
                    imStatus: e.detail.value ? 1 : 0
                })
                else brr.push({ ...item })
            })
            store.commit('storeInfo/setImOnlineStatus', brr)
        } else {
            uni.jxAlert({
                title: '提示',
                content: `修改失败：${res.desc || res.data}`,
                success: () => {
                    // chatData.value.pop()
                }
            })
        }
    }

    /**
     * 是否打印Upc
     */
    function switchUpc(e: AnyObject) {
        setStorage('isPrinterUpc', e.detail.value)
    }


    /*************************************************
     * 是否开启打印机兼容模式
    */
    function switchCompatible(e: AnyObject) {
        setStorage('printerCompatible', e.detail.value)
    }


    /**
     * 蓝牙打印机字体大小
     */
    const printerFontSize = ref<Array<string>>(['小号', '中号', '大号', '开发者模板'])
    const retryActive = ref<string>('0')
    function changeRetry(e: AnyObject) {
        retryActive.value = e.detail.value
        setStorage('printerRetrySize', +e.detail.value)
    }


    /**
     * 蓝牙打印机设置
     */
    function bluetoothPrinterSetUp() {
        uni.navigateTo({ url: '/subPages/merchantChild/printerSetUp/printerSetUp' })
    }


    /**
     * 京西协议信息
     */
    function copyRightFn(url: string, id: number) {
        if (id == 3) {
            uni.navigateTo({ url: url })
        } else {
            uni.navigateTo({ url: `/subPages/agreement/jxcs?url=${url}` })
        }
    }


    /**
     * 当前打印机名字
     */
    const newPrinterName = ref<string>('')
    onShow(() => {
        newPrinterName.value = getStorage('deviceName') || '未连接'
    })


    /*************************************************
     * 后台运行能力
    */
    function backstage() {
        switch (uni.getSystemInfoSync().platform) {
            case 'android':
                uni.navigateTo({ url: '/subPages/merchantChild/backstageApp/backstageApp' })
                break;
            case 'ios':
                uni.jxAlert({
                    title: '提示',
                    content: 'IOS暂不支持此功能'
                })
                break;
        }
    }


    /*************************************************
     * 注销账号
    */
    function accoutCancellation() {
        uni.jxConfirm({
            title: '注销账号',
            content: '您确定注销账号吗？如果确定注销账号请联系官方运行进行注销账号（预计7个工作日）。',
            success: () => {
                uni.navigateTo({ url: '/subPages/orderChild/getPhone/getPhone' })
            }
        })
    }

    /*************************************************
     * 退出登录
    */
    function outLogin() {
        logOutFn()
        uni.navigateTo({
            url: '/subPages/login/wxLogin/wxLogin',
            animationType: 'zoom-out',
        })
    }


    /*************************************************
     * 是否打印机商品价格
    */
    function switchgoodsMoney(e: AnyObject) {
        setStorage('printerGoodsMoney', e.detail.value)

    }
	
	/**
	 * 跳转到设置营业状态页面
	 */
	function jumpBusinessStatus() {
		uni.navigateTo({url: '/subPages/merchantChild/setBusinessStatus/setBusinessStatus'})
	}

    /**
     * 跳转到发票设置页面 (饿百)
     */
    function jumpInvoiceSet() {
        uni.navigateTo({url: '/subPages/merchantChild/setInvoiceEB/setInvoiceEB'})
    }

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

    /**
     * 订单提醒
     */
    // const orderReminder = ref(true)
    // orderReminder.value = getStorage('defaultOrderReminder') || getStorage('defaultOrderReminder') === '' ? true : false
    // function changeOrderReminder() {
    //     orderReminder.value = !orderReminder.value
    //     setStorage('defaultOrderReminder',  orderReminder.value ? 1 : 0)
    // }

    
    /***************************************************
     * 修改自提的类型
     */
    async function switchJxDeliverySelf(e:AnyObject) {
        let res = await merchant.update_store_vendor_map({
            storeID:getStorage('storeID'),
            vendorID:9,
            payload:JSON.stringify({
                deliverySelf:e.detail.value ? 1 : 0
            })
        })
    }
    

    return {
        copyRight,              // 京西版权信息
        smsNotifyData,          // 未拣货选项
        defaultPrinter,         // 选择默认打印设备
        defaultPrinterChange,   // 切换打印设备
        defaultPrinterValue,    // 默认选中设备
        smsNotify,              // 选中提醒方式
        bindMultiPickerChange,  // 未拣货选择提醒方式
        copyRightFn,            // 京西协议
        // printerName,         // 绑定的打印机品牌
        // bindPrinter,         // 绑定打印机
        bluetoothPrinterSetUp,  // 蓝牙打印机设置
        switchUpc,              // 是否打印Upc
        newPrinterName,         // 当前绑定打印机设备
        DeletePrinterSeq,       // 清空打印队列
        printerDisabled,        // 是否禁用网络打印机
        switchprinterDisabled,  // 网络打印机禁用开关,
        imMtStoreStatus,        // IM单聊状态是否开启
        imEbStoreStatus,        // IM单聊状态是否开启 饿百
        isDeliverSelf,          // 京西
        switchJxDeliverySelf,   // 切换自送
        switchImMtStoreStatus,  // 更改IM单聊门店状态
        isExistMtStore,         // 是否绑定美团门店
        isExistEbStore,         // 是否绑定饿百门店
        printerFontSize,        // 蓝牙打印机字体大小
        retryActive,            // 默认选中重试次数
        changeRetry,            // 选择重试次数
        backstage,              // 后台运行能力
        accoutCancellation,     // 注销账号
        switchCompatible,       // 打印机兼容模式
        outLogin,               // 退出登录
        switchgoodsMoney,       // 是否打印商品价格
        netPrinterData,         // 网络打印机
        defultNetPrinterValue,  // 默认选中的网络打印机
        updateNetPrinter,       // 选择网络打印机
        popup,                  // 弹框实例
        scanCode,               // 易联云 扫码绑定打印机
        cancelPopup,            // 取消绑定打印机弹框
        currentNetPrinter,      // 当前选中的网络打印机需填写的数据
        bindNetPrinter,         // 绑定的网络打印机的值 v-model
        handleConfirm,          // 绑定网络打印机
		setTime,                // 去修改营业时间
		jumpBusinessStatus,     // 跳转到营业状态页面
        // orderReminder,          // 来单提醒
        // changeOrderReminder,    // 改变订单提醒状态
        jumpInvoiceSet,         // 跳转到发票设置页面
        store
    }
}


export default setUp