<script setup lang="tsx">
import { reactive, ref, unref, useTemplateRef } from 'vue'
import { getBrandList, addBrand, editBrand, delBrand } from '@/api/goods'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElDivider, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import Write from './components/Write.vue'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getBrandList({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10
    })
    return {
      list: res.data.list,
      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: 'brand_name',
    label: '名称',
    minWidth: 100
  },
  {
    field: 'is_show',
    label: '是否显示',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.is_show ? 'primary' : 'danger'}>
              {row.is_show ? '显示' : '隐藏'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action('edit', row)}>
              编辑
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              删除
            </BaseButton>
          </>
        )
      }
    }
  }
])

const dialogVisible = ref(false)
const currentRow = ref()
const dialogTitle = ref('')
const actionType = ref('')
const saveLoading = ref(false)
const writeRef = useTemplateRef('writeRef')

// function arrayToObject(array) {
//     var obj = {};
//     for (var i = 0; i < array.length; i++) {
//         obj[i] = array[i];
//     }
//     return obj;
// }
const action = async (type: string, row?: any) => {
  actionType.value = type
  if (type == 'add') {
    dialogTitle.value = t('exampleDemo.add')
    currentRow.value = undefined
  }
  if (type == 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
    currentRow.value = {
      is_show: row.is_show ? true : false,
      brand_name: row.brand_name,
      id: row.id,
      fid: 0
    }
    console.log(currentRow, 'currentRow')
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delBrand(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    const arr: string[] = []
    for (const key in formData.slide_images) {
      arr.push(formData.slide_images[key] || '')
    }
    const data: any = {
      is_show: formData.is_show ? 1 : 0,
      brand_name: formData.brand_name,
      id: formData.id,
      fid: 0
    }
    try {
      if (actionType.value === 'edit') {
        await editBrand(data)
      } else if (actionType.value === 'add') {
        await addBrand(data)
      }
      ElMessage({
        showClose: true,
        message: '保存成功',
        type: 'success'
      })
      getList()
      saveLoading.value = false
      dialogVisible.value = false
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton type="primary" @click="action('add')">{{ 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="450px" maxHeight="110px">
    <Write ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
