<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="alarmCode">
              <el-input v-model="queryParams.alarmCode" placeholder="请输入报警编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备选择" prop="deviceId">
              <el-select v-model="queryParams.deviceId" placeholder="请选择" clearable style="width: 160px">
                <el-option v-for="item in deviceInfo" :key="item.id || item.code" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="报警时间" prop="queryTime">
              <el-date-picker
                v-model="queryTime"
                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-form-item>
            <el-form-item label="报警区域" prop="monitoringArea">
              <el-input v-model="queryParams.monitoringArea" 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" class="flex justify-end mb8">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="multiple" @click="handleBatchProcess">批量处理</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="demoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
        <el-table-column label="报警编号" align="center" prop="alarmCode" width="180" />
        <el-table-column label="报警时间" align="center" prop="alarmTime" min-width="170" />
        <el-table-column label="所属设备" align="center" prop="deviceName" min-width="120" show-overflow-tooltip />
        <el-table-column label="报警区域" align="center" prop="monitoringArea" min-width="120" show-overflow-tooltip />
        <!-- pay content  -->
        <!-- <el-table-column label="报警图片" align="center" prop="alarmImage" min-width="120">
          <template #default="scope">
            <el-image
              v-if="scope.row.alarmImage"
              :src="scope.row.alarmImage"
              :preview-src-list="[scope.row.alarmImage]"
              preview-teleported
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column> -->
        <el-table-column label="处理状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">未处理</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">已处理</el-tag>
            <span v-else>{{ scope.row.status ?? '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="userId" min-width="100">
          <template #default="scope">
            {{ scope.row.userName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="处理时间" align="center" prop="processingTime" min-width="170">
          <template #default="scope">
            {{ scope.row.processingTime ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <el-button :disabled="scope.row.status === 1" type="primary" @click="handleUpdate(scope.row)">处理</el-button>
          </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 v-model="dialog.visible" :title="dialog.title" width="520px" append-to-body>
      <el-form ref="demoFormRef" :model="form" label-width="100px">
        <el-form-item label="设备编号">
          <el-input v-model="form.deviceId" disabled />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="form.deviceName" disabled />
        </el-form-item>
        <el-form-item label="监控区域">
          <el-input v-model="form.monitoringArea" disabled />
        </el-form-item>
        <el-form-item label="报警时间">
          <el-input v-model="form.alarmTime" disabled />
        </el-form-item>
        <el-form-item label="处理状态">
          <el-tag v-if="form.status === 0" type="warning">未处理</el-tag>
          <el-tag v-else-if="form.status === 1" type="success">已处理</el-tag>
          <span v-else>{{ form.status ?? '-' }}</span>
        </el-form-item>
        <el-form-item label="处理人">
          <el-input :model-value="form.userId ?? '-'" disabled />
        </el-form-item>
        <el-form-item label="处理时间">
          <el-input :model-value="form.processingTime ?? '-'" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="WarningList" lang="ts">
import { listDemo, updateDemo } from '@/api/WarningList/index';
//import { DemoVO, DemoQuery, DemoForm } from '@/api/WarningList/types';
import { useDeviceStore } from '@/store/modules/equipmentList';
import { storeToRefs } from 'pinia';
import { useWarningListStore } from '@/store/modules/warnningList';

const warningListStore = useWarningListStore();
const { getWarningList, handleAction } = warningListStore;
const { warningListTotal, warningList } = storeToRefs(warningListStore);

const deviceStore = useDeviceStore();
const { deviceList } = storeToRefs(deviceStore);
const { getdeviceList } = deviceStore;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const demoList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const demoFormRef = ref<ElFormInstance>();

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

const initFormData: any = {
  id: undefined,
  deviceId: undefined,
  deviceName: undefined,
  userName: undefined,
  monitoringArea: undefined,
  alarmTime: undefined,
  status: undefined,
  userId: undefined,
  processingTime: undefined
};
/* ?id=&deviceId=&pageSize=1&pageNum=1&beginTime=&endTime= */
/** 查询参数 */
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    deviceId: undefined,
    //status: undefined,
    beginTime: undefined,
    endTime: undefined,
    monitoringArea: undefined,
    userName: undefined,
    alarmCode: undefined
  },
  rules: {},
  queryTime: []
});

const { queryParams, form, rules, queryTime } = toRefs(data);

/** 获取列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listDemo(queryParams.value);
    demoList.value = res.data.rows;
    total.value = res.data.total;
    await getWarningList({
      status: 0,
      pageNum: 1,
      pageSize: 300
    });
  } finally {
    loading.value = false;
  }
};

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

/** 查询按钮 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.beginTime = queryTime.value[0];
  queryParams.value.endTime = queryTime.value[1];
  getList();
};

/** 重置按钮 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryTime.value = [];
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item) => item.id as string | number);
  multiple.value = !selection.length;
};

/** 单条：打开确认弹窗 */
const handleUpdate = async (row: any) => {
  console.log(row.id);

  loading.value = true;
  try {
    await handleAction(row.id);
    proxy?.$modal.msgSuccess('处理成功');
    await getList();
  } finally {
    loading.value = false;
  }
};

/** 检查行是否可选（已处理不可选） */
const checkSelectable = (row: any) => {
  return row.status !== 1;
};

/** 批量：确认后直接提交 */
const handleBatchProcess = async () => {
  if (!ids.value.length) {
    proxy?.$modal.msgWarning('请先选择要处理的报警');
    return;
  }
  await proxy?.$modal.confirm('是否确认批量处理已选中的报警？');
  loading.value = true;
  try {
    await handleAction(ids.value);
    proxy?.$modal.msgSuccess('处理成功');
    await getList();
  } finally {
    loading.value = false;
  }
};

/** 提交按钮 */
const submitForm = async () => {
  if (form.value.id == null) {
    proxy?.$modal.msgWarning('数据异常');
    return;
  }
  buttonLoading.value = true;
  try {
    await updateDemo(form.value.id);
    proxy?.$modal.msgSuccess('处理成功');
    dialog.visible = false;
    await getList();
  } finally {
    buttonLoading.value = false;
  }
};

//获取设备名称-搜索_设备选择
const deviceInfo = ref([]);
const getDeviceName = async () => {
  try {
    await getdeviceList();
    deviceInfo.value = deviceList.value;
    console.log('设备列表：', deviceInfo.value);
  } catch (error) {
    proxy?.$modal.msgError('获取设备列表失败');
  }
  // const res = await getdeviceList();
  // deviceInfo.value = res?.rows;
};
onMounted(() => {
  getList();
  getDeviceName();
});

//监听数据源变化，自动刷新列表
watch(warningListTotal, async (newVal) => {
  //console.log('监听到报警列表变化，自动刷新列表', newVal);
  //数据源不同， 接口复用，请求多了一遍（不属于bug）
  await getList();
});
</script>
