<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
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 { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { TableImage } from '@/components/tableImage'
import { UpImgButtom } from '@/components/UpFile'
import {
  FormInstance,
  ElDivider,
  ElMessage,
  ElMessageBox,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElSwitch} from 'element-plus'
import { getIndex, addIndex, editIndex,delIndex } from '@/api/system/config'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getIndex({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })
    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'
  },
  {
    field: 'image',
    label: '图片',
    width: 80,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <TableImage src={row.image} />
          </>
        )
      }
    }
  },
  {
    field: 'type_chs',
    label: '类型',
    minWidth: 100
  },
  {
    field: 'title',
    label: '标题',
    minWidth: 100
  },
  {
    field: 'path',
    label: '路径',
    minWidth: 100
  },
  {
    field: 'sort',
    label: '排序',
    minWidth: 150
  },
  {
    field: 'is_show',
    label: '是否显示',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <ElSwitch
            disabled
              v-model={row.is_show}
              active-value={1}
              inactive-value={0}
              inline-prompt
              active-text="是"
              inactive-text="否"
            />
          </>
        )
      }
    }
  },
  {
    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 searchSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '首页轮播',
          value: '0'
        },
        {
          label: '菜单导航',
          value: '1'
        },
        {
          label: '收银轮播',
          value: '2'
        },
        {
          label: '开屏广告',
          value: '3'
        }
      ]
    }
  },
])

const searchParams = ref<{
  type?: string 
}>({
  type: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

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



// 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 = '新增'
    currentRow.value = undefined
  }
  if (type == 'edit') {
    dialogTitle.value = '编辑'
    formData.type = row.type
    formData.id = row.id
    formData.title = row.title
    formData.path = row.path
    formData.image = [row.image]
    formData.sort = row.sort || 0
    formData.is_show = row.is_show
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delIndex(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const formRef = ref<FormInstance>()
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return []
  const valid = await formEl.validate((valid, fields) => {
    if (valid) {
    } else {
      for (const key in fields) {
        ElMessage.error(fields[key][0].message)
        return
      }
      console.log('error submit!', fields)
    }
  })
  if (valid) {
    let res: any
    const data = {
      id: formData.id,
      type: formData.type,
      title: formData.title,
      path: formData.path,
      sort: formData.sort,
      is_show: formData.is_show,
      image: formData.image[0]
    }
    if (formData.id) {
      res = await editIndex(formData.id, data)
    } else {
      res = await addIndex(data)
    }

    if (res.status == 200) {
      ElMessage.success(dialogTitle.value + '成功')
      choses()
      getList()
    }
  }
}

const formData = reactive<any>({
  id: '',
  type: 0,
  image: [],
  sort: 0,
  is_show: 1,
  title: '',
  path: ''
})
const rules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  image: [{ required: true, message: '请选择图片', trigger: 'change' }]
})
const choses = () => {
  dialogVisible.value = false
  formData.sort = 0
  formData.path = ''
  formData.is_show = 1
  formData.title = ''
  formData.image = []
  formData.id = ''
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <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="800px"
    maxHeight="300px"
    @close="choses"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="类型" prop="type">
        <ElRadioGroup v-model="formData.type" class="ml5">
          <ElRadio :label="0" size="large">首页轮播</ElRadio>
          <ElRadio :label="1" size="large">菜单导航</ElRadio>
          <ElRadio :label="2" size="large">收银轮播</ElRadio>
          <ElRadio :label="3" size="large">开屏广告</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="图片" prop="image">
        <UpImgButtom :num="1" v-model="formData.image"></UpImgButtom>
      </ElFormItem>
      <ElFormItem label="标题" prop="title">
        <ElInput type="text" v-model="formData.title" />
      </ElFormItem>
      <ElFormItem label="路径" prop="path">
        <ElInput type="text" v-model="formData.path" />
      </ElFormItem>
      <ElFormItem label="排序" prop="sort">
        <ElInput type="number" v-model="formData.sort" />
      </ElFormItem>
      <ElFormItem label="显示" prop="is_show">
        <ElRadioGroup v-model="formData.is_show" class="ml5">
          <ElRadio :label="1" size="large">是</ElRadio>
          <ElRadio :label="0" size="large">否</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save(formRef)">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style>
.el-radio.el-radio--large {
  height: 32px !important;
}
</style>
