<script setup lang="ts">
import {
  Storehouse_IotCard_List,
  Storehouse_IotCard_Add,
  Storehouse_IotCard_Edit,
  Storehouse_IotCard_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('120px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)

const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_iccid', label: '物联网卡号', ellipsis: true },
  { prop: 'T_sn', label: '关联SN' },
  { prop: 'T_State', label: '状态', name: 'T_State' },
  { prop: 'T_type', label: '类型' },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]

// 添加仓库名称
const form = reactive({
  T_id: '',
  T_sn: '',
  T_type: '',
  T_state: null,
  T_iccid: ''
})

const validate_T_sn = (rule: any, value: any, callback: any) => {
  if (form.T_state === 2 && value === '') {
    callback(new Error('请输入已使用的关联SN'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  T_iccid: [{ required: true, message: '请输入物联网卡号', trigger: 'blur' }],
  T_state: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  T_type: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  T_sn: [{ validator: validate_T_sn, trigger: 'blur' }]
})

const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  done()
}
const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  nextTick(() => {
    form.T_id = row.Id
    form.T_sn = row.T_sn
    form.T_type = row.T_type
    form.T_state = row.T_State
    form.T_iccid = row.T_iccid
  })
  drawerRef.value?.openDrawer()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const AddUserName = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
      if (valid) {
        (async () => {
          let res: any = {}
          if (isNew.value) {
            res = await Storehouse_IotCard_Add({ User_tokey: globalStore.GET_User_tokey, ...form })
          } else {
            res = await Storehouse_IotCard_Edit({
              User_tokey: globalStore.GET_User_tokey,
              ...form
            })
          }
          if (res.Code === 200) {
            ElMessage.success(`${isNew.value ? '添加' : '修改'}物联网卡成功！！`)
            nextTick(() => {
              drawerRef.value?.closeDrawer()
              TableRef.value?.getTableList()
              resetForm(ruleFormRef.value)
              isNew.value = true
            })
          }
        })()
      }
    })
}

// 删除
const UserDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除该物联网卡号吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await Storehouse_IotCard_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 options = reactive([
  { name: '未使用', id: 1 },
  { name: '已使用', id: 2 },
  { name: '已作废', id: 3 }
])
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_state: ''
})
const searchHandle = () => {
  TableRef.value?.searchTable()
}
</script>

<template>
  <div class="IoTNetworkCard">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_IotCard_List" :initParam="initParam">
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :xl="6" :lg="8" :md="10">
              <span class="inline-flex items-center">关键词：</span>
              <el-input
                v-model="initParam.T_name"
                type="text"
                class="w-50 m-2"
                placeholder="按物联网卡号或SN搜索"
                @change="searchHandle"
              />
            </el-col>
            <el-col :xl="10" :md="12">
              <span class="inline-flex items-center">状态：</span>
              <el-select v-model="initParam.T_state" class="w-50 m-2" clearable placeholder="请选择状态~">
                <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-button type="primary" @click="searchHandle">搜索</el-button>
            </el-col>
            <el-col :xl="6" :md="2" class="btn"
              ><el-button type="primary" @click="openDrawer('new')">添加</el-button></el-col
            >
          </el-row>
        </div>
      </template>
      <template #T_State="{ row }">
        <el-tag v-if="row.T_State === 2" type="success" effect="dark"> 已使用 </el-tag>
        <el-tag v-else-if="row.T_State === 1" type="warning" effect="dark"> 未使用 </el-tag>
        <el-tag v-else type="info" effect="dark"> 已作废 </el-tag>
      </template>
      <template #right="{ row }">
        <el-button
          :disabled="row.T_State === 2"
          link
          type="primary"
          size="small"
          :icon="Edit"
          @click="openDrawer('edit', row)"
          >编辑</el-button
        >
        <el-button :disabled="row.T_State === 2" 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="T_iccid">
          <el-input v-model="form.T_iccid" type="text" autocomplete="off" placeholder="请输入物联网卡号" />
        </el-form-item>
        <el-form-item label="型号：" :label-width="formLabelWidth" prop="T_type">
          <el-input v-model="form.T_type" type="text" autocomplete="off" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="状态：" :label-width="formLabelWidth" prop="T_state">
          <el-radio-group v-model="form.T_state">
            <el-radio :label="2">已使用</el-radio>
            <el-radio :label="1">未使用</el-radio>
            <el-radio :label="3">已作废</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联SN：" :label-width="formLabelWidth" prop="T_sn">
          <el-input v-model="form.T_sn" type="text" autocomplete="off" placeholder="请输入关联SN" />
        </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';

.IoTNetworkCard {
  @include f-direction;
  :deep(.el-drawer__header) {
    margin-bottom: 0;
  }
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .btn {
      display: flex;
      justify-content: end;
    }
    .w-50 {
      width: 12.5rem;
    }
  }
}
</style>
