<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {addCoupon, editCoupon, releaseCoupon,couponList,couponDel,changeCouponField } 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 couponList({
      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: 'type',
    label: '类型',
    width: 80,
    slots: {
      default: ({ row }: any) => {
        return <>{row.type == 1 ? '品类券' : row.type == 2 ? '商品券' : '普通券'}</>
      }
    }
  },
  {
    field: 'time',
    label: '生效时间',
    minWidth: 100,
    slots: {
      default: ({ row }: any) => {
        return <>{row.start_time?row.start_time_chs + ' ~ ' + row.end_time_chs : '永久有效'}</>
      }
    }
  },
  {
    field: 'total_count',
    label: '发布数量',
    minWidth: 100,
    slots: {
      default: ({ row }: any) => {
        if (row.total_count == 0) {
          return <>{'不限量'}</>
        } else {
          return <>
            <div>发布:{row.total_count}</div>
            <div>剩余:{row.remain_count}</div>

          </>
        }
      }
    }
  },
  // 	消费满赠
  {
    field: 'is_full_give',
    label: '消费满赠',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.is_full_give ? 'primary' : 'danger'}>
              {row.is_full_give ? '是' : '否'}
            </ElTag>
          </>
        )
      }
    }
  },
  // 首次关注赠送
  {
    field: 'is_give_subscribe',
    label: '首次关注赠送',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.is_give_subscribe ? 'primary' : 'danger'}>
              {row.is_give_subscribe ? '是' : '否'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'status',
    label: '是否启用',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag class="mr-5px" type={row.status ? 'primary' : 'danger'}>
              {row.status ? '启用' : '停止'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        if (row.status == 0) {
          return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action('list', row)}>
              领取记录
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton  link size="small" type="primary" onClick={() => action('open', row)}>
              开启
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              删除
            </BaseButton>
          </>
        )
        } else {
          return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action('list', row)}>
              领取记录
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton  link size="small" type="danger" onClick={() => action('close', row)}>
              关闭
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              删除
            </BaseButton>
          </>
        )
        }
       
      }
    }
  }
])

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)

const changeCouponFields = (row) => {
  changeCouponField({
    id: row.id,
    field: 'status',
    status: row.status === 1 ? 0 : 1
  }).then(() => {
    getList()
  })
}

// 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
  }
  if (type == 'open' || type == 'close') {
    changeCouponFields(row)
  }
}
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>
