<template>
  <CommonPage show-footer :title="$route.title">
    <n-button v-perms="['/admin/rotation/edit']" type="primary" @click="handleAdd(1)">
      新增幻灯片
    </n-button>
    <n-data-table
      :loading="loading"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
    />
    <n-modal v-model:show="showModal" :auto-focus="false">
      <n-card
        style="width: 600px"
        :title="modelTitle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-form ref="formRef" label-placement="left" :model="formValue" :rules="rules">
          <n-form-item label="图片：" path="url">
            <Upload v-model:list="formValue.url" />
          </n-form-item>
          <n-form-item label="链接：" path="jump">
            <div flex items-center>
              <n-button class="m-auto" type="primary" attr-type="button" @click="handleJump">
                选择链接
              </n-button>
              <span ml-10>{{ formValue.jump || '暂无' }}</span>
            </div>
          </n-form-item>
          <n-form-item label="状态：" path="status">
            <n-switch v-model:value="formValue.status" :checked-value="1" :unchecked-value="2" />
          </n-form-item>
          <n-form-item>
            <div class="m-auto">
              <n-button
                class="m-auto"
                type="primary"
                attr-type="button"
                @click="handleValidateClick"
              >
                提交
              </n-button>
              <n-button class="ml-10" @click="clear">取消</n-button>
            </div>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>
    <!-- 选择地址 -->
    <n-modal v-model:show="showUrlModal">
      <n-card
        style="width: 900px"
        title="链接选择"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <template #header-extra>
          <n-button quaternary circle>
            <template #icon>
              <TheIcon
                icon="ant-design:close-outlined"
                :size="20"
                @click="showUrlModal = !showUrlModal"
              />
            </template>
          </n-button>
        </template>
        <div w-full flex>
          <n-menu
            v-model:value="activeKey"
            class="w-150"
            :options="menuOptions"
            @update:value="handleUpdateExpandedKeys"
          />
          <n-data-table
            v-if="activeKey === 1"
            v-model:checked-row-keys="checkedRowKeys"
            :row-key="(row) => row.bid"
            :loading="loading1"
            :columns="columns1"
            :data="data1"
            :pagination="pagination1"
            :bordered="false"
            remote
            @update:checked-row-keys="handleUpdateCheckedRowKeys"
          />
          <n-data-table
            v-else
            v-model:checked-row-keys="checkedRowKeys"
            :row-key="(row) => row.gid"
            :loading="loading2"
            :columns="columns2"
            :data="data2"
            :pagination="pagination2"
            :bordered="false"
            remote
            @update:checked-row-keys="handleUpdateCheckedRowKeys"
          />
        </div>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { onMounted, h, withDirectives, resolveDirective } from 'vue'
import api from './api'
import api1 from '@/views/business/mer_list/api'
import api2 from '@/views/commodity/hot_list/api'
import { NButton, NImage, NEllipsis } from 'naive-ui'
import Upload from '@/components/Upload.vue'
const vPerms = resolveDirective('perms')

const loading = ref(false)

const columns = ref([
  {
    title: 'ID',
    align: 'center',
    key: 'ID',
  },
  {
    title: '图片',
    align: 'center',
    slot: 'url',
    render(row) {
      return h(NImage, {
        width: '50',
        src: row.url[0]?.url || '',
      })
    },
  },
  {
    title: '状态',
    align: 'center',
    slot: 'status',
    render(row) {
      return h('span', row.status === 1 ? '正常' : '禁用')
    },
  },
  {
    title: '操作',
    align: 'center',
    slot: 'action',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              type: 'primary',
              size: 'small',
              onClick: () => {
                formValue.value = row
                handleAdd(2)
              },
            },
            () => '编辑'
          ),
          [[vPerms, ['/admin/rotation/edit']]]
        ),
      ]
    },
  },
])

const data = ref([])

const formRef = ref(null)

const rules = {
  url: {
    required: true,
    type: 'array',
    message: '请上传图片',
  },
}

const formValue = ref({
  url: [],
  status: 1,
  jump: '',
})

const showModal = ref(false)

const showUrlModal = ref(false)

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

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

const getList = async () => {
  loading.value = true
  try {
    const res = await api.getBanner({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
    })
    console.log(res)
    data.value = res.data.data.map((item) => ({
      ...item,
      url: [
        {
          id: item.ID,
          url: item.url,
          status: 'finished',
        },
      ],
    }))
  } catch (error) {
    $message.error(error.msg)
  }
  loading.value = false
}

const modelTitle = ref('')

const handleAdd = (e) => {
  modelTitle.value = e === 1 ? '新增幻灯片' : '编辑幻灯片'
  showModal.value = true
}

const clear = () => {
  formValue.value = {
    name: '',
    status: 1,
    jump: '',
  }
  showModal.value = false
}

const handleValidateClick = async (e) => {
  e.preventDefault()
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        const data = {
          ...formValue.value,
          url: formValue.value.url[0].url,
          status: formValue.value.status,
        }
        await api.addBanner(data)
        $message.success('成功')
        clear()
        getList()
      } catch (error) {
        $message.error(error.msg)
      }
    } else {
      $message.error('Invalid')
    }
  })
}

const handleJump = () => {
  getList1()
  showUrlModal.value = true
}

const menuOptions = [
  {
    label: '商家页面',
    key: 1,
  },
  {
    label: '商品页面',
    key: 2,
  },
]

const activeKey = ref(1)

const handleUpdateExpandedKeys = () => {
  if (activeKey.value === 1) {
    getList1()
  } else {
    getList2()
  }
}

const columns1 = ref([
  {
    type: 'selection',
    multiple: false,
    align: 'center',
  },
  {
    title: '商户ID',
    align: 'center',
    key: 'bid',
  },
  {
    title: '商户名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '状态',
    align: 'center',
    slot: 'status',
    render(row) {
      return h('span', row.status === 1 ? '正常' : '禁用')
    },
  },
])

const checkedRowKeys = ref([])

const data1 = ref([])

const loading1 = ref(false)

const pagination1 = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  onChange: (page) => {
    pagination1.value.page = page
    getList1()
  },
  onUpdatePageSize: (pageSize) => {
    pagination1.value.pageSize = pageSize
    pagination1.value.page = 1
    getList1()
  },
})

const getList1 = async () => {
  loading.value = true
  const res = await api1.getList({
    PageNum: pagination1.value.page,
    PageSize: pagination1.value.pageSize,
  })
  data1.value = res.data.data || []
  pagination1.value.itemCount = res.data.total
  loading.value = false
}

const columns2 = ref([
  {
    type: 'selection',
    multiple: false,
    align: 'center',
  },
  {
    title: '商品名称',
    slot: 'name',
    align: 'center',
    render: (row) => {
      return h(
        NEllipsis,
        {
          style: 'max-width: 200px',
        },
        {
          default: () => row.name,
        }
      )
    },
  },
  {
    title: '商品封面',
    slot: 'cover',
    align: 'center',
    render(row) {
      return h(NImage, {
        src: row.cover,
        width: '30',
      })
    },
  },
  {
    title: '商品分类',
    slot: 'Classify',
    align: 'center',
    render(row) {
      return h(
        'div',
        {},
        {
          default: () => row.Classify.name,
        }
      )
    },
  },
  {
    title: '商品价格(元)',
    key: 'number',
    align: 'center',
  },
  {
    title: '商品库存',
    key: 'stock',
    align: 'center',
  },
])

const data2 = ref([])

const loading2 = ref(false)

const pagination2 = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  onChange: (page) => {
    pagination2.value.page = page
    getList2()
  },
  onUpdatePageSize: (pageSize) => {
    pagination2.value.pageSize = pageSize
    pagination2.value.page = 1
    getList2()
  },
})

const getList2 = async () => {
  loading.value = true
  try {
    const res = await api2.getHotlist({
      pageNum: pagination2.value.page,
      pageSize: pagination2.value.pageSize,
    })
    data2.value = res.data.data || []
    pagination2.value.itemCount = res.data.total
  } catch (error) {
    $message.error(error.msg)
  }
  loading.value = false
}

const handleUpdateCheckedRowKeys = (e) => {
  formValue.value.jump =
    activeKey.value === 1
      ? `/pages/mer/mer_detail/index?type=${activeKey.value}&bid=${e[0]}`
      : `/pages/goods/goods_detail/index?type=${activeKey.value}&gid=${e[0]}`
  showUrlModal.value = false
  checkedRowKeys.value = []
}
</script>

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