import {
  NButton,
  NDataTable,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTabsViewStore } from '@/store/modules/tabsView'
import SaveForm from '@components/save-form'
import Pagination from '@components/pagination'
import deepClone from '@/utils/deep.clone'
import WechatConfigEdit from '@views/message/message-config/wechat/modal/wechat-config-edit'
import { sysApplicationPage } from '@views/menu-manage/api'
import { getMapValueByKey } from '@/utils/objectUtil'
import { appKey } from '@/utils/constant'
import { wxConfigInfoPage, wxConfigInfoRemove, wxConfigInfoStatus } from '@views/message/api'

export default defineComponent({
  name: 'wechat-config',
  setup(props, ctx) {
    const route = useRoute()
    const router = useRouter()
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      appId: null as any,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null, //关键字
        appKey: null, //应用
        status: null // 状态
      },
      name: null as any,
      dataList: [],
      showEdit: false,
      editMode: 'add',
      editRowData: {} as any,
      appData: [] as any
    })
    const tabsViewStore = useTabsViewStore()
    const gotoBack = () => {
      tabsViewStore.closeCurrentTab(route)
      router.push({
        path: '/message/messageConfig'
      })
    }

    onMounted(async () => {
      state.appData = []
      const { data } = await sysApplicationPage({ page: 1, rows: 999 })
      if (data && data.rows) {
        data.rows.forEach((item: any) => {
          state.appData.push({ label: item.appName, value: item.appKey })
        })
      }

      getList()
    })

    const saveForm = ref()
    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await wxConfigInfoPage({
          ...state.pagination,
          ...state.searchForm
        })
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {}
      state.loading = false
    }

    const onChangeStatus = (row: any) => {
      const statusStr = row.status ? '停用' : '启用'
      dialog.warning({
        title: '提示',
        content: `是否${statusStr}？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await wxConfigInfoStatus({
              id: row.id,
              status: !row.status
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {}
        }
      })
    }

    const onRmove = (row: any): void => {
      dialog.warning({
        title: '提示',
        content: `删除"${row.name}"，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await wxConfigInfoRemove(row.id)
            getList()
            message.success('删除成功')
          } catch {}
        }
      })
    }

    const columns = (): any => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '应用',
          key: 'appKey',
          render(row: any) {
            return <div>{getMapValueByKey(row.appKey, new Map(Object.entries(appKey)))}</div>
          }
        },
        {
          title: '公众号名称',
          key: 'mpName'
        },
        {
          title: '公众号ID',
          key: 'appid'
        },
        {
          title: '接入密钥',
          key: 'secret'
        },
        {
          title: '消息密钥',
          key: 'token'
        },
        {
          title: '加密模式密钥',
          key: 'aeskey'
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="message/wxTemplateConfig1788457824507092993"
                  onClick={() => {
                    router.push({
                      path: '/message/wxTemplateConfig',
                      query: {
                        id: row.id
                      }
                    })
                  }}
                >
                  查看模板
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="wxConfigInfo/status1790934722325581825"
                  onClick={() => {
                    onChangeStatus(row)
                  }}
                >
                  {row.status ? '停用' : '启用'}
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="wxConfigInfo/update1790934555132235777"
                  onClick={() => {
                    state.showEdit = true
                    state.editRowData = deepClone(row)
                    state.editMode = 'edit'
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="wxConfigInfo/remove1790934636120051714"
                  disabled={!!row.status}
                  onClick={() => {
                    onRmove(row)
                  }}
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    return () => (
      <div class="system-menu-container">
        <div class={['section-container']}>
          <div class="system-menu-container">
            <SaveForm
              ref={saveForm}
              model={state.searchForm}
              onSubmit={onSubmit}
              saveKey="wechat-config"
              onSetModel={(val: any) => (state.searchForm = val)}
            >
              <NFormItem label="关键字" path="keyword">
                <NInput
                  placeholder="应用编号/名称"
                  v-model:value={state.searchForm.keyword}
                  clearable
                />
              </NFormItem>
              <NFormItem label="应用" path="appKey">
                <NSelect
                  placeholder="请选择应用"
                  v-model:value={state.searchForm.appKey}
                  options={state.appData}
                  clearable
                />
              </NFormItem>
              <NFormItem label="状态" path="status">
                <NSelect
                  v-model:value={state.searchForm.status}
                  clearable
                  options={
                    [
                      {
                        label: '启用',
                        value: 1
                      },
                      {
                        label: '停用',
                        value: 0
                      }
                    ] as any
                  }
                  placeholder="全部状态"
                />
              </NFormItem>
              <NFormItem>
                <NSpace>
                  <NButton type="primary" onClick={onSearch}>
                    搜索
                  </NButton>
                  <NButton type="default" onClick={onBtnReset}>
                    重置
                  </NButton>
                </NSpace>
              </NFormItem>
            </SaveForm>

            <NSpace style={{ paddingBottom: '12px' }}>
              <NButton
                type="primary"
                v-auth="wxConfigInfo/save1790934473301364738"
                onClick={() => {
                  state.showEdit = true
                  state.editMode = 'add'
                }}
              >
                新增公众号配置
              </NButton>
            </NSpace>

            <div class={['section-container']}>
              <NDataTable
                loading={state.loading}
                columns={columns()}
                data={state.dataList}
                rowKey={(row: any) => row.id}
                scrollX={'1400'}
              ></NDataTable>

              <Pagination
                v-model:page={state.pagination.page}
                v-model:pageSize={state.pagination.rows}
                v-model:pageTotal={state.pagination.pageTotal}
                onList={getList}
                sync
                saveKey="wechat-config"
              ></Pagination>
            </div>
            <NModal
              blockScroll={true}
              v-model:show={state.showEdit}
              preset="dialog"
              showIcon={false}
              title={(state.editMode == 'add' ? '新增' : '编辑') + '短信平台'}
              // style={{width: 'auto'}}
              style={{ width: '700px' }}
            >
              <WechatConfigEdit
                editMode={state.editMode}
                rowData={state.editRowData}
                appData={state.appData}
                onClose={() => (state.showEdit = false)}
                onGetList={() => {
                  state.pagination.page = 1
                  getList()
                }}
              />
            </NModal>
          </div>
        </div>
      </div>
    )
  }
})
