<script setup lang="ts">
import {
  Storehouse_Depot_List,
  Storehouse_Depot_Add,
  Storehouse_Depot_Edit,
  Storehouse_Depot_Del
} from '@/api/storehouse/index'
import { ref, reactive, nextTick } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import TableBase from '@/components/TableBase/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useTablePublic } from '@/hooks/useTablePublic'

const isNew = ref(true)
const formLabelWidth = ref('100px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const { resetForm, globalStore, searchOnTableList, updateOnTableList } = useTablePublic()
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: ''
})
const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_name', label: '仓库名称' },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]

// 添加仓库名称
const form = reactive({ name: '', id: '' })
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }]
})
const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  done()
}
const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  nextTick(() => {
    !isNew.value && ((form.name = row.T_name), (form.id = row.Id))
  })
  drawerRef.value?.openDrawer()
}
// const AddUserName = (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   formEl.validate(async valid => {
//     if (valid) {
//       let res: any = {}
//       if (isNew.value) {
//         res = await Storehouse_Depot_Add({ User_tokey: globalStore.GET_User_tokey, T_name: form.name })
//       } else {
//         res = await Storehouse_Depot_Edit({ User_tokey: globalStore.GET_User_tokey, T_name: form.name, T_id: form.id })
//       }
//       if (res.Code === 200) {
//         ElMessage.success('添加仓库名称成功！！')
//         nextTick(() => {
//           drawerRef.value?.closeDrawer()
//           updateOnTableList(TableRef.value)
//           resetForm(ruleFormRef.value)
//           isNew.value = true
//         })
//       }
//     } else {
//       return false
//     }
//   })
// }
    const AddUserName = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (!valid) return // 此处直接返回，不返回boolean
        
        const apiParams = isNew.value
          ? { User_tokey: globalStore.GET_User_tokey, T_name: form.name }
          : { User_tokey: globalStore.GET_User_tokey, T_name: form.name, T_id: form.id }
          
        const request = isNew.value 
          ? Storehouse_Depot_Add(apiParams)
          : Storehouse_Depot_Edit(apiParams)
    
        request.then(res => {
          if (res.Code === '200') {
            ElMessage.success(`${isNew.value ? '添加' : '修改'}成功！`)
            drawerRef.value?.closeDrawer()
            updateOnTableList(TableRef.value)
            resetForm(ruleFormRef.value)
            isNew.value = true
          }
        }).catch(err => {
          console.error('操作失败:', err)
        })
      })
    }
const UserDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除该仓库吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await Storehouse_Depot_Del({ User_tokey: globalStore.GET_User_tokey, T_id: row.Id })
      if (res.Code === 200) {
        ElMessage.success('删除成功！')
        nextTick(() => updateOnTableList(TableRef.value))
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}
</script>

<template>
  <div class="list">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_Depot_List" :initParam="initParam">
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :span="12">
              <span class="inline-flex items-center">仓库名称：</span>
              <el-input
                v-model="initParam.T_name"
                type="text"
                class="w-50 m-2"
                @change="searchOnTableList(TableRef)"
                placeholder="按仓库名称搜索"
              />
              <el-button type="primary" @click="searchOnTableList(TableRef)">搜索</el-button>
            </el-col>
            <el-col :span="6" :offset="6"><el-button type="primary" @click="openDrawer('new')">添加</el-button></el-col>
          </el-row>
        </div>
      </template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openDrawer('edit', row)">编辑</el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="UserDelete(row)">删除</el-button>
      </template>
    </TableBase>
    <Drawer ref="drawerRef" :handleClose="callbackDrawer">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 仓库名称</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="仓库名称：" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" type="text" autocomplete="off" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-button v-if="isNew" color="#626aef" @click="AddUserName(ruleFormRef)">提交</el-button>
          <el-button v-else color="#626aef" @click="AddUserName(ruleFormRef)">修改</el-button>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.list {
  @include f-direction;
}
.input-suffix {
  width: 100%;
  .w-50 {
    width: 33.33%;
  }
}
</style>
