<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getSalespersonLevel,
  addSalespersonLevel,
  putSalespersonLevel,
  delSalespersonLevel
} from '@/api/regulate'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { BaseButton } from '@/components/Button'
import { ElMessage, ElDivider, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { salespersonLevelData } from '@/api/regulate/types'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getSalespersonLevel()
    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: 'award_ratio',
    label: '分成（%）',
    minWidth: 100
  },
  {
    field: 'info',
    label: '等级说明',
    minWidth: 140
  },
  {
    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 dialogVisible = ref(false)
const currentRow = ref<salespersonLevelData>()
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 = {
    id: row.id,
    name: row.name,
    award_ratio: row.award_ratio,
    info: row.info
  }
  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()
  if (formData) {
    saveLoading.value = true
    const data: salespersonLevelData = {
      name: formData.name,
      id: formData.id,
      award_ratio: formData.award_ratio,
      info: formData.info
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        data.id = formData.id
        // console.log(data)
        res = await putSalespersonLevel(data)
      } else if (actionType.value === '') {
        res = await addSalespersonLevel(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 delSalespersonLevel(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
</script>

<template>
  <ContentWrap>
    <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>
