<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable />
            </el-form-item>
            <el-form-item label="设备MAC" prop="deviceMac">
              <el-input v-model="queryParams.deviceMac" placeholder="请输入设备MAC" clearable />
            </el-form-item>
            <el-form-item label="请输入设备IMEI" prop="deviceImei">
              <el-input v-model="queryParams.deviceImei" placeholder="请输入设备IMEI" clearable />
            </el-form-item>
            <el-form-item label="设备类型" prop="typeName">
              <el-select v-model="queryParams.deviceType" placeholder="设备类型">
                <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.typeName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备状态" prop="typeName">
              <el-select v-model="queryParams.deviceStatus" placeholder="设备状态" style="margin-left: 10px;">
                <el-option label="正常" value="1" />
                <el-option label="失效" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="typeName">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :search="true" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="deviceDist" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column prop="customerName" label="所属客户" />
        <el-table-column prop="devicePic" label="设备图片" width="80">
          <template #default="scope">
            <el-popover trigger="click">
              <img :src="scope.row.devicePic" class="img1" />
              <img slot="reference" :src="scope.row.devicePic" class="img2" style="width:40px;height:40px;">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="deviceMac" label="设备MAC" />
        <el-table-column prop="deviceImei" label="设备IMEI" />
        <el-table-column prop="typeName" label="设备类型" />
        <el-table-column prop="bindingStatus" label="绑定状态">
          <template #default="scope">
            <el-tag :type="scope.row.bindingStatus === 1 ? 'success' : 'info'">
              {{ scope.row.bindingStatus === 1 ? '已绑定' : '未绑定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deviceStatus" label="设备状态">
          <template #default="scope">
            <el-tag :type="scope.row.deviceStatus == 1 ? 'success' : 'danger'">
              {{ scope.row.deviceStatus == 1 ? '正常' : '失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column prop="createByName" label="创建人" />

        <el-table-column label="操作" fixed="right" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="scope.row.id !== 1" content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.id !== 1" content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>


    <!-- 添加或修改用户配置对话框 -->
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="30%" append-to-body
      @close="closeDialog">
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备类型" prop="typeName">
              <el-select v-model="form.deviceType" placeholder="设备类型">
                <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.typeName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备MAC" prop="deviceMac">
              <el-input v-model="form.deviceMac" placeholder="请输入设备MAC" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备IMEI" prop="deviceImei">
              <el-input v-model="form.deviceImei" placeholder="请输入设备IMEI" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备图片" prop="image">
              <el-upload action="#" list-type="picture-card" :before-upload="beforeUpload" :on-change="fileUploadChange"
                :http-request="httpRequestImg" :file-list="fileList" :limit="1">
                <i class="el-icon-plus"></i>
                <template v-if="form.image && typeof form.image === 'string'">
                  <img :src="form.image" class="avatar" />
                </template>
                <i v-else class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User" lang="ts">
import api from '@/api/equipmentManagement/device/index';
import { deviceForm, deviceQuery, deviceVO } from '@/api/equipmentManagement/device/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const deviceDist = ref<deviceVO[]>();
import { to } from 'await-to-js';
const loading = ref(true);
const showSearch = ref(true);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const initPassword = ref<string>('');
const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();
const formDialogRef = ref<ElDialogInstance>();
const deviceTypeOptions = ref([]); //设备类型

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: deviceForm = {
  deviceName: '',
  deviceMac: '',
  deviceImei: '',
  remark: '',
  id: '',
  deviceType: "",
  image:''
};

const initData: PageData<deviceForm, deviceQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: '',
    deviceMac: '',
    deviceImei: '',
    deviceType: '',
    deviceStatus: '',

  },
  rules: {
    deviceName: [
      { required: true, message: '请输入设备名称', trigger: 'blur' },
    ],
    deviceType: [
      { required: true, message: '请选择设备类型', trigger: 'blur' },
    ],
    deviceMac: [
      { required: true, message: '请输入设备MAC', trigger: 'blur' },
    ],
    deviceImei: [
      { required: true, message: '请输入设备IMEI', trigger: 'blur' },
    ],
  }
};
const data = reactive<PageData<deviceVO, deviceQuery>>(initData);
const { queryParams, form, rules } = toRefs<PageData<deviceVO, deviceQuery>>(data);
/** 查询设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.deviceList(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading.value = false;
  deviceDist.value = res.rows;
  total.value = res.total;
};


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageNum = 1;
  getList();

};

/** 删除按钮操作 */
const handleDelete = async (row?: deviceVO) => {
  // 批量删除逻辑
  let arrey = ids.value.map((item) => item.id);
  if (!row) {
    const [err] = await to(proxy?.$modal.confirm(`是否确认删除选中的 ${ids.value.length} 条数据？`) as any);
    if (!err) {
      await api.deleteDevice(arrey);
      await getList();
      proxy?.$modal.msgSuccess('删除成功');
    }
    return;
  }
  // 单行删除逻辑
  const [err] = await to(proxy?.$modal.confirm('是否确认删除"' + row.nickName + '"的数据项？') as any);
  if (!err) {
    await api.deleteDevice([row.id]);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 选择条数  */
const handleSelectionChange = (selection: deviceVO[]) => {
  ids.value = selection.map((item) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};


/** 重置操作表单 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
};
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增设备';
  form.value.password = initPassword.value.toString();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: deviceForm) => {
  reset();
  dialog.visible = true;
  dialog.title = '修改设备';
  try {
    if (row) {
      // 从行内按钮调用，直接使用行数据
      Object.assign(form.value, row);
    } else {
      const customerId = ids.value[0];
      Object.assign(form.value, customerId);
    }
  } catch (error) {
    dialog.visible = false;
  }
};
    // 覆盖默认的上传行为，可以自定义上传的实现
   const  httpRequestImg=(parm)=> { };
    const beforeUpload=(file)=> {
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        ElMessage.warning("请上传jpg、png格式，大小不超过2M的照片");
        return false;
      }
      if (!isLt2M) {
        ElMessage.warning("大小不超过2M的照片片");
        return false;
      }
      return isJPG && isLt2M;
    };
    // 文件上传状态改变时触发
    const fileUploadChange=(files, fileList)=> {
      console.log(fileList, '5555');
      if (fileList.length > 0) {
      form.value.image = fileList[0].raw; // 正确获取File对象
        // 调试：检查是否是真正的 File 对象
        console.log('File对象验证:', form.value.image);
      } else {
        form.value.image = null;
      }
    };

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      //  try {
      //     const formData = new FormData();
      //     // 处理图片字段
      //     if (this.form.image instanceof File) {
      //       formData.append('file', this.form.image);
      //     } else if (this.form.image && typeof this.form.image === 'string') {
      //       // 编辑时未修改图片，传递原图片URL
      //       formData.append('imageUrl', this.form.image);
      //     }
      //     // 添加其他必要字段
      //     const fields = ['id', 'deviceName', 'deviceType', 'remark'];
      //     fields.forEach(key => {
      //       if (this.form[key] !== undefined && this.form[key] !== null) {
      //         formData.append(key, this.form[key]);
      //       }
      //     });
      //     // 根据通讯方式，有条件地添加deviceMac或deviceImei
      //     if (this.form.deviceMac) {
      //       formData.append('deviceMac', this.form.deviceMac)
      //     }
      //     if (this.form.deviceImei) {
      //       formData.append('deviceImei', this.form.deviceImei)
      //     }
      //     // 根据操作类型设置URL和方法
      //     const isAdd = this.crud.status.add;
      //     const res = await request({ // 使用 await 等待结果
      //       url: isAdd ? '/api/device/add' : '/api/device/update',
      //       method: isAdd ? 'post' : 'put',
      //       data: formData,
      //       headers: {
      //         'Content-Type': 'multipart/form-data'
      //       }
      //     });
      //     if (res.code == 0) {
      //       this.$message.success(isAdd ? '添加成功' : '编辑成功');
      //       this.crud.cancelCU();
      //       this.crud.toQuery();
      //     } else {
      //       this.$message.warning(res.msg);
      //     }
      //   } catch (err) {
      //     this.$message.warning('操作失败');
      //     console.error(err);
      //   }
    }
  });
};

/**
 * 关闭用户弹窗
 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
};

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
  form.value.customerId = undefined;
};
// 设备类型
const getDeviceType = () => {
  api.deviceTypeAll().then(res => {
    if (res.code == 0) {
      deviceTypeOptions.value = res.data
    }
  }).catch(err => {

  })
};
onMounted(() => {
  getList(); // 初始化列表数据
  getDeviceType()
});

</script>
