<script setup>
import { CirclePlus} from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { getDeviceList, postDevice, putDevice, delDevice, getAllWaterFactoryList } from '@/api/client/manage'
import { ref } from 'vue';

const { proxy } = getCurrentInstance();

const queryParams = ref({ 
  pageNum: 1,
  pageSize: 10,
  deviceStatus: ''
 });

const total = ref(0);
const loading = ref(false);
const tableData = ref([]);

const formData = ref({});
const formRef = ref(null);

const dialogVisible = ref(false);

const rules = {
  deviceWorks:{ required: true, message: '请选择水厂', trigger: 'change' },
  deviceSn:{ required: true, message: '请输入设备SN', trigger: 'blur' },
  deviceName: { required: true, message: '请输入设备名称', trigger: 'blur' },
  deviceModel: { required: true, message: '请输入设备型号', trigger: 'blur' },
  type: { required: true, message: '请选择设备型号', trigger: 'blur' },
  deviceStatus: { required: true, message: '请选择设备状态', trigger: 'blur' }
}

// 设备用途 select 数据
const deviceTypeOptions = [
  { value: 1, label: '化验室' },
  { value: 2, label: '连续检测' },
]

// 设备状态 select 数据
const deviceStatusOptions = [
  { value: 0, label: '正常' },
  { value: 1, label: '停用' },
]

const waterFactoryOptions = ref([]);

const initPageData = async () => {
  
  loading.value = true;

  const { total: tableTotal, rows } = await getDeviceList(queryParams.value);

  const typeEmun = {
    1: '化验室',
    2: '连续检测'
  }
  tableData.value = rows.map(item => ({
    ...item,
    typeName: typeEmun[item.type]
  }));
  total.value = tableTotal;
  loading.value = false;
}

// 查询
const handleQuery = async() => {
  initPageData();
}


// 编辑设置
const handleEditDevice = (row) => {
  formData.value = { ...row };
  dialogVisible.value = true;
}

// 删除设备
const handleDelete = async ({ deviceId }) => {
  await delDevice(deviceId);
  proxy.$modal.msgSuccess("删除成功");
  initPageData();
}

// 重置
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    deviceStatus: ''
  }
  initPageData();
}

// 切换table - 状态
const onChangeTag= (row) => {
  ElMessageBox.confirm(
    `请确认，是否要${row.deviceStatus == 0 ? '停用' : '启用'}该设备？`,
    '状态变更提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    await putDevice({ deviceId: row.deviceId, deviceStatus: row.deviceStatus == 0 ? 1 : 0 });
    initPageData();
    proxy.$modal.msgSuccess("状态变更成功");
  }).catch(() => {})
}

// 重置dialog表单
const handleDialogReset = () => {
  formData.value = {};
  formRef.value.resetFields();
}

const handleDialogConfirm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      !formData.value.deviceId ? await postDevice(formData.value) : await putDevice(formData.value);
      initPageData();
      formRef.value.resetFields();
      dialogVisible.value = false;
      proxy.$modal.msgSuccess("操作成功");
    } else {
      console.log('error submit!', fields)
    }
  })
}

onMounted(() => {
  getAllWaterFactoryList().then(({ data }) => waterFactoryOptions.value = data);
  initPageData();
})
</script>

<template>
  <div>
    <el-card shadow="never" :body-style="{ border: '0px' }" style="margin-bottom: 10px;">
      <template #header>
        <p class="space-x-[10px]">
          <span class="font-bold">数据筛选</span>
        </p>
      </template>
      <el-row class="pt-[5px]" justify="space-between" :gutter="20">
        <el-col :span="6">
          <el-form-item label="设备名称">
            <el-input placeholder="请输入设备名称" v-model.trim="queryParams.deviceName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备SN">
            <el-input placeholder="请输入设备SN" v-model.trim="queryParams.deviceSn"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备用途">
            <el-select v-model="queryParams.type" placeholder="请选择设备用途" clearable>
              <el-option v-for="item in deviceTypeOptions" :key="item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属水厂">
            <el-select v-model="queryParams.deviceWorks" placeholder="请选择所属水厂" filterable clearable>
              <el-option v-for="item in waterFactoryOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备状态">
            <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" :empty-values="[null, undefined]">
              <el-option label="全部" value="" />
              <el-option v-for="item in deviceStatusOptions" :key="item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="12">
          <div class="flex justify-end">
            <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
            <el-button @click="handleReset" :loading="loading">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '20px' }">
      <div class="flex justify-between items-center mb-[10px]">
        <el-button type="primary" @click="dialogVisible = true" :loading="loading" :icon="CirclePlus">新增设备</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading" row-key="id" border>
        <el-table-column prop="deviceName" label="设备名称" width="200" fixed/>
        <el-table-column prop="deviceSn" label="设备SN" width="180" />
        <el-table-column prop="deviceModel" label="设备型号" width="180"/>
        <el-table-column prop="organization.name" label="所属水厂" width="200"/>
        <el-table-column prop="typeName" label="设备用途" width="180"/>
        <el-table-column prop="deviceStatus" label="使用状态" width="180">
          <template #default="{ row }">
            <el-check-tag :checked="row.deviceStatus == 0" type="success" @change="onChangeTag(row)">
              {{ row.deviceStatus == 0 ? '正常' : '停用' }}
            </el-check-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createUser.nickName" label="创建人" width="180"/>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column prop="address" label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEditDevice(row)">编辑</el-button>
            <el-popconfirm title="请确认是否删除?" @confirm="handleDelete(row)" width="200">
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="initPageData" />

    </el-card>

    <el-dialog v-model="dialogVisible" :title="formData.deviceId ? '编辑设备' : '新增设备'" width="900" @closed="handleDialogReset">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px" label-position="left" require-asterisk-position="right">
        <el-row justify="space-between">
          <el-col :span="11">
            <el-form-item label="选择水厂" prop="deviceWorks">
              <el-select v-model="formData.deviceWorks" placeholder="请选择水厂" filterable clearable>
                <el-option v-for="item in waterFactoryOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备SN" prop="deviceSn">
              <el-input v-model.trim="formData.deviceSn" placeholder="请输入设备SN" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model.trim="formData.deviceName" placeholder="请输入设备名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-input v-model.trim="formData.deviceModel" placeholder="请输入设备型号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备用途" prop="type">
              <el-select v-model="formData.type" placeholder="请选择设备用途" clearable>
                <el-option v-for="item in deviceTypeOptions" :key="item.label" :label="item.label" :value="item.value?.toString()" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备状态" prop="deviceStatus">
              <el-select v-model="formData.deviceStatus" placeholder="请选择设备状态" clearable>
                <el-option v-for="item in deviceStatusOptions" :key="item.label" :label="item.label" :value="item.value?.toString()" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="维护人员" prop="deviceMaintainer">
              <el-input v-model.trim="formData.deviceMaintainer" placeholder="请输入维护人员" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="维护人员电话" prop="deviceTel">
              <el-input v-model.trim="formData.deviceTel" placeholder="请输入维护人员电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" >取 消</el-button>
          <el-button @click="handleDialogConfirm" type="primary">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<style lang="scss" scoped>

</style>