<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :pagination="false"
      :columns="columns"
      row-key="id"
      :request-api="listProductApi"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" v-auth="['als:product:add']" icon="CirclePlus" @click="openDialog(1, '产品树新增')"> 新增 </el-button>
        <el-button type="primary" v-auth="['als:product:import']" icon="Upload" plain @click="batchAdd"> 导入 </el-button>
        <el-button type="primary" v-auth="['als:product:export']" icon="Download" plain @click="downloadFile"> 导出 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link icon="EditPen" v-auth="['als:product:edit']" @click="openDialog(2, '产品树编辑', scope.row)"> 编辑 </el-button>
        <el-button type="primary" link v-auth="['als:product:add']" icon="CirclePlus" @click="openDialog(4, '产品树新增', scope.row)">
          新增
        </el-button>
        <el-button type="primary" link icon="Delete" v-auth="['als:product:remove']" @click="deleteProduct(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" :items-options="itemsOptions" :model="model" />
    <ImportExcel ref="dialogRef" />
    <TaskDialog ref="taskDialogRef" />
  </div>
</template>

<script setup lang="tsx" name="Product">
import { useHandleData } from '@/hooks/useHandleData'
import { ElMessageBox } from 'element-plus'
import ImportExcel from '@/components/ImportExcel/index.vue'
import TaskDialog from '@/components/TaskDialog/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import { handleTree } from '@/utils/common'
import {
  listProductApi,
  delProductApi,
  addProductApi,
  updateProductApi,
  importTemplateApi,
  importProductDataApi,
  exportProductApi,
  getProductApi
} from '@/api/modules/als/product'

// ProTable 实例
const proTable = ref<ProTableInstance>()
// 表单model
const model = ref()
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({})
const productOptions = ref<any[]>([])
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
const dataCallback = (res: any) => {
  const data = handleTree(res, 'id')
  productOptions.value = Object.assign([], data)
  productOptions.value.push({ id: 0, name: '顶层', children: null })
  setItemsOptions()
  return data
}

// 删除产品树信息
const deleteProduct = async (params: any) => {
  await useHandleData(delProductApi, params.id, '删除【' + params.name + '】产品树')
  proTable.value?.getTableList()
}

const taskDialogRef = ref<InstanceType<typeof TaskDialog> | null>(null)
// 导出产品树列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出产品树数据?', '温馨提示', { type: 'warning' }).then(async () => {
    exportProductApi(proTable.value?.searchParam)
    taskDialogRef.value?.openExportDialog()
  })
}

// 批量添加产品树
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
const batchAdd = () => {
  const params = {
    title: '产品树',
    tempApi: importTemplateApi,
    importApi: importProductDataApi,
    getTableList: proTable.value?.getTableList
  }
  dialogRef.value?.acceptParams(params)
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.id) {
    res = await getProductApi(row?.id || null)
  }
  // 重置表单项
  setItemsOptions()
  if (row?.parentId == 0 && type == 2) {
    itemsOptions.splice(0, 1)
  }
  // 增加子节点
  if (type == 4) {
    res.data = {
      parentId: row?.id
    }
  }
  model.value = type == 1 ? {} : res.data
  const params = {
    title,
    width: 580,
    isEdit: type !== 3,
    api: [1, 4].includes(type) ? addProductApi : updateProductApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: 'name',
    label: '产品名称',
    align: 'left',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'snsCode',
    label: 'SNS编号',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'orderNum',
    label: '显示顺序'
  },
  {
    prop: 'createByName',
    label: '创建人'
  },
  {
    prop: 'createTime',
    label: '创建时间'
  },
  {
    prop: 'updateByName',
    label: '更新人'
  },
  {
    prop: 'updateTime',
    label: '更新时间'
  },
  { prop: 'operation', label: '操作', width: 230 }
])
// 表单配置项
let itemsOptions = reactive<ProForm.ItemsOptions[]>([])
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '父ID',
      prop: 'parentId',
      rules: [{ required: true, message: '父ID不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'tree-select',
        enum: productOptions.value,
        valueKey: 'id',
        checkStrictly: true,
        props: {
          value: 'id',
          label: 'name'
        },
        placeholder: '请选择父ID'
      }
    },
    {
      label: '产品名称',
      prop: 'name',
      rules: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入产品名称'
      }
    },
    {
      label: 'SNS编号',
      prop: 'snsCode',
      rules: [{ required: true, message: 'SNS编号不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入SNS编号'
      }
    },
    {
      label: '显示顺序',
      prop: 'orderNum',
      rules: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'input-number',
        value: 0,
        min: 0
      }
    }
  ]
}
</script>
