<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="typeName">
              <el-input v-model="queryParams.typeName" placeholder="请输入型号名称" clearable @keyup.enter="handleQuery" />
            </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="deviceTypeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="型号名称" align="center" prop="typeName" />
        <el-table-column label="是否支持蓝牙" align="center" prop="isSupportBle">
          <template #default="scope">
            {{ scope.row.isSupportBle ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="locateMode" label="定位方式">
          <template #default="scope">
            <div v-if="scope.row.locateMode == 0">无</div>
            <div v-if="scope.row.locateMode == 1">GPS</div>
            <div v-if="scope.row.locateMode == 2">基站</div>
            <div v-if="scope.row.locateMode == 3">wifi</div>
            <div v-if="scope.row.locateMode == 4">北斗</div>
          </template>
        </el-table-column>
        <el-table-column prop="communicationMode" label="通讯方式">
          <template #default="scope">
            <div v-if="scope.row.communicationMode == 0">4G</div>
            <div v-if="scope.row.communicationMode == 1">蓝牙</div>
          </template>
        </el-table-column>
        <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="typeName">
              <el-input v-model="form.typeName" placeholder="请输入设备类型名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否支持蓝牙" prop="isSupportBle">
              <el-select v-model="form.isSupportBle" placeholder="请选择">
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="定位方式" prop="locateMode">
              <el-select v-model="form.locateMode" placeholder="请选择">
                <el-option label="无" value="0" />
                <el-option label="GPS" value="1" />
                <el-option label="基站" value="2" />
                <el-option label="wifi" value="3" />
                <el-option label="北斗" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="通讯方式" prop="communicationMode">
              <el-select v-model="form.communicationMode" placeholder="请选择">
                <el-option label="4G" value="0" />
                <el-option label="蓝牙" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="loadingIng">确 定</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/deviceType/index';
import { UserForm, deviceTypeQuery, deviceTypeVO } from '@/api/equipmentManagement/deviceType/types';
import { UserQuery, UserVO } from '@/api/system/user/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const deviceTypeList = ref<deviceTypeVO[]>();
import { to } from 'await-to-js';
const loading = ref(true);
const showSearch = ref(true);
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 loadingIng = ref(false)
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserForm = {
  typeName: '',
  isSupportBle: '',
  locateMode: '',
  communicationMode: '',
  id: ''
};

const initData: PageData<UserForm, deviceTypeQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: '',

  },
  rules: {
    typeName: [
      { required: true, message: '请输入设备类型名称', trigger: 'blur' },
    ],
    locateMode: [
      { required: true, message: '请选择定位方式', trigger: 'blur' },
    ],
    communicationMode: [
      { required: true, message: '请选择通讯方式', trigger: 'blur' },
    ],
  }
};
const data = reactive<PageData<UserForm, UserQuery>>(initData);
const { queryParams, form, rules } = toRefs<PageData<UserForm, UserQuery>>(data);
/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.deviceType(queryParams.value);
  loading.value = false;
  deviceTypeList.value = res.rows;
  total.value = res.total;
};


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

};

/** 删除按钮操作 */
const handleDelete = async (row?: UserVO) => {
  // 批量删除逻辑
  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.deleteDeviceType(arrey);
      await getList();
      proxy?.$modal.msgSuccess('删除成功');
    }
    return;
  }
  // 单行删除逻辑
  const [err] = await to(proxy?.$modal.confirm('是否确认删除"' + row.typeName + '"的数据项？') as any);
  if (!err) {
    await api.deleteDeviceType([row.id]);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 选择条数  */
const handleSelectionChange = (selection: UserVO[]) => {
  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?: UserForm) => {
  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 submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loadingIng.value = true;
      form.value.id ? await api.updateDeviceType(form.value) : await api.addDeviceType(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      loadingIng.value = false;
    }
  });
};

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

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
  form.value.customerId = undefined;
};
onMounted(() => {
  getList(); // 初始化列表数据

});

</script>
