<script setup lang="tsx">
import { reactive, ref, unref, computed } from 'vue'
import {
  getClassConfigList,
  addClassConfig,
  putClassConfig,
  delClassConfig,
  putClassConfigStatus
} from '@/api/system/config'
import type { classConfigUp } 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 { ContentWrap } from '@/components/ContentWrap'
import Write from './components/detailWrite.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { useRoute, useRouter } from 'vue-router'
import { isArray } from 'lodash-es'
import { TableImage } from '@/components/tableImage'

const { back } = useRouter()
const { params, query } = useRoute()
const { t } = useI18n()
const id = ref<string>(Array.isArray(params.id) ? params.id[0] || '' : params.id || '')
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getClassConfigList({
      tab_id: unref(id),
      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',
    width: 80
  },
  {
    field: 'info',
    label: '名称',
    minWidth: 100
  },
  {
    field: 'menu_name',
    label: '参数',
    minWidth: 100
  },
  {
    field: 'type',
    label: '类型',
    headerAlign: 'center',
    align: 'center',
    width: 130
  },
  {
    field: 'value',
    label: '默认值',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        if (row.type == 'RadioGroup' || row.type == 'CheckboxGroup' || row.type == 'Select') {
          let label: string = ''
          for (let i = 0; i < row.configuration?.options?.length; i++) {
            row.value = row.value ? row.value : '0'
            if (row.configuration?.options[i].value == row.value) {
              label = row.configuration?.options[i].label
              break
            }
          }
          return <>{label}</>
        } else if (row.type == 'Upload' && Array.isArray(data.row.value)) {
          const arr = row.value.map((item: any) => {
            return item.filepath
          })
          return (
            <>
              {arr.map((item: string, ind) => {
                return (
                  <>
                    <TableImage src={item} list={arr} ind={ind} />
                  </>
                )
              })}
            </>
          )
        } else {
          return (
            <>
              <span>{data.row.value}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'sort',
    label: '排序',
    headerAlign: 'center',
    align: 'center',
    width: 60
  },
  {
    field: 'status',
    label: '状态',
    align: 'center',
    headerAlign: 'center',
    width: 70,
    slots: {
      default: (data: any) => {
        const status = data.row.status == 1
        return (
          <>
            <ElSwitch v-model={status} onChange={() => putClassStatus(data.row)}></ElSwitch>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 110,
    headerAlign: 'center',
    align: '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 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 || '', //修改id
    config_tab_id: unref(id), //所属分类
    status: row.status == 1 ? true : false, //是否启用
    menu_name: row.menu_name, //字段变量
    info: row.info, //配置名称
    type: row.type, //组件类型
    value: row.value, //当前设置参数值
    desc: row.desc, //描述
    sort: row.sort, //排序
    is_store: row.is_store, //系统
    permissionList: row.configuration?.options || [], //默认选项
    required: row.configuration?.required || [], //验证类型
    maxlength: row.configuration?.maxlength, //最长字数
    minlength: row.configuration?.minlength, //最短字数
    input_type: row.configuration?.input_type, //输入框类型
    upload_type: row.configuration?.upload_type //上传类型
  }
  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 delClassConfig({ id: row.id })
      await getList()

      ElMessage({
        showClose: true,
        message: '删除',
        type: 'success'
      })
    })
    .catch(() => {})
}
const putClassStatus = (row: any) => {
  putClassConfigStatus({ 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
    // console.log(formData, 'formData')
    const data: classConfigUp = {
      id: formData.id || '', //修改id
      config_tab_id: unref(id), //所属分类
      status: formData.status ? 1 : 0, //是否启用
      menu_name: formData.menu_name, //字段变量
      info: formData.info, //配置名称
      type: formData.type, //组件类型
      value: formData.value || '', //当前设置参数值
      desc: formData.desc || '', //描述
      sort: formData.sort, //排序
      is_store: formData.is_store, //系统
      configuration: {
        options: formData.permissionList || [], //默认选项
        required: formData.required || [], //验证类型
        maxlength: formData.maxlength, //最长字数
        minlength: formData.minlength, //最短字数
        input_type: formData.input_type, //输入框类型
        upload_type: formData.upload_type //上传类型
      }
    }
    // return
    if (actionType.value === 'edit') {
      if (data.type == 'Upload' && data.configuration.upload_type != 2 && isArray(formData.value)) {
        data.value = ''
      }
      await putClassConfig(data)
    } else if (actionType.value === '') {
      await addClassConfig(data)
    }
    ElMessage({
      showClose: true,
      message: '保存成功',
      type: 'success'
    })
    getList()
    saveLoading.value = false
    dialogVisible.value = false
  }
}

const backPage = () => {
  back()
}
const title = computed(() => {
  const titleValue = query.title
  if (Array.isArray(titleValue)) {
    return titleValue.join(', ') // 或者根据业务需求选择其他处理方式
  }
  return titleValue || ''
})
</script>

<template>
  <ContentWrap :title="title">
    <div class="mb-10px">
      <BaseButton @click="backPage">返回</BaseButton>
      <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"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog top="100px" maxHeight="500px" v-model="dialogVisible" :title="dialogTitle" width="800">
    <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>
