<template>
  <div>
    <search-module :search="search" :table="table">
      <template #btn>
        <el-button @click="onAddOrEdit('add', null)" type="success">新增</el-button>
      </template>
    </search-module>
    <table-module :table="table">
      <template #headerBtn>
        <el-radio-group v-model="commodityType" @change="onChangeCommodityType">
          <el-radio-button
            v-for="item in commodityTypeOptions"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</el-radio-button
          >
        </el-radio-group>
      </template>
    </table-module>
  </div>
</template>

<script lang="ts" setup>
import { initConfig } from './config'
import { useCommodityType } from './use-method'

const router = useRouter()
/** 新增&编辑 */
const onAddOrEdit = (type: string, row: any) => {
  router.push({ name: '/goods/detail', query: { type, id: row.id } })
}

/** 复制 */
const onCopy = (row: any) => {}

// 加入首页
const onAddHome = (row: any) => {
  handleMessageBox({
    msg: `是否加入首页?`,
    success: api.commodity.addOrUpdateCommodity.post!,
    data: { id: row.id, frontPage: 1 }
  }).then(() => {
    table.value.$onGetData(table.value)
  })
}

// 删除
const onDelete = (row: any) => {
  handleMessageBox({
    msg: `是否确认删除吗?`,
    success: api.commodity.addOrUpdateCommodity.post!,
    data: { id: row.id, status: 'delete' }
  }).then(() => {
    table.value.$onGetData(table.value)
  })
}

// 改变上下架
const onChangeStatus = (row: any) => {
  const type = row.status === 'online' ? '下架' : '上架'
  handleMessageBox({
    msg: `是否确认${type}吗?`,
    success: api.commodity.addOrUpdateCommodity.post!,
    data: {
      id: row.id,
      status: row.status === 'online' ? 'down' : 'online'
    }
  }).then(() => {
    table.value.$onGetData(table.value)
  })
}

/** 初始化页面 */
const ConfigData = initConfig()
const { search, table } = handleInit(ConfigData, api.commodity.getCommodityList.post, [
  onAddOrEdit.bind(null, 'edit'),
  onCopy,
  onAddHome,
  onChangeStatus,
  onDelete
])
const { commodityType, onChangeCommodityType, commodityTypeOptions } = useCommodityType(
  search,
  table
)
onChangeCommodityType(commodityType.value)

/** 页面缓存 */
defineOptions({ name: 'Commodity' })
</script>
