<template>
  <CommonPage show-footer :title="$route.title">
    <n-button v-perms="['/admin/paytype/add']" type="primary" @click="openModal(1)">
      添加支付方式
    </n-button>
    <n-data-table
      class="mt-5"
      :loading="loading"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
    />

    <n-modal v-model:show="showModal">
      <n-card
        style="width: 600px"
        title="添加/编辑支付方式"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-form ref="formRef" :model="model" :rules="rules" label-placement="left">
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="16" label="支付图标:" path="icon">
              <Upload v-model:list="model.icon" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="支付名称:" path="name">
              <n-input v-model:value="model.name" placeholder="请输入支付名称" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="启用状态:">
              <n-switch v-model:value="model.status" :checked-value="1" :unchecked-value="2" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="余额状态:" path="state">
              <n-select
                v-model:value="model.state"
                :options="[
                  {
                    label: '无限',
                    value: 1,
                  },
                  {
                    label: '有限',
                    value: 2,
                  },
                ]"
              />
            </n-form-item-gi>
            <n-form-item-gi v-if="model.state === 2" :span="16" label="商家余额:" path="amount">
              <n-input-number v-model:value="model.amount" placeholder="请输入商家余额" />
            </n-form-item-gi>
            <n-form-item-gi :span="18">
              <div m-auto>
                <n-button type="primary" @click="handleValidateClick">保存</n-button>
                <n-button ml-10 @click="clear">取消</n-button>
              </div>
            </n-form-item-gi>
          </n-grid>
        </n-form>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { h, withDirectives, resolveDirective } from 'vue'
import api from './api'
import { NTag, NButton } from 'naive-ui'
import Upload from '@/components/Upload.vue'

const vPerms = resolveDirective('perms')

onMounted(() => {
  getList()
})

const loading = ref(false)

const columns = ref([
  {
    title: 'icon',
    slot: 'icon',
    align: 'center',
    render: (row) => {
      return h('img', {
        src: row.icon[0].url,
        width: 50,
        height: 50,
      })
    },
  },
  {
    title: '支付名称',
    key: 'name',
    align: 'center',
  },
  {
    title: '状态',
    slot: 'status',
    align: 'center',
    render: (row) => {
      return h(
        NTag,
        {
          type: row.status === 1 ? 'success' : 'warning',
        },
        {
          default: () => (row.status === 1 ? '启用' : '禁用'),
        }
      )
    },
  },
  {
    title: '商家余额',
    slot: 'amount',
    align: 'center',
    render: (row) => {
      return h(
        'span',
        {},
        {
          default: () => (row.state === 1 ? '无限' : row.amount),
        }
      )
    },
  },
  {
    title: '余额状态',
    slot: 'state',
    align: 'center',
    render: (row) => {
      return h(
        'span',
        {},
        {
          default: () => (row.state === 1 ? '无限' : '有限'),
        }
      )
    },
  },
  {
    title: '操作',
    slot: 'action',
    align: 'center',
    render: (row) => {
      return [
        withDirectives(
          h(
            NButton,
            {
              text: true,
              onClick: () => {
                openModal(2, row)
              },
            },
            {
              default: () => '编辑',
            }
          ),
          [[vPerms, ['/admin/paytype/edit']]]
        ),
      ]
    },
  },
])

const data = ref([])

const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  onChange: (page) => {
    pagination.value.page = page
    getList()
  },
})

const getList = async () => {
  loading.value = true
  const res = await api.getData({
    page: pagination.value.page,
    pageSize: pagination.value.pageSize,
  })
  data.value =
    res.data.data.map((item) => ({
      ...item,
      icon: [
        {
          id: item.ID,
          url: item.icon,
          status: 'finished',
        },
      ],
    })) || []
  // console.log(res)
  pagination.value.itemCount = res.data.total
  loading.value = false
}

const showModal = ref(false)

const model = ref({
  icon: [],
  name: '',
  status: 1,
  state: 1,
  amount: 0,
})

const formRef = ref(null)

const rules = ref({
  icon: {
    required: true,
    type: 'array',
    message: '请上传图片',
  },
  name: {
    required: true,
    message: '请输入支付名称',
  },
  state: {
    required: true,
    type: 'number',
    message: '请选择余额状态',
  },
  amount: {
    required: true,
    type: 'number',
    message: '请输入商家余额',
  },
})

const nowType = ref(1)

const openModal = (type, row = {}) => {
  nowType.value = type
  if (type === 2) {
    model.value = {
      ...row,
    }
  }
  showModal.value = true
}

const handleValidateClick = async (e) => {
  e.preventDefault()
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        const data = {
          ...model.value,
          icon: model.value.icon[0].url,
        }
        if (nowType.value === 1) {
          await api.add(data)
        } else {
          await api.edit(data)
        }
        clear()
        getList()
      } catch (error) {
        $message.error(error.msg)
      }
    }
  })
}
const clear = async () => {
  model.value = {
    icon: [],
    name: '',
    status: 1,
    state: 1,
    amount: 0,
  }
  showModal.value = false
}
</script>

<style lang="scss" scoped></style>
