<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" label-width="160px">
            <el-form-item label="用户信息" prop="params.userKeyword">
              <el-input v-model="queryParams.params.userKeyword" placeholder="请输入用户名或手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备信息" prop="params.deviceKeyword">
              <el-input v-model="queryParams.params.deviceKeyword" placeholder="请输入设备名称或设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="溶解氧上限开关" prop="oxyUpperOpen">
              <el-select v-model="queryParams.oxyUpperOpen" placeholder="请选择溶解氧上限开关" clearable >
                <el-option v-for="dict in open_close" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="溶解氧下限开关" prop="oxyLowerOpen">
              <el-select v-model="queryParams.oxyLowerOpen" placeholder="请选择溶解氧下限开关" clearable >
                <el-option v-for="dict in open_close" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否触发上限关闭操作" prop="isOxyUpperTrigger">
              <el-select v-model="queryParams.isOxyUpperTrigger" placeholder="请选择是否触发上限关闭操作" clearable >
                <el-option v-for="dict in yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['fishery:linkedCtrl:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['fishery:linkedCtrl:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['fishery:linkedCtrl:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['fishery:linkedCtrl:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="linkedCtrlList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名" align="center" prop="userName"  />
        <el-table-column label="手机号" align="center" prop="mobilePhone" />
        <el-table-column label="设备编号" align="center" prop="serialNum" />
        <el-table-column label="设备名称" align="center" prop="deviceName"/>
        <el-table-column label="溶解氧上限开关" align="center" prop="oxyUpperOpen">
          <template #default="scope">
            <dict-tag :options="open_close" :value="scope.row.oxyUpperOpen"/>
          </template>
        </el-table-column>
        <el-table-column label="溶解氧上限值" align="center" prop="oxyUpperValue" />
        <el-table-column label="溶解氧下限开关" align="center" prop="oxyLowerOpen">
          <template #default="scope">
            <dict-tag :options="open_close" :value="scope.row.oxyLowerOpen"/>
          </template>
        </el-table-column>
        <el-table-column label="溶解氧下限值" align="center" prop="oxyLowerValue" />
        <el-table-column label="是否触发上限关闭操作" align="center" prop="isOxyUpperTrigger">
          <template #default="scope">
            <dict-tag :options="yes_no" :value="scope.row.isOxyUpperTrigger"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fishery:linkedCtrl:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fishery:linkedCtrl:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改溶解氧联动控制对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="linkedCtrlFormRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="设备" prop="deviceId">
          <el-input
            v-model="selectedDeviceDisplay"
            placeholder="请选择设备"
            readonly
            style="width: calc(100% - 90px); cursor: pointer;"
            @click="openDeviceSelect"
          >
            <template #suffix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button
            type="primary"
            style="margin-left: 10px;"
            @click="openDeviceSelect"
          >
            选择
          </el-button>
        </el-form-item>
        <el-form-item label="溶解氧上限开关" prop="oxyUpperOpen">
          <el-select v-model="form.oxyUpperOpen" placeholder="请选择溶解氧上限开关">
            <el-option
                v-for="dict in open_close"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="溶解氧上限值" prop="oxyUpperValue">
          <el-input v-model="form.oxyUpperValue" placeholder="请输入溶解氧上限值" />
        </el-form-item>
        <el-form-item label="溶解氧下限开关" prop="oxyLowerOpen">
          <el-select v-model="form.oxyLowerOpen" placeholder="请选择溶解氧下限开关">
            <el-option
                v-for="dict in open_close"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="溶解氧下限值" prop="oxyLowerValue">
          <el-input v-model="form.oxyLowerValue" placeholder="请输入溶解氧下限值" />
        </el-form-item>
        <el-form-item label="是否触发上限关闭操作" prop="isOxyUpperTrigger">
          <el-select v-model="form.isOxyUpperTrigger" placeholder="请选择是否触发上限关闭操作">
            <el-option
                v-for="dict in yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </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>

    <!-- 设备选择对话框 -->
    <el-dialog title="选择设备" v-model="deviceSelectVisible" width="1200px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="deviceQueryParams" :inline="true" class="mb-4">
        <el-form-item label="用户信息">
          <el-input
            v-model="deviceQueryParams.params.userKeyword"
            placeholder="请输入用户名或手机号"
            clearable
            style="width: 200px"
            @keyup.enter="handleDeviceQuery"
          />
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input
            v-model="deviceQueryParams.serialNum"
            placeholder="请输入设备编号"
            clearable
            style="width: 180px"
            @keyup.enter="handleDeviceQuery"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="deviceQueryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            style="width: 180px"
            @keyup.enter="handleDeviceQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleDeviceQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetDeviceQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 设备表格 -->
      <el-table
        :data="deviceList"
        highlight-current-row
        height="400px"
        border
      >
        <el-table-column label="用户名" align="center" prop="userName" />
        <el-table-column label="手机号" align="center" prop="mobilePhone" />
        <el-table-column label="设备编号" align="center" prop="serialNum" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="塘口名称" align="center" prop="pondName" />
        <el-table-column label="绑定时间" align="center" prop="bindTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.bindTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务到期时间" align="center" prop="deadTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deadTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleDeviceSelect(scope.row)"
            >
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="deviceTotal > 0"
        :total="deviceTotal"
        v-model:page="deviceQueryParams.pageNum"
        v-model:limit="deviceQueryParams.pageSize"
        @pagination="handleDevicePaginationChange"
        class="mt-4"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDeviceSelect">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LinkedCtrl" lang="ts">
import { listLinkedCtrl, getLinkedCtrl, delLinkedCtrl, addLinkedCtrl, updateLinkedCtrl } from '@/api/fishery/linkedCtrl';
import { LinkedCtrlVO, LinkedCtrlQuery, LinkedCtrlForm } from '@/api/fishery/linkedCtrl/types';
import { listDevice } from '@/api/fishery/device';
import { DeviceVO } from '@/api/fishery/device/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yes_no, open_close } = toRefs<any>(proxy?.useDict('yes_no', 'open_close'));

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

// 设备选择相关
const deviceList = ref<DeviceVO[]>([]);
const selectedDevice = ref<DeviceVO | null>(null);
const deviceSelectVisible = ref(false);
const deviceQueryParams = reactive<{
  pageNum: number;
  pageSize: number;
  serialNum?: string;
  deviceName?: string;
  params: {
    userKeyword?: string;
  };
}>({
  pageNum: 1,
  pageSize: 10,
  serialNum: undefined,
  deviceName: undefined,
  params: {
    userKeyword: undefined
  }
});
const deviceTotal = ref(0);

// 设备显示文本
const selectedDeviceDisplay = computed(() => {
  if (selectedDevice.value) {
    return `${selectedDevice.value.deviceName} (${selectedDevice.value.serialNum})`;
  }
  return '';
});

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

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

const initFormData: LinkedCtrlForm = {
  id: undefined,
  deviceId: undefined,
  oxyUpperOpen: undefined,
  oxyUpperValue: undefined,
  oxyLowerOpen: undefined,
  oxyLowerValue: undefined,
  isOxyUpperTrigger: undefined,
  remark: undefined
}
const data = reactive<PageData<LinkedCtrlForm, LinkedCtrlQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    oxyUpperOpen: undefined,
    oxyLowerOpen: undefined,
    isOxyUpperTrigger: undefined,
    params: {
    }
  },
  rules: {
    deviceId: [
      { required: true, message: "设备不能为空", trigger: "blur" }
    ],
    oxyUpperOpen: [
      { required: true, message: "溶解氧上限开关不能为空", trigger: "change" }
    ],
    oxyUpperValue: [
      { required: true, message: "溶解氧上限值不能为空", trigger: "blur" }
    ],
    oxyLowerOpen: [
      { required: true, message: "溶解氧下限开关不能为空", trigger: "change" }
    ],
    oxyLowerValue: [
      { required: true, message: "溶解氧下限值不能为空", trigger: "blur" }
    ],
    isOxyUpperTrigger: [
      { required: true, message: "是否触发上限关闭操作不能为空", trigger: "change" }
    ],
  }
});

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

/** 查询溶解氧联动控制列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLinkedCtrl(queryParams.value);
  linkedCtrlList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  selectedDevice.value = null;
  linkedCtrlFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: LinkedCtrlVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加溶解氧联动控制";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: LinkedCtrlVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getLinkedCtrl(_id);
  Object.assign(form.value, res.data);

  // 回显设备信息
  if (form.value.deviceId) {
    try {
      const deviceRes = await listDevice({
        pageNum: 1,
        pageSize: 1000
      });
      const deviceListData = deviceRes.rows || deviceRes.data || [];
      const device = deviceListData.find(d => d.id.toString() === form.value.deviceId.toString());
      if (device) {
        selectedDevice.value = device;
      } else {
        selectedDevice.value = null;
      }
    } catch (error) {
      console.error('加载设备信息失败:', error);
      selectedDevice.value = null;
    }
  } else {
    selectedDevice.value = null;
  }

  dialog.visible = true;
  dialog.title = "修改溶解氧联动控制";
}

/** 提交按钮 */
const submitForm = () => {
  linkedCtrlFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateLinkedCtrl(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addLinkedCtrl(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: LinkedCtrlVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的数据项？').finally(() => loading.value = false);
  await delLinkedCtrl(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('fishery/linkedCtrl/export', {
    ...queryParams.value
  }, `linkedCtrl_${new Date().getTime()}.xlsx`)
}

/** 获取设备列表 */
const getDeviceList = async () => {
  const res = await listDevice(deviceQueryParams);
  deviceList.value = res.rows || res.data || [];
  deviceTotal.value = res.total || 0;
};

/** 打开设备选择对话框 */
const openDeviceSelect = () => {
  deviceQueryParams.pageNum = 1;
  deviceQueryParams.serialNum = undefined;
  deviceQueryParams.deviceName = undefined;
  deviceQueryParams.params.userKeyword = undefined;
  getDeviceList();
  deviceSelectVisible.value = true;
};

/** 搜索设备 */
const handleDeviceQuery = () => {
  deviceQueryParams.pageNum = 1;
  getDeviceList();
};

/** 重置设备搜索 */
const resetDeviceQuery = () => {
  deviceQueryParams.pageNum = 1;
  deviceQueryParams.serialNum = undefined;
  deviceQueryParams.deviceName = undefined;
  deviceQueryParams.params.userKeyword = undefined;
  getDeviceList();
};

/** 设备分页改变 */
const handleDevicePaginationChange = () => {
  getDeviceList();
};

/** 选择设备 */
const handleDeviceSelect = (device: DeviceVO) => {
  selectedDevice.value = device;
  form.value.deviceId = device.id;
  deviceSelectVisible.value = false;
};

/** 取消设备选择 */
const cancelDeviceSelect = () => {
  deviceSelectVisible.value = false;
};

onMounted(() => {
  getList();
});
</script>
