<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getStaffSalesperson,
  addStaffSalesperson,
  putStaffSalesperson,
  delStaffSalesperson
} from '@/api/staff'
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 { ElMessage, ElDivider, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { TableImage } from '@/components/tableImage'
import { SalespersonData } from '@/api/staff/types'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getStaffSalesperson({
      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',
    width: 70
  },
  {
    field: 'avatar',
    label: '头像',
    width: 80,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <TableImage src={row.avatar} />
          </>
        )
      }
    }
  },
  {
    field: 'name',
    label: '姓名',
    minWidth: 100
  },
  {
    field: 'phone',
    label: '手机号',
    minWidth: 120
  },
  {
    field: 'area',
    label: '区域',
    minWidth: 200,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            {row.province_text} {row.city_text} {row.area_text}
          </>
        )
      }
    }
  },
  {
    field: 'detail_address',
    label: '定位',
    minWidth: 150
  },
  {
    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: 'name',
    label: '姓名',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入姓名'
    }
  }
])

const searchParams = ref({
  name: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const currentRow = ref()
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 = {
    name: row.name,
    uid: row.uid,
    id: row.id,
    phone: row.phone,
    avatar: [row.avatar],
    province: row.province,
    city: row.city,
    area: row.area,
    longitude: row.longitude,
    latitude: row.latitude,
    detail_address: row.detail_address,
    parent_id: row.parent_id,
    salesperson_status: row.salesperson_commission === '-1.00' ? false : true,
    salesperson_commission:
      row.salesperson_commission === '-1.00' ? '默认' : row.salesperson_commission
  }
  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: SalespersonData = {
      name: formData.name,
      uid: formData.uid,
      phone: formData.phone,
      avatar: formData.avatar[0],
      province: formData.province,
      city: formData.city,
      area: formData.area,
      longitude: formData.longitude,
      latitude: formData.latitude,
      detail_address: formData.detail_address,
      parent_id: formData.parent_id,
      salesperson_commission:
        formData.salesperson_commission === '默认' ? '-1.00' : formData.salesperson_commission
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        data.id = formData.id
        res = await putStaffSalesperson(data)
      } else if (actionType.value === '') {
        res = await addStaffSalesperson(data)
      }
      if (res?.status === 200) {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success'
        })
        getList()
        dialogVisible.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 delStaffSalesperson(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <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="900px" max-height="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>
