<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {addCoupon, editCoupon, releaseCoupon,couponList,couponDel,couponGetList } from '@/api/marketing'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElDivider, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import Write from './components/Write.vue'
import Record from './components/Record.vue'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await couponGetList({
      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: 'coupon_title',
    label: '优惠券名称',
    minWidth: 150
  },
  {
    field: 'user',
    label: '领取人',
    minWidth: 150,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
          <div >{row.user.nickname} (UID:{row.user.uid})</div>
          </>
        )
      }
    }
  },
  {
    field: 'coupon_price',
    label: '面值',
    minWidth: 100,
  },
  {
    field: 'use_min_price',
    label: '最低消费',
    minWidth: 100
  },
  {
    field: 'status',
    label: '是否使用',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.status == 0 ? 'primary' : 'danger'}>
              {row.status == 0 ? '未使用' :(row.status == 1 ? '已使用' :'已过期') }
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'is_fail',
    label: '是否有效',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.is_fail == 0 ? 'primary' : 'danger'}>
              {row.is_fail == 0 ? '有效' :"失效" }
            </ElTag>
          </>
        )
      }
    }
  }
])

const searchParams = ref<{
  type?: string
}>({
  type: ''
})

const dialogVisible = ref(false)
const dialogVisibles = ref(false)

const currentRow = ref()
const cid = ref(0)

const dialogTitle = ref('')
const actionType = ref('')
const saveLoading = ref(false)

// 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
    dialogVisible.value = true
  }
  if (type == 'list') {
    dialogTitle.value = '领取记录'
    cid.value = row.id*1
    dialogVisibles.value = true
  }
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await couponDel(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async (coupon) => {
  console.log('zhe', coupon)
  const data = {
    type: coupon.type,
    title: coupon.title,
    coupon_price: coupon.coupon_price,
    use_min_price: coupon.use_min_price,
    coupon_time: coupon.coupon_time,
    sort: coupon.sort,
    status: coupon.status,
    category_id: coupon.category_id || ''
  }
  try {
    if (actionType.value === 'edit') {
      await editCoupon(data)
    } else if (actionType.value === 'add') {
      await addCoupon(data)
    }
    ElMessage({
      showClose: true,
      message: '保存成功',
      type: 'success'
    })
    getList()
    saveLoading.value = false
    dialogVisible.value = false
  } catch (error) {
    console.log(error)
  } finally {
    saveLoading.value = false
  }
  // }
}
const release = async (coupon) => {
  // release
  console.log('发布', coupon)

  const data = {
    start_time: coupon.start_time,
    end_time: coupon.end_time,
    is_permanent: coupon.is_permanent,
    total_count: coupon.total_count,
    is_full_give: coupon.is_full_give,
    id: coupon.id,
    full_reduction: coupon.full_reduction,
    status: coupon.status,
    is_give_subscribe: coupon.is_give_subscribe
  }
  try {
    await releaseCoupon(data)
    ElMessage({
      showClose: true,
      message: '发布成功',
      type: 'success'
    })
    getList()
    saveLoading.value = false
    dialogVisibles.value = false
  } catch (error) {
    
  }
}
</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="500px">
    <Write ref="writeRef" :current-row="currentRow" @addCoupon="save" />
    <!-- <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template> -->
  </Dialog>
  <Dialog v-model="dialogVisibles" :title="dialogTitle" width="800px" maxHeight="500px">
<Record :cid="cid"></Record>
  </Dialog>
  <!--  -->
</template>
