<template>
  <div class="variety-enums table_form-container">
    <!-- 搜索 --> 
    <el-button style="width: 70px;" type="primary" @click="handleAdd()" v-auth="'contractVariety_addVarietyEnums'">
      新增
    </el-button> 

    <!-- 表格 -->
    <VarietyEnumsTable 
      :table-data="tableData" 
      :columns="tableColumnsOptions" 
      row-key="id"
      @row-click="handleRowClick" 
      :loading="loading">
      <template #status="{ row }">
        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
          {{ row.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </template>
      <template #action="{ row }">
        <el-button type="primary" link @click.stop="handleEdit(row)" v-auth="'contractVariety_editVarietyEnums'">
          编辑
        </el-button>
        <el-button type="danger" link @click.stop="handleDelete(row)" v-auth="'contractVariety_delVarietyEnums'">
          删除
        </el-button>
      </template>
    </VarietyEnumsTable>
  </div>

  <!-- dialog -->
  <VarietyEnumsDialog 
    :visible="dialogVisible" 
    :title="dialogTitle" 
    :button-loading="submitLoading"
    @confirm="handleSubmit" 
    @cancel="handleCancel" 
    @close="handleClose">
    <VarietyEnumsForm
      :form-data="formData"
      :form-rules="formRules"
      :form-items="dialogFormItemOptions"
      :options-map="formOptionsMap"
      :row-gutter="rowGutter"
      :col-span="colSpan"
      ref="formRef">
    </VarietyEnumsForm>
  </VarietyEnumsDialog>
</template>

<script setup lang="ts">
import { usePageLoading, useButtonLoading } from '@/composables/useLoading'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'VarietyEnums'
})

// 组件
const { loading, startLoading, stopLoading } = usePageLoading()
const { buttonLoading: submitLoading, startButtonLoading: startSubmitLoading, stopButtonLoading: stopSubmitLoading } = useButtonLoading()

import VarietyEnumsSearch from '@/components/common/Search.vue'
import VarietyEnumsTable from '@/components/common/Table.vue'
import VarietyEnumsDialog from '@/components/common/Dialog.vue'
import VarietyEnumsForm from '@/components/common/Form.vue'

// 配置以及表单验证规则
import { search, tableColumns, DialogFormItem } from './options'
import { rules } from './rules'

// 接口
import {
  getVarietyEnumsListApi,
  addVarietyEnumsApi,
  editVarietyEnumsApi,
  delVarietyEnumsApi,
} from '@/api/modules/trade/varietyEnums'

/**
 * @description: 定义搜索数据
 */
const searchForm = ref({})
const searchOptions = ref(search)

/**
 * @description: 定义表格数据
 */
const tableData = ref<any[]>([])
const tableColumnsOptions = ref([...tableColumns, { slotName: 'action', label: '操作', align: 'center' as const }])

/**
 * @description: 定义弹窗数据
 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('')

/**
 * @description: 定义弹窗表单数据
 */
const formData = ref({
  id: 0,
  code: '',
  name: '',
  status: 1,
})
const formRef = ref<any>()
const formRules = ref(rules())
const dialogFormItemOptions = ref(DialogFormItem)
const formOptionsMap = ref({
  status: [
    { label: '启用', value: 1 },
    { label: '禁用', value: 2 },
  ],
})
const rowGutter = ref(20)
const colSpan = ref(24)

// 选中行
const selectedRow = ref<any>(null)

/**
 * @description: 获取品种枚举列表
 */
const getList = async () => {
  startLoading()
  try {
    const data = await getVarietyEnumsListApi()
    tableData.value = data || []
  } finally {
    stopLoading()
  }
}

/**
 * @description: 页面加载完成需要请求的数据
 */
onMounted(() => {
  getList()
})

/**
 * @description: 定义搜索方法
 */
const handleSearch = async () => {
  getList()
}

const handleReset = () => {
  searchForm.value = {}
  handleSearch()
}

// 点击行事件
const handleRowClick = (row: any) => {
  if (!row) {
    selectedRow.value = null
    return
  }
  selectedRow.value = row
}

/**
 * @description: 新增
 */
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增品种枚举'
  dialogType.value = 'add'
  formData.value = {
    id: 0,
    code: '',
    name: '',
    status: 1,
  }
}

/**
 * @description: 编辑
 */
const handleEdit = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑品种枚举'
  dialogType.value = 'edit'
  formData.value = {
    id: row.id,
    code: row.code,
    name: row.name,
    status: row.status,
  }
}

/**
 * @description: 删除
 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该品种枚举吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await delVarietyEnumsApi({ id: row.id })
    ElMessage.success('删除成功')
    getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

/**
 * @description: 定义弹窗方法
 */
const handleSubmit = async () => {
  startSubmitLoading()
  try {
    await formRef.value?.validate()
    const params = {
      code: formData.value.code,
      name: formData.value.name,
      status: formData.value.status,
    }

    if (dialogType.value === 'edit') {
      await editVarietyEnumsApi({
        id: Number(formData.value.id),
        ...params,
      })
      ElMessage.success('编辑成功')
    } else {
      await addVarietyEnumsApi(params)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } finally {
    stopSubmitLoading()
  }
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleClose = () => {
  dialogVisible.value = false
}
</script>

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