<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Storehouse_Device_Check } from '@/api/storehouse/index'

type Fn = () => void
interface FormSnType {
  Id?: number
  sn: string
  type?: number
}

const snTable = ref()
const SNDataMap = new Map<number, FormSnType[]>()
const tableSnData = ref<FormSnType[]>([])
const ruleSnFormRef = ref<FormInstance>()
const drawerSnRef = ref<InstanceType<typeof Drawer> | null>(null)

const snColumns = [
  { type: 'index', label: '序号', width: 80, align: 'center ' },
  { label: 'SN', prop: 'sn', align: 'center ' },
  { prop: 'operation', label: '操作', width: 80, fixed: 'right' }
]
const formSn = reactive<FormSnType>({
  Id: undefined,
  sn: '',
  type: undefined
})
const rulesSn = reactive<FormRules>({
  sn: [{ required: true, message: '请输入SN号', trigger: 'blur' }]
})

const addSn = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      const res: any = await Storehouse_Device_Check({ T_sn: formSn.sn, T_type: formSn.type })
      if (res.Code === 200) {
        tableSnData.value.push({ sn: formSn.sn })
        nextTick(() => {
          resetSnForm(ruleSnFormRef.value)
        })
      }
    }
  })
}
const deleteSn = (row: any) => {
  const index = tableSnData.value.findIndex((item: any) => row.sn === item.sn)
  tableSnData.value.splice(index, 1)
}

const callbackSnDrawer = (done: Fn) => {
  SNDataMap.set(formSn.Id as number, tableSnData.value)
  emit('onCount', SNDataMap.get(formSn.Id as number)?.length, formSn.Id as number)
  done()
  nextTick(() => {
    resetSnForm(ruleSnFormRef.value)
    tableSnData.value = []
  })
}

const emit = defineEmits<{ (event: 'onCount', value: any, id: number): void }>()

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

const addDeviceSn = (id: number, type: number) => {
  formSn.Id = id
  formSn.type = type
  if (SNDataMap.has(id)) {
    tableSnData.value = SNDataMap.get(id) as FormSnType[]
  } else {
    SNDataMap.set(id, [])
  }
  drawerSnRef.value?.openDrawer()
}
const getDeviceSn = () => SNDataMap
const clearDeviceSn = () => SNDataMap.clear()
const deleteDeviceSn = (id: number) => SNDataMap.delete(id)
defineExpose({
  getDeviceSn,
  addDeviceSn,
  clearDeviceSn,
  deleteDeviceSn
})
</script>

<template>
  <Drawer ref="drawerSnRef" :handleClose="callbackSnDrawer" size="30%">
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="sn-header">
          <el-form ref="ruleSnFormRef" :model="formSn" :rules="rulesSn">
            <el-form-item label="SN：" label-width="120px" prop="sn">
              <el-input v-model="formSn.sn" type="text" placeholder="请输入SN" class="w-50" />
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="addSn(ruleSnFormRef)">添加</el-button>
        </div>
      </template>
      <el-table
        ref="snTable"
        :data="tableSnData"
        style="width: 100%; height: 99%"
        :header-cell-style="{
          background: '#dedfe0',
          height: '50px'
        }"
      >
        <template v-for="item in snColumns" :key="item">
          <el-table-column v-if="item.type === 'index'" v-bind="item" />
          <el-table-column v-if="item.prop" align="center" v-bind="item">
            <template #default="{ row }">
              <el-button
                v-if="item.prop === 'operation'"
                link
                type="danger"
                size="small"
                :icon="Delete"
                @click="deleteSn(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-card>
  </Drawer>
</template>

<style scoped lang="scss">
.box-card {
  height: 100%;
  :deep(.el-card__body) {
    height: calc(100% - 70px);
  }
  .sn-header {
    display: flex;
    justify-content: end;
  }
}
</style>
