<script setup lang="tsx">
import { reactive, ref, unref, onMounted } from 'vue'
import { getDesigner, addDesigner, putDesigner, delDesigner, getDesignerGroup } 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, ElTag } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { TableImage } from '@/components/tableImage'
import { designerData, designerSearch } from '@/api/staff/types'
import { formatToDate } from '@/utils/dateUtil'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getDesigner({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })
    return {
      list: res.data.list.map((ree) => {
        ree.tag_list_chs = ree.tag_list_chs.filter((fil) => fil.length > 0)
        return ree
      }),
      total: res.data.count || 0
    }
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
const groupList = ref([])
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: 160,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            姓名：{row.name}（{row.gender_chs}）<br></br>
            手机：{row.phone}
          </>
        )
      }
    }
  },
  {
    field: 'group',
    label: '所属组',
    align: 'center',
    width: 100,
    slots: {
      default: ({ row }: any) => {
        return <>{row.group ? row.group.name : ''}</>
      }
    }
  },
  {
    field: 'start_job_year',
    label: '就业年份',
    align: 'center',
    headerAlign: 'center',
    minWidth: 100
  },
  {
    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: 'tag_list_chs',
    label: '标签',
    minWidth: 160,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            {row.tag_list_chs.map((item: any) => {
              return (
                <>
                  <ElTag class="mr-5px" type="primary">
                    {item}
                  </ElTag>
                </>
              )
            })}
          </>
        )
      }
    }
  },
  {
    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: 'gender',
    label: '性别',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '性别',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '保密',
          value: 0
        },
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        }
      ]
    }
  },
  {
    field: 'group_id',
    label: '组',
    component: 'Select',
    componentProps: {
      placeholder: '请选择要搜索的组'
    },
    optionApi: async () => {
      const res = await getDesignerGroup({ page: 1, limit: 100 })
      groupList.value = res.data.list.map((ree) => {
        return {
          value: ree.id,
          label: ree.name
        }
      })
      return groupList.value
    }
  },
  {
    field: 'tag_list',
    label: '标签',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入搜索标签'
    }
  },

  {
    field: 'name',
    label: '姓名',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入姓名'
    }
  }
])

const searchParams = ref<designerSearch>({
  gender: '',
  tag_list: '',
  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],
    gender: row.gender,
    birth_day_time: formatToDate(row.birth_day_time * 1000),
    province: row.province,
    city: row.city,
    area: row.area,
    tag_list: row.tag_list,
    longitude: row.longitude,
    latitude: row.latitude,
    detail_address: row.detail_address,
    start_job_year: row.start_job_year,
    group_id: row.group_id == 0 ? '' : row.group_id
  }
  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: designerData = {
      name: formData.name,
      uid: formData.uid,
      phone: formData.phone,
      avatar: formData.avatar[0],
      gender: formData.gender,
      birth_day_time: formatToDate(formData.birth_day_time),
      province: formData.province,
      city: formData.city,
      area: formData.area,
      longitude: formData.longitude,
      latitude: formData.latitude,
      detail_address: formData.detail_address,
      start_job_year: formData.start_job_year,
      group_id: !formData.group_id ? 0 : formData.group_id
    }
    if (formData.tag_list) {
      data.tag_list = formData.tag_list.filter((fil) => fil.length > 0)
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        data.id = formData.id
        res = await putDesigner(data)
      } else if (actionType.value === '') {
        res = await addDesigner(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 delDesigner(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
      :groupList="groupList"
      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>
