<script setup lang="ts">
import {
  Storehouse_Depot_List,
  Storehouse_Depot_Add,
  Storehouse_Depot_Edit,
  Storehouse_Depot_Del
} from '@/api/storehouse/index'
import { GlobalStore } from '@/stores/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'

const isNew = ref(true)
const globalStore = GlobalStore()
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 initParam = {
  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' }
]

// 添加仓库名称
type Fn = () => void
const form = reactive({
  name: '',
  id: ''
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }]
})

const callbackDrawer = (done: Fn) => {
  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 resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

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()
          TableRef.value?.getTableList()
          resetForm(ruleFormRef.value)
          isNew.value = true
        })
      }
    } else {
      return false
    }
  })
}

// 删除
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(() => {
          TableRef.value?.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}

// 搜索
const search = ref('')
const searchHandle = () => {
  initParam.T_name = search.value
  TableRef.value?.searchTable()
}
</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="search"
                type="text"
                class="w-50 m-2"
                @change="searchHandle"
                placeholder="按仓库名称搜索"
              />
              <el-button type="primary" @click="searchHandle">搜索</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-divider border-style="dashed" />
        <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">
.input-suffix {
  width: 100%;
  .w-50 {
    width: 12.5rem;
  }
}
</style>
