import { NTabPane, NTabs } from 'naive-ui'
import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { getTabsCache, setTabsCaches } from '@/hooks/use-async'
import { appKey } from '@/utils/constant'
import { sysApplicationPage } from '@views/menu-manage/api'
import SmsRecord from '@views/message/message-record/sms-record'
import PushRecord from '@views/message/message-record/push-record'
import WechatRecord from '@views/message/message-record/wechat-record'
import EmailRecord from '@views/message/message-record/email-record'

export default defineComponent({
  name: 'message-template-index',
  setup() {
    const state = reactive({
      tabName: 'KT' as 'KT' | 'GYT' | 'KLX' | 'GYM' | 'CBS',
      appKeyList: [] as any,
      appNameList: [] as any,
      messageSendMode: 'SMS' as 'SMS' | 'PUSH' | 'EMAIL' | 'WECHAT'
    })
    const tabsInstRef = ref()
    getTabsCache((val: any) => {
      if (val.form.tabName) {
        state.tabName = val.form.tabName
        nextTick(() => tabsInstRef.value?.syncBarPosition())
      }
    })
    const route = useRoute()
    const setTabs = (val: any) => {
      setTabsCaches(val, 'tabName', route)
    }

    onMounted(async () => {
      // 获取应用APP信息
      // const appKeys = Object.keys(appKey)
      const { data } = await sysApplicationPage({ page: 1, rows: 99, parentId: 0 })
      const tempList = data.rows || []
      tempList.forEach((next: any) => {
        // if (appKeys.includes(next.appKey)) {
        state.appKeyList.push(next.appKey)
        state.appNameList.push(next.appName)
        // }
      })
      nextTick(() => tabsInstRef.value?.syncBarPosition())
    })

    return () => {
      return (
        <div class="system-menu-container">
          <div class={['section-container']} style="padding-top: 0">
            <NTabs
              ref={tabsInstRef}
              type="line"
              size="large"
              v-model:value={state.tabName}
              onUpdate:value={(val: any) => setTabs(val)}
            >
              {state.appKeyList.map((app: any, index: number) => (
                <NTabPane name={app} tab={state.appNameList[index]}>
                  <NTabs type="card" size="small" v-model:value={state.messageSendMode}>
                    <NTabPane name={'SMS'} tab={'短信'}>
                      <SmsRecord appKey={app} />
                    </NTabPane>
                    <NTabPane name={'PUSH'} tab={'推送'}>
                      <PushRecord appKey={app} />
                    </NTabPane>
                    <NTabPane name={'WECHAT'} tab={'公众号'}>
                      <WechatRecord appKey={app} />
                    </NTabPane>
                    <NTabPane name={'EMAIL'} tab={'邮件'}>
                      <EmailRecord appKey={app} />
                    </NTabPane>
                  </NTabs>
                </NTabPane>
              ))}
            </NTabs>
          </div>
        </div>
      )
    }
  }
})
