<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="类型code" align="center" prop="appModelDictionary">
          <template #default="scope">
            {{appmodelDictionaryOptions.find(item => item.dictValue === String(scope.row.appModelDictionary))?.dictLabel
            }}
          </template>
        </el-table-column>
        <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>
            <div v-if="scope.row.communicationMode == 2">4G&蓝牙</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="appModelDictionary">
              <el-select v-model="form.appModelDictionary" placeholder="请选择" @change="handlePcRouteChange">
                <el-option v-for="item in appmodelDictionaryOptions" :key="item.dictCode" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
            <el-form-item label="pc路由跳转" prop="pcModelDictionary" style="display: none;">
              <el-select v-model="form.pcModelDictionary" placeholder="请选择">
                <el-option v-for="item in pcmodelDictionaryOptions" :key="item.dictCode" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </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-option label="4G&蓝牙" :value="2" />
              </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 { deviceTypeQuery } from '@/api/equipmentManagement/deviceType/types';
import { getDicts } from '@/api/system/dict/data';
import { to } from 'await-to-js';
import { ComponentInternalInstance, getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElInput, ElRow, ElCol, ElButton, ElCard, ElSelect, ElOption, ElDatePicker, ElTable, ElTableColumn, ElTooltip, ElSwitch } from 'element-plus';
interface deviceTypeVO {
  id: string | number;
  typeName: string;
  isSupportBle: boolean;
  locateMode: number;
  modelDictionary: string;
  appModelDictionary: string;
  pcModelDictionary: string;
  communicationMode: number;
  createTime: string;
  createByName: string;
}
interface DeviceTypeForm extends deviceTypeVO {
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const deviceTypeList = ref<deviceTypeVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<deviceTypeVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<InstanceType<typeof ElForm>>();
const userFormRef = ref<InstanceType<typeof ElForm>>();
const formDialogRef = ref<InstanceType<typeof ElDialog>>();
const loadingIng = ref(false)
const appmodelDictionaryOptions = ref<any[]>([]);
const pcmodelDictionaryOptions = ref<any[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData: DeviceTypeForm = {
  typeName: '',
  isSupportBle: false,
  locateMode: 0,
  // modelDictionary: '',
  appModelDictionary: '',
  pcModelDictionary: '',
  communicationMode: 0,
  id: '',
  createTime: '',
  createByName: '',
};

const initData = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: '',
  },
  rules: {
    typeName: [
      { required: true, message: '请输入设备类型名称', trigger: 'blur' },
    ],
    appModelDictionary: [
      { required: true, message: '请选择类型code', trigger: 'blur' },
    ],
    locateMode: [
      { required: true, message: '请选择定位方式', trigger: 'blur' },
    ],
    communicationMode: [
      { required: true, message: '请选择通讯方式', trigger: 'blur' },
    ],
  }
};

const data = reactive<{
  form: DeviceTypeForm,
  queryParams: deviceTypeQuery,
  rules: any
}>(initData);

const { queryParams, form, rules } = toRefs(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 getDict = async () => {
  const res = await getDicts('app_model_dictionary');
  appmodelDictionaryOptions.value = res.data;
}
const pcgetDict = async () => {
  const res = await getDicts('pc_model_dictionary');
  pcmodelDictionaryOptions.value = res.data;
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  getList();
};
// PC路由变化时，同步对应APP路由
const handlePcRouteChange = (pcDictValue: string) => {
  const selectedPcItem = appmodelDictionaryOptions.value.find(
    item => item.dictValue === pcDictValue
  );
  if (!selectedPcItem) return;
  const matchedAppItem = pcmodelDictionaryOptions.value.find(
    item => item.dictLabel === selectedPcItem.dictLabel
  );
  if (matchedAppItem) {
    form.value.pcModelDictionary = matchedAppItem.dictValue;
  } else {
    form.value.pcModelDictionary = '';
    console.warn(`没有找到dictLabel为${selectedPcItem.dictLabel}的APP路由`);
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: deviceTypeVO) => {
  const deviceTypeIds = row ? [row.id] : ids.value.map(item => item.id);
  const typeNames = row ? row.typeName : ids.value.map(item => item.typeName).join(',');
  const [err] = await to(proxy?.$modal.confirm('是否确认删除"' + typeNames + '"的数据项？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }) as any);
  if (!err) {
    await api.deleteDeviceType(deviceTypeIds);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 选择条数  */
const handleSelectionChange = (selection: deviceTypeVO[]) => {
  ids.value = selection;
  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 = '新增设备类型';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceTypeForm) => {
  reset();
  dialog.visible = true;
  dialog.title = '修改设备类型';
  try {
    const deviceData = row || ids.value[0];
    Object.assign(form.value, deviceData);
    // 确保数据类型正确
    form.value.appModelDictionary = String(form.value.appModelDictionary || '');
    form.value.pcModelDictionary = String(form.value.pcModelDictionary || '');
    form.value.locateMode = Number(form.value.locateMode) || 0;
    form.value.communicationMode = Number(form.value.communicationMode) || 0;
  } catch (error) {
    dialog.visible = false;
  }
};

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loadingIng.value = true;
      try {
        const payload = {
          ...form.value,
          appModelDictionary: form.value.appModelDictionary,
          pcModelDictionary: form.value.pcModelDictionary,

          locateMode: Number(form.value.locateMode),
          communicationMode: Number(form.value.communicationMode)
        };
        form.value.id ? await api.updateDeviceType(payload) : await api.addDeviceType(payload);
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        loadingIng.value = false;
      }
    }
  });
};

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

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
  form.value.id = '';
};

onMounted(() => {
  getList(); // 初始化列表数据
  getDict();
  pcgetDict() //pc跳转
});
</script>
