<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="分组名称">
        <el-input v-model="queryParams.groupName" placeholder="分组名称" width="120px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" :disabled="state.search_disabled" @click="queryList">
          查询分组
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAddRoot">新增分组</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" :height="tableHeight"
      highlight-current-row @current-change="handleCurrentRowChange"
      :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
      <el-table-column fixed type="index" width="50" align="center" />
      <el-table-column fixed prop="groupName" label="分组名称" header-align="center" width="200" />
      <el-table-column prop="groupPy" label="拼音简码" header-align="center" width="140" />
      <el-table-column label="分组等级" header-align="center" align="center" width="80">
        <template #default="scope">
          <el-tag>{{ scope.row.groupLevel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed prop="parentName" label="上级分组" header-align="center" width="200" />
      <el-table-column prop="createMan" label="创建人" header-align="center" width="120" />
      <el-table-column fit prop="groupMemo" label="分组备注" header-align="center" min-width="90" />
      <el-table-column fixed="right" label="" align="left" width="150">
        <template #default="scope">
          <el-button type="text" :disabled="scope.row.groupLevel === 4" @click="handleAddChild(scope.row)">新增
          </el-button>
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-config-provider :locale="locale">
      <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
        :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
        :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
        style="text-align: center; margin-top: 10px; height: 30px" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-config-provider>

    <el-dialog :title="adddialog.title" v-model="adddialog.visible" width="450px" draggable center>
      <el-form ref="formRef" :model="formData" :rules="state.rules" label-width="100px">
        <el-form-item label="上级分组:">
          <el-input v-model="formData.parentName" disabled width="120px" />
        </el-form-item>
        <el-form-item label="分组名称:" prop="groupName">
          <el-input v-model="formData.groupName" placeholder="分组名称" width="120px" />
        </el-form-item>
        <el-form-item label="分组拼音码:">
          <el-input v-model="formData.groupPy" placeholder="分组拼音码" width="120px" />
        </el-form-item>
        <el-form-item label="分组备注:">
          <el-input v-model="formData.groupMemo" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import StationGroupAction from "@/api/station/stationgroup";
import { StationGroupQueryParam, StationGroupModel, Dialog, PageResult } from "@/types";
import tool from "@/until/tool"
import zhCn from "element-plus/lib/locale/lang/zh-cn";

let locale = ref(zhCn);

const formRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

const loading = ref(false);

const state = reactive({
  queryParams: { page: 1, rows: 10, customerId: localStorage.getItem("CustomerId") || "" } as StationGroupQueryParam,
  currentType: 0,//val=0 新增根节点; =1 新增子节点; =2 编辑;
  total: 0,
  small: false,
  background: true,
  disabled: false,
  search_disabled: false,
  adddialog: {} as Dialog,
  formData: {} as StationGroupModel,
  tableData: [] as StationGroupModel[],
  rules: {
    groupName: [
      { required: true, message: "分组名称不能为空", trigger: "blur" },
    ],
  },
});

const {
  queryParams,
  total,
  adddialog,
  formData,
  tableData,
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 250);

const currentRow = ref();

const handleCurrentRowChange = (val: StationGroupModel | undefined) => {
  currentRow.value = val;
};

const handleAddRoot = () => {
  state.currentType = 0;
  state.formData = {} as StationGroupModel;
  state.formData.parentCode = "1";
  state.formData.groupLevel = 1;
  state.formData.customerId = localStorage.getItem("CustomerId") || "";
  state.formData.createMan = localStorage.getItem("UserName") || "";
  state.adddialog = {
    title: "新增遥测站分组",
    visible: true,
    disabled: false,
  };
};

const handleAddChild = (val: StationGroupModel) => {
  state.currentType = 1;
  state.formData = {} as StationGroupModel;
  state.formData.parentCode = val.groupCode;
  state.formData.parentName = val.groupName;
  state.formData.groupLevel = val.groupLevel + 1;
  state.formData.customerId = localStorage.getItem("CustomerId") || "";
  state.formData.createMan = localStorage.getItem("UserName") || "";
  state.adddialog = {
    title: "新增遥测站分组",
    visible: true,
    disabled: false,
  };
};

const handleEdit = (row: StationGroupModel) => {
  state.currentType = 2;
  state.formData = JSON.parse(JSON.stringify(row));;
  state.adddialog = {
    title: "编辑遥测站分组",
    visible: true,
    disabled: false,
  };
};

const queryList = () => {
  loading.value = true;
  state.search_disabled = true;
  StationGroupAction.QueryStationGroupList(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as StationGroupModel[];
          state.tableData = pageData;
          state.total = pageData.length;
        } else {
          ElMessage.error(error);
        }
        loading.value = false;
        state.search_disabled = false;
      }
    })
    .catch((error) => {
      //请求失败时的操作
      loading.value = false;
      state.search_disabled = false;
    });
};

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
};

const submitForm = () => {
  if (state.currentType == 0 || state.currentType == 1) {
    formRef.value.validate((valid: any) => {
      if (valid) {
        StationGroupAction.AddStationGroup(state.formData).then((result) => {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success("新增成功");
            queryList();
          } else {
            ElMessage.error(error);
          }
        }).catch((error) => {
          ElMessage.success(error);
        });
      }
    });
  } else if (state.currentType == 2) {
    state.formData.customerId = localStorage.getItem("CustomerId") || "";
    state.formData.createMan = localStorage.getItem("UserName") || "";
    StationGroupAction.EditStationGroup(state.formData).then((result) => {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success("编辑成功");
        queryList();
      }
      else {
        ElMessage.error(error);
      }
    });
  }
  cancel();
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(" 是否删除分组[" + row.groupName + "]? ", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
    center: true,
  })
    .then(() => {
      StationGroupAction.DeleteStationGroup(row.id).then((result) => {
        ElMessage.success("删除成功");
        queryList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除成功!",
      });
    });
};

const cancel = () => {
  state.adddialog.visible = false;
};

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 250;
  };

  queryList();
});
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}
</style>