<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getClass, addClass, putClass, delClass, putClassStatus } from '@/api/system/config'
import type { classUp } from '@/api/system/config/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElMessageBox, ElSwitch, ElDivider } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'
import { useRouter } from 'vue-router'

const { push } = useRouter()
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getClass({
      ...searchParams.value,
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10
    })
    return {
      list: res.data.list || [],
      total: res.data.count || 0
    }
  }
})
const { dataList, loading, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    width: 80
  },
  {
    field: 'title',
    label: '名称',
    width: 100
  },
  {
    field: 'icon',
    label: '图标',
    align: 'center',
    headerAlign: 'center',
    width: 60,
    slots: {
      default: (data: any) => {
        const icon = data.row.icon
        if (icon) {
          return (
            <>
              <Icon icon={icon} />
            </>
          )
        } else {
          return null
        }
      }
    }
  },
  {
    field: 'eng_title',
    label: '英文名',
    width: 100
  },
  {
    field: 'sort',
    label: '排序',
    align: 'center',
    headerAlign: 'center',
    width: 80
  },
  {
    field: 'info',
    label: '描述',
    minWidth: 80
  },
  {
    field: 'status',
    label: '状态',
    width: 80,
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const status = data.row.status == 1
        return (
          <>
            <ElSwitch v-model={status} onChange={() => putStatus(data.row)}></ElSwitch>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 180,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton
              link
              size="small"
              type="primary"
              onClick={() => push('/preserve/config/detail/' + row.id + '?title=' + row.title)}
            >
              {'配置列表'}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: t('userDemo.disable'),
          value: 0
        },
        {
          label: t('userDemo.enable'),
          value: 1
        }
      ]
    }
  },
  {
    field: 'is_store',
    label: '是否门店',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '非门店',
          value: 0
        },
        {
          label: '门店',
          value: 1
        }
      ]
    }
  },
  {
    field: 'title',
    label: '搜索',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入姓名或者账号'
    }
  }
])

const searchParams = ref({ status: '', title: '', is_store: '' })
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref()
const actionType = ref('')
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = {
    id: row.id || '',
    status: row.status ? true : false, //是否启用
    title: row.title, //名称
    icon: row.icon, //图标
    sort: row.sort, //排序
    pid: row.pid, //pid
    is_store: row.is_store, //是否门店
    eng_title: row.eng_title, //英文名
    info: row.info //描述
  }
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delAction = async (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delClass({ id: row.id })
      await getList()

      ElMessage({
        showClose: true,
        message: '删除',
        type: 'success'
      })
    })
    .catch(() => {})
}
const putStatus = (row: any) => {
  putClassStatus({ id: row.id, status: row.status === 1 ? 0 : 1 }).then(() => {
    getList()
  })
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const data: classUp = {
      id: formData.id || '',
      status: formData.status ? 1 : 0, //是否启用
      title: formData.title, //名称
      icon: formData.icon, //图标
      sort: formData.sort, //排序
      pid: formData.pid, //pid
      is_store: formData.is_store, //是否门店
      eng_title: formData.eng_title, //英文名
      info: formData.info //描述
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        res = await putClass(data)
      } else if (actionType.value === '') {
        res = await addClass(data)
      }
      if (res?.status == 200) {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success'
        })
        getList()
        dialogVisible.value = false
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <div>
    <ContentWrap>
      <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
      <div class="mb-10px">
        <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      </div>
      <Table
        :columns="tableColumns"
        default-expand-all
        node-key="id"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
      <Write
        :menuList="dataList"
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :current-row="currentRow"
      />
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
