<template>
    <el-dialog v-model="visible" title="开始盘点" width="800px" @open="onOpen" @close="onClose">
      <div>
        <div class="form-row">
          <el-input v-model="device_code" placeholder="设备编号" @keyup.enter="handleAdd" :disabled="loading" />
          <el-input v-model="check_no" placeholder="盘点编号" @keyup.enter="handleAdd" :disabled="true" />
          <el-button type="primary" @click="handleAdd" :loading="loading">添加</el-button>
        </div>
    
        <el-table :data="deviceList"  v-loading="loading" style="margin-top: 20px">
          <el-table-column type="index" label="序号" width="60" />
          <!-- <el-table-column prop="id" label="盘点id" width="60" /> -->
          <el-table-column prop="device_code" label="设备编号" />
          <el-table-column prop="device_name" label="设备名称" />
          <el-table-column prop="device_category" label="设备分类" />
          <el-table-column prop="check_no" label="盘点编号" />
          <el-table-column prop="status_display" label="状态" />
          <!-- <el-table-column prop="productName" label="商品名称" /> -->
        </el-table>
      </div>
      <template #footer v-if="deviceList.length > 0">
        <div class="dialog-footer">
          <el-button @click="onCancelAll" :disabled="!currentRecordId">取消盘点</el-button>
          <el-button type="primary" @click="onCompleteAll" :disabled="!check_no">完成盘点</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts" >
  import { ref } from 'vue';
  import * as api from '../api';
  import { ElMessage } from 'element-plus';
  const emit = defineEmits(['completed']);

  const visible = ref(false);
  const device_code = ref('');
  const check_no = ref('');
  const deviceList = ref<any[]>([]);
  const currentRecordId = ref<number | null>(null);
  const loading = ref(false);
//   const btflag=ref(true);
  
  const setCheckNo = (val: string) => {
    console.log("val::::::",val)
    check_no.value = val;
};
  const onOpen = () => {
    device_code.value = '';
    // check_no.value = '';
    deviceList.value = [];
    currentRecordId.value = null;
  };
  
  const findCheckRecord = (checkNo: string, list: any[]) => {
        console.log("lists::::",list)
        if (!Array.isArray(list)) return null;
        return list.find(item => item.check_no === checkNo);
    };

        

  const handleAdd = async () => {
    if (!device_code.value || !check_no.value) return;

    const payload = {
        device_code: device_code.value,
        check_no: check_no.value,
    };
    
    loading.value = true;
    try {
      const res = await api.ScanDevice(payload);
      if (res?.code===2000) {
          const reslist=await api.GetPermission();
          if (reslist?.code===2000) {
              const record = findCheckRecord(check_no.value, reslist.data);
              deviceList.value.push({
                  ...payload,
                  productName: res.data?.productName || '未知商品',
                  id: record?.id||0,
                  status_display:record?.status_display||'',
                  device_name: res.data?.device_name || '未知设备',
                  device_category: res.data?.device_category || '未知分类',
              });
              device_code.value = '';
              currentRecordId.value = record?.id ?? null;
          }
      }
    } finally {
      loading.value = false;
    }
  };

  const onCompleteAll = async () => {
    if (!check_no.value) return;
    const res=await api.CompleteScan({ check_no: check_no.value });
    if (res?.code===2000) {
        ElMessage.success('完成盘点！');
        visible.value = false;
        emit('completed');
    }
  };

  const onCancelAll = async () => {
    if (!currentRecordId.value) return;
    const res=await api.CancelScan(currentRecordId.value);
    if (res?.code===2000) {
        ElMessage.success('取消盘点成功！');
        visible.value = false;
        emit('completed');
    }
  };
  
  const completeScan = async (row: any) => {
    const res=await api.CompleteScan({ check_no: row.check_no });
    if (res?.code===2000) {
        // const payload = {
        //     device_code: device_code.value,
        //     check_no: check_no.value,
        // };
        // const reslist=await api.GetPermission();
        // const record = findCheckRecord(check_no.value, reslist.data.results);
        // deviceList.value.push({
        //     ...payload,
        //     productName: res.data?.productName || '未知商品',
        //     id: record?.id||0,
        //     status_display:record?.status_display||'',
        //     // record,
        // });
        // btflag.value=false;
        ElMessage.success('完成盘点！');
       /*  visible.value = false */
    }
  };
  
  const cancelScan = async (row: any) => {
    const res=await api.CancelScan(row.id);
    if (res?.code===2000) {
        console.log("deviceList.value::",deviceList.value)
        deviceList.value = deviceList.value.filter(item => item.id !== row.id);
        console.log("deviceList.value22222::",deviceList.value)
        ElMessage.success('取消盘点成功！');
        visible.value = false
    }
  };
  
  defineExpose({ visible,setCheckNo});

  const onClose = () => {
  check_no.value = '';
    };


  </script>
  
  <style scoped>
  .form-row {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
  }
  </style>
  