<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getDeviceConfigList, removeDeviceConfig } from "@/api/device-config";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import DeviceConfigDialog from "./device-config-dialog.vue";
import { formatDict, getDictColor } from "@/utils/dict";

defineOptions({
  name: "AdminPlatformDeviceConfig"
});

const queryRef = ref();
const tableRef = ref();
const dialogRef = ref();

const state = reactive({
  formQuery: {
    name: "",
    remark: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "ID", prop: "id", width: 80 },
      { label: "配置名称", prop: "name", width: 180 },
      { label: "配置备注", prop: "remark", width: 200 },
      { label: "自动关闭", prop: "motorFlowOff", width: 100 },
      { label: "自动启动", prop: "motorFlowOn", width: 100 },
      { label: "泡沫单价", prop: "priceFoam", width: 100 },
      { label: "清水单价", prop: "priceWater", width: 100 },
      { label: "创建时间", prop: "createTime", width: 160 },
      { label: "更新时间", prop: "updateTime", width: 160 }
    ]
  }
});

onMounted(() => {
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 230;
  });
});

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getDeviceConfigList({ ...state.formQuery, ...state.pageQuery })
    .then((res: any) => {
      const { list, count } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = count || 0;
    })
    .catch(() => {
      state.tableData.data = [];
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    name: "",
    remark: ""
  };
  loadData(true);
};

const handleAdd = () => {
  dialogRef.value?.open("add");
};

const handleEdit = (row: any) => {
  dialogRef.value?.open("edit", row);
};

const handleView = (row: any) => {
  dialogRef.value?.open("view", row);
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`此操作将永久删除『${row.name}』，是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    removeDeviceConfig(row.id)
      .then(() => {
        ElMessage.success("删除成功");
        loadData(true);
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

const toBoolVal = (val: string | boolean) => (val === true || val === "true" || val === "1") ? 1 : 0;
const getBooleanText = (val: string | boolean) => formatDict("yes_no", toBoolVal(val));
const getBooleanType = (val: string | boolean) => getDictColor("yes_no", toBoolVal(val));

const formatPrice = (val: number) => {
  if (!val) return "¥0.00";
  return `¥${(val / 100).toFixed(2)}`;
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">设备配置</span>
      </template>
      <el-form
        ref="queryRef"
        :model="state.formQuery"
        inline
        class="search-form"
      >
        <el-form-item label="配置名称">
          <el-input
            v-model="state.formQuery.name"
            placeholder="请输入配置名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="配置备注">
          <el-input
            v-model="state.formQuery.remark"
            placeholder="请输入配置备注"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
          <el-button
            type="success"
            :icon="useRenderIcon('ri/add-line')"
            @click="handleAdd"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="tableRef"
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column
          v-for="col in state.tableData.columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template v-if="col.prop === 'name'">
              <span class="link" @click="handleView(row)">{{ row.name }}</span>
            </template>
            <template v-else-if="col.prop === 'motorFlowOff' || col.prop === 'motorFlowOn'">
              <el-tag :type="getBooleanType(row[col.prop])" size="small">
                {{ getBooleanText(row[col.prop]) }}
              </el-tag>
            </template>
            <template v-else-if="col.prop === 'priceFoam' || col.prop === 'priceWater'">
              {{ formatPrice(row[col.prop]) }}
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="warning" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <DeviceConfigDialog ref="dialogRef" @refresh="loadData(true)" />
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 15px;
}

.card-header { font-size: 16px; font-weight: 600; }

.search-form {
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.link {
  color: var(--el-color-primary);
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}
</style>
