<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getUserLevel,
  addUserLevel,
  putUserLevel,
  delUserLevel,
  putUserLevelStatus
} from '@/api/user'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { BaseButton } from '@/components/Button'
import { userLevelSearch } from '@/api/user/types'
import { ElMessage, ElSwitch, ElDivider, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { userLevelData } from '@/api/user/types'
import { TableImage } from '@/components/tableImage'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getUserLevel({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })
    return {
      list: res.data.list.map((re) => {
        re.is_forever = re.is_forever == 1 ? true : false
        re.is_show = re.is_show == 1 ? true : false
        return re
      }),
      total: res.data.count || 0
    }
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center',
    width: 70
  },
  {
    field: 'name',
    label: '等级名称',
    minWidth: 100
  },
  {
    field: 'explain',
    label: '等级说明',
    minWidth: 140
  },
  {
    field: 'icon',
    label: '等级图标',
    align: 'center',
    headerAlign: 'center',
    width: 90,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <TableImage src={row.icon[0]}></TableImage>
          </>
        )
      }
    }
  },
  {
    field: 'image',
    label: '背景图',
    align: 'center',
    headerAlign: 'center',
    width: 90,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <TableImage src={row.image[0]}></TableImage>
          </>
        )
      }
    }
  },
  {
    field: 'type',
    label: '状态',
    width: 90,
    slots: {
      default: ({ row }) => {
        return (
          <>
            <ElSwitch
              inlinePrompt
              activeText="显示"
              inactiveText="隐藏"
              v-model={row.is_show}
              onChange={() => changeLevelStatus(row)}
            ></ElSwitch>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 110,
    align: 'center',
    headerAlign: 'center',
    fixed: 'right',
    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="danger" onClick={() => delAction(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'is_show',
    label: '状态',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '显示',
          value: 1
        },
        {
          label: '隐藏',
          value: 0
        }
      ]
    }
  },
  {
    field: 'title',
    label: '等级名称',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入等级名称'
    }
  }
])

const searchParams = ref<userLevelSearch>({
  title: '',
  is_show: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const currentRow = ref<userLevelData>()
const dialogTitle = ref('')
const actionType = ref('')
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const action = async (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = {
    price: row.price,
    gift_amount: row.gift_amount,
    price_value: row.price_value,
    id: row.id,
    name: row.name,
    is_forever: row.is_forever == 1 ? true : false,
    valid_date: row.valid_date,
    grade: row.grade,
    icon: row.icon,
    image: row.image,
    is_show: row.is_show == 1 ? true : false,
    explain: row.explain,
    task: row.task
  }
  dialogVisible.value = true
}

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

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  // console.log(formData, 'data11111')
  if (formData) {
    saveLoading.value = true
    const data: userLevelData = {
      price: formData.price,
      gift_amount: formData.gift_amount,
      price_value: formData.price_value,
      name: formData.name,
      is_forever: formData.is_forever,
      valid_date: formData.valid_date,
      grade: formData.grade,
      icon: formData.icon[0],
      image: formData.image[0],
      is_show: formData.is_show,
      explain: formData.explain,
      task: formData.task
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        data.id = formData.id
        // console.log(data)
        res = await putUserLevel(data)
      } else if (actionType.value === '') {
        res = await addUserLevel(data)
      }
      if (res?.status === 200) {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success'
        })
        getList()
        dialogVisible.value = false
      }
      saveLoading.value = false
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}

const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除用户等级?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delUserLevel(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const changeLevelStatus = (item) => {
  putUserLevelStatus({
    id: item.id,
    status: item.is_show === 1 ? 0 : 1
  }).then((res) => {
    if (res.status === 200) {
      ElMessage({
        showClose: true,
        message: '修改成功',
        type: 'success'
      })
      getList()
    }
  })
}
</script>

<template>
  <ContentWrap>
    <div class="max-w-1000px">
      <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    </div>
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
    <Write 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>
</template>
