<script setup lang="tsx">
import { reactive, ref, unref, onMounted } from 'vue'
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 {
  FormInstance,
  ElDivider,
  ElMessage,
  ElMessageBox,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElOption,
  ElSelect
} from 'element-plus'
import { getREchange, addRechange, delRechange, editRechange } from '@/api/marketing'
import { getStoreList } from '@/api/erp'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getREchange({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count || 0
    }
  }
})
const storeList = ref<any[]>([])
onMounted(async () => {
  const res = await getStoreList({ page: 1, limit: 1000, store: 1 })
  storeList.value = res.data.data.map((item) => {
    return {
      value: item.id,
      label: item.name
    }
  })
})
const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center'
  },
  {
    field: 'type_chs',
    label: '类型',
    minWidth: 100
  },
  {
    field: 'price',
    label: '充值金额',
    minWidth: 150
  },

  {
    field: 'gift_price',
    label: '赠送金额'
  },
  {
    field: 'store_name',
    label: '门店'
  },
  {
    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: '',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '全局',
          value: 0
        },
        {
          label: '门店',
          value: 1
        }
      ]
    }
  },
  {
    field: 'store_id',
    label: '门店',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择门店',
      options: storeList
    }
  }
])

const searchParams = ref<{
  store_id?: string | number
}>({
  store_id: ''
})
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)

// 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 = '新增'
    currentRow.value = undefined
  }
  if (type == 'edit') {
    dialogTitle.value = '编辑'
    formData.type = row.type
    formData.applicable_store_id = row.applicable_store_id.split(',').map((item) => {
      return +item
    })
    formData.price = row.price
    formData.gift_price = row.gift_price
    formData.id = row.id
    formData.sort = row.sort || 0
    formData.status = row.status
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delRechange(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const formRef = ref<FormInstance>()
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return []
  const valid = await formEl.validate((valid, fields) => {
    if (valid) {
    } else {
      for (const key in fields) {
        ElMessage.error(fields[key][0].message)
        return
      }
      console.log('error submit!', fields)
    }
  })
  if (valid) {
    let res: any
    if (formData.id) {
      res = await editRechange({
        id: formData.id,
        type: formData.type,
        price: formData.price,
        gift_price: formData.gift_price,
        sort: formData.sort,
        status: formData.status,
        applicable_store_id: formData.applicable_store_id.join(',')
      })
    } else {
      res = await addRechange({
        id: formData.id,
        type: formData.type,
        price: formData.price,
        gift_price: formData.gift_price,
        sort: formData.sort,
        status: formData.status,
        applicable_store_id: formData.applicable_store_id.join(',')
      })
    }

    if (res.status == 200) {
      ElMessage.success(dialogTitle.value + '成功')
      choses()
      getList()
    }
  }
}

const formData = reactive<any>({
  id: '',
  type: 0,
  applicable_store_id: [],
  sort: 0,
  status: 1,
  price: '',
  gift_price: ''
})
const rules = reactive({
  applicable_store_id: [{ required: true, message: '请选择门店', trigger: 'change' }],
  price: [{ required: true, message: '请输入充值金额', trigger: 'blur' }]
})
const choses = () => {
  dialogVisible.value = false
  formData.sort = 0
  formData.price = ''
  formData.status = 1
  formData.gift_price = ''
  formData.applicable_store_id = []
  formData.id = ''
}
</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="300px"
    @close="choses"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="类型" prop="type">
        <ElRadioGroup v-model="formData.type" class="ml5">
          <ElRadio :label="0" size="large">全局</ElRadio>
          <ElRadio :label="1" size="large">门店</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="门店" prop="applicable_store_id" v-if="formData.type == 1">
        <ElSelect v-model="formData.applicable_store_id" multiple placeholder="请选择门店">
          <ElOption
            v-for="item in storeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="充值金额" prop="price">
        <ElInput type="number" v-model="formData.price" />
      </ElFormItem>
      <ElFormItem label="赠送金额" prop="gift_price">
        <ElInput type="number" v-model="formData.gift_price" />
      </ElFormItem>
      <ElFormItem label="排序" prop="sort">
        <ElInput type="number" v-model="formData.sort" />
      </ElFormItem>
      <ElFormItem label="状态" prop="status">
        <ElRadioGroup v-model="formData.status" class="ml5">
          <ElRadio :label="1" size="large">启用</ElRadio>
          <ElRadio :label="0" size="large">禁用</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save(formRef)">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style>
.el-radio.el-radio--large {
  height: 32px !important;
}
</style>
