<script setup lang="tsx">
import { reactive, ref, unref, useTemplateRef } from 'vue'
import { getStoreList, addStore, editStore, delStore } from '@/api/store'
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 { ElDivider, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { TableImage } from '@/components/tableImage'
import Write from './components/Write.vue'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getStoreList({
      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: 'logo',
    label: 'LOGO',
    width: 80,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <TableImage src={row.logo} />
          </>
        )
      }
    }
  },
  {
    field: 'name',
    label: '门店名称',
    minWidth: 100
  },
  {
    field: 'introduction',
    label: '简介',
    minWidth: 150
  },
  {
    field: 'type',
    label: '类型',
    width: 80,
    slots: {
      default: ({ row }: any) => {
        return <>{row.type == 1 ? '自营' : '加盟'}</>
      }
    }
  },
  {
    field: 'manager_name',
    label: '店长',
    width: 80
  },
  {
    field: 'phone',
    label: '联系号码',
    width: 150
  },
  {
    field: 'detailed_address',
    label: '地址',
    minWidth: 150
  },
  {
    field: 'valid_range',
    label: '有效距离（km）',
    width: 150
  },
  {
    field: 'product_verify_status',
    label: '商品免审核',
    width: 150,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.product_verify_status ? 'primary' : 'danger'}>
              {row.product_verify_status ? '开启' : '关闭'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'product_status',
    label: '自主添加商品',
    width: 150,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.product_status ? 'primary' : 'danger'}>
              {row.product_status ? '开启' : '关闭'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'is_show',
    label: '是否显示',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.is_show ? 'primary' : 'danger'}>
              {row.is_show ? '显示' : '隐藏'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    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: '1',
    componentProps: {
      placeholder: '自营',
      options: [
        {
          label: '自营',
          value: '1'
        },
        {
          label: '加盟',
          value: '2'
        }
      ]
    }
  },
  {
    field: 'name',
    label: '名称',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入门店名称'
    }
  }
])

const searchParams = ref<{
  type?: string
}>({
  type: '1'
})
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)
const writeRef = useTemplateRef('writeRef')

// 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 = t('exampleDemo.add')
    currentRow.value = undefined
  }
  if (type == 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
    currentRow.value = {
      uid: row.uid,
      id: row.id,
      name: row.name,
      is_show: row.is_show == 1 ? true : false,
      introduction: row.introduction,
      address: row.address,
      area: row.area,
      city: row.city,
      province: row.province,
      detailed_address: row.detailed_address,
      latitude: row.latitude,
      logo: [row.logo],
      longitude: row.longitude,
      manager_name: row.manager_name,
      phone: row.phone,
      product_verify_status: row.product_verify_status == 1 ? true : false,
      product_status: row.product_status == 1 ? true : false,
      valid_range: row.valid_range,
      slide_images: row.slide_images_chs
    }
    console.log(currentRow, 'currentRow')
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delStore(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    const arr: string[] = []
    for (const key in formData.slide_images) {
      arr.push(formData.slide_images[key] || '')
    }
    const data: any = {
      uid: formData.uid,
      id: formData.id || '',
      name: formData.name,
      type: formData.type,
      logo: formData.logo[0],
      introduction: formData.introduction,
      slide_images: arr,
      manager_name: formData.manager_name,
      phone: formData.phone,
      valid_range: formData.valid_range,
      product_status: formData.product_status ? 1 : 0,
      product_verify_status: formData.product_verify_status ? 1 : 0,
      detailed_address: formData.detailed_address,
      address: formData.address,
      area: formData.area,
      city: formData.city,
      province: formData.province,
      latitude: formData.latitude,
      longitude: formData.longitude,
      is_show: formData.is_show ? 1 : 0,
      store_account: formData.store_account,
      store_password: formData.store_password
    }
    try {
      if (actionType.value === 'edit') {
        await editStore(data)
      } else if (actionType.value === 'add') {
        await addStore(data)
      }
      ElMessage({
        showClose: true,
        message: '保存成功',
        type: 'success'
      })
      getList()
      saveLoading.value = false
      dialogVisible.value = false
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
</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="700px">
    <Write ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
