<template>
  <div class="detail-container">
    <el-card shadow="hover">
      <el-descriptions title="基础信息" :column="3">
        <el-descriptions-item label="服务站名称:">{{
          basicData.mc
        }}</el-descriptions-item>
        <el-descriptions-item label="服务站经度:">{{
          basicData.jd
        }}</el-descriptions-item>
        <el-descriptions-item label="服务站纬度:">{{
          basicData.wd
        }}</el-descriptions-item>
        <el-descriptions-item label="设备数:">{{
          basicData.sbsl
        }}</el-descriptions-item>
        <el-descriptions-item label="物资数:">{{
          basicData.wzsl
        }}</el-descriptions-item>
        <el-descriptions-item label="人员数:">{{
          basicData.rysl
        }}</el-descriptions-item>
        <el-descriptions-item label="创建日期:">{{
          basicData.createTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card shadow="hover">
      <el-descriptions title="配置信息" :column="3"> </el-descriptions>
      <el-tabs v-model="activeTab" class="demo-tabs" @tab-click="handleClick">
        <div class="button-container">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <el-tab-pane label="人员信息" name="people">
          <DynamicTable
            :dataSource="peopleList"
            :columns="columns()"
            :autoHeight="true"
            :pagination="pagination"
          ></DynamicTable>
        </el-tab-pane>
        <el-tab-pane label="物资信息" name="material">
          <DynamicTable
            :dataSource="materialList"
            :columns="columns()"
            :autoHeight="true"
            :pagination="pagination"
          ></DynamicTable>
        </el-tab-pane>
        <el-tab-pane label="设备信息" name="equipment">
          <DynamicTable
            :dataSource="equipmentList"
            :columns="columns()"
            :autoHeight="true"
            :pagination="pagination"
          ></DynamicTable>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <MyDialog
      v-model="modelVisible"
      :title="model?.title"
      :dynamicComponent="model?.content"
      :component-props="model?.props"
      :onConfirm="model?.onConfirm"
      :onCancel="model?.onCancel"
      ref="dialogRef"
      :width="model?.width"
    >
    </MyDialog>
  </div>
</template>
  
  <script setup>
import { h, ref, onMounted, reactive, watch, toRaw, nextTick } from "vue";
import DynamicTable from "../../component/DynamicTable";
import MyDialog from "../../component/MyDialog";
import { request } from "@/utils/request";
import { render } from "less";
import PersonAddDialog from "./component/PersonAddDialog.vue";
import MaterialAddDialog from "./component/MaterialAddDialog.vue";
import EquipmentAddDialog from "./component/EquipmentAddDialog.vue";
const props = defineProps({
  basicData: {
    type: Object,
    default: () => ({}),
  },
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "prev, pager, next, jumper",
  onChange: (page, pageSize) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    if (activeTab.value === "people") {
      getPeopleList();
    }
  },
}); // 表格分页

const columns = () => {
  switch (activeTab.value) {
    case "people":
      return [
        {
          width: "100px",
          label: "序号",
          render: (...args) => {
            return () => {
              const actualIndex =
                (pagination.current - 1) * pagination.pageSize + args[2] + 1;
              return h("div", {}, actualIndex);
            };
          },
        },
        {
          prop: "xm",
          label: "姓名",
        },
        {
          prop: "sjhm",
          label: "手机号",
        },
        {
          label: "人员角色",
          render: (row) => () => {
            const role = Number(row.ryjs);
            const config = {
              1: { type: "danger", text: "负责人" },
              2: { type: "success", text: "普通工作人员" },
            }[role] || { type: "info", text: "未知角色" };

            return h(
              ElTag,
              {
                type: config.type,
                style: { margin: "2px" },
              },
              () => config.text
            );
          },
        },
        {
          label: "操作",
          fixed: "right",
          width: 150,
          render: (row) => () =>
            h("div", { class: "action-btns" }, [
              h(
                ElButton,
                {
                  type: "danger",
                  link: true,
                  style: "margin-left: 10px;",
                  onClick: async () => {
                    try {
                      await ElMessageBox.confirm(
                        "确定要删除该人员吗？",
                        "删除确认",
                        {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning",
                        }
                      );
                      const res = await request({
                        url: `/snow-ops-platform/yhzry/delete`,
                        method: "POST",
                        data: {
                          id: row.id,
                        },
                      });
                      if (res.code === "00000") {
                        ElMessage.success("删除成功");
                        getPeopleList();
                      }
                    } catch (error) {
                      if (error instanceof Error) {
                        ElMessage.error(error.message || "删除失败");
                      }
                    }
                  },
                },
                () => "删除"
              ),
            ]),
        },
      ];
    case "material":
      return [
        {
          width: "100px",
          label: "序号",
          render: (...args) => {
            return () => {
              const actualIndex =
                (pagination.current - 1) * pagination.pageSize + args[2] + 1;
              return h("div", {}, actualIndex);
            };
          },
        },
        {
          prop: "wzmc",
          label: "物资名称",
        },
        {
          prop: "ye",
          label: "余量",
          render: (row) => () => {
            return h("span", {}, row.ye + " " + row.dw);
          },
        },
        {
          prop: "fzr",
          label: "负责人",
        },
        {
          prop: "rkrq",
          label: "入库日期",
          render: (row) => () => {
            return h("span", row.rkrq?.substring(0, 10));
          },
        },
      ];
    case "equipment":
      return [
        {
          width: "100px",
          label: "序号",
          render: (...args) => {
            return () => {
              const actualIndex =
                (pagination.current - 1) * pagination.pageSize + args[2] + 1;
              return h("div", {}, actualIndex);
            };
          },
        },
        {
          prop: "sbmc",
          label: "设备名称",
        },
        {
          prop: "sbxh",
          label: "设备型号",
        },
        {
          prop: "sbbh",
          label: "设备编号",
        },
        {
          prop: "sbdl",
          label: "设备大类",
        },
        {
          prop: "sblx",
          label: "设备类型",
        },
        {
          prop: "gzrq",
          label: "购置日期",
          render: (row) => () => {
            return h("span", row.gzrq?.substring(0, 10));
          },
        },
      ];
  }
};

onMounted(() => {
  getPeopleList();
});

const peopleList = ref([]); // 人员列表
const materialList = ref([]); // 物资列表
const equipmentList = ref([]); // 设备列表

const activeTab = ref("people");

// 查询养护站人员列表
const getPeopleList = async () => {
  try {
    const data = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      yhzid: props.basicData.id,
    };
    const res = await request({
      url: "/snow-ops-platform/yhzry/list",
      method: "get",
      params: data,
    });
    if (res.code === "00000") {
      pagination.total = res.data.total;
      peopleList.value = res.data.records;
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    console.log(error);
    ElMessage.error(error.message);
  }
};

// 查询养护站物资列表
const getMaterialList = async () => {
  try {
    const data = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      yhzid: props.basicData.id,
    };
    const res = await request({
      url: "/snow-ops-platform/yjwz/list",
      method: "get",
      params: data,
    });
    if (res.code === "00000") {
      pagination.total = res.data.total;
      materialList.value = res.data.records;
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    console.log(error);
    ElMessage.error(error.message);
  }
};

// 查询养护站设备列表
const getEquipmentList = async () => {
  try {
    const data = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      yhzid: props.basicData.id,
    };
    const res = await request({
      url: "/snow-ops-platform/yjsb/list",
      method: "get",
      params: data,
    });
    if (res.code === "00000") {
      pagination.total = res.data.total;
      equipmentList.value = res.data.records;
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    console.log(error);
    ElMessage.error(error.message);
  }
};

const handleClick = (tab, event) => {
  pagination.current = 1;
  switch (tab.props.name) {
    case "people":
      getPeopleList();
      break;
    case "material":
      getMaterialList();
      break;
    case "equipment":
      getEquipmentList();
      break;
  }
};

// 新增相关
const peopleForm = reactive({});
const INIT_FORM_people = {
  userId: "",
  ryjs: 1,
  yhzid: props.basicData.id,
  sjhm: "",
  xm: "",
  jd: "",
  wd: "",
};
const materialForm = reactive({});
const INIT_FORM_material = {
  material: {
    rkrq: "",
    rkdw: "",
    sl: "",
    dw: "",
    cfdd: "",
    fzr: "",
    lxdh: "",
    ye: "",
    qxmc: "",
    wzmc: "",
    fzrid: "",
    yhzid: "",
    jd: "",
    wd: "",
  },
  photos: [],
};
const equipmentForm = reactive({});
const INIT_FORM_equipment = {
  rid: "",
  qxmc: "",
  sbbh: "",
  sbdl: "",
  sbmc: "",
  sblx: "",
  sbxh: "",
  sbwz: "",
  jd: props.basicData.jd,
  wd: props.basicData.wd,
  glry: "",
  glryid: "",
  czy: "",
  czyid: "",
  gzrq: "",
  gmfy: "",
  sbzt: "",
  sccj: "",
  sfyjsb: "",
  sfnrsjbz: "",
  fsfw: "",
  yhzid: props.basicData.id,
};
const dialogRef = ref(null);
const modelVisible = ref(false);
const model = reactive({
  title: "",
  content: null,
  props: {},
  onConfirm: () => {},
  onCancel: () => {},
  width: "30%",
});
const handleAdd = () => {
  switch (activeTab.value) {
    case "people":
      model.title = "新增人员";
      model.content = PersonAddDialog;
      Object.assign(peopleForm, INIT_FORM_people);
      model.props = {
        form: peopleForm,
      };
      model.onConfirm = handleAddPeopleConfirm;
      model.onCancel = handleCancel;
      model.width = "30%";
      modelVisible.value = true;
      break;
    case "material":
      model.title = "新增物资";
      model.content = MaterialAddDialog;
      // 重置表单
      materialForm.material = { ...INIT_FORM_material.material };
      materialForm.photos = [...INIT_FORM_material.photos];
      materialForm.material.yhzid = props.basicData.id;
      materialForm.material.jd = props.basicData.jd;
      materialForm.material.wd = props.basicData.wd;
      model.props = {
        form: materialForm,
        basicData: props.basicData,
      };
      model.onConfirm = handleAddMaterialConfirm;
      model.onCancel = handleCancel;
      model.width = "40%";
      modelVisible.value = true;
      break;
    case "equipment":
      console.log("basicData", toRaw(props.basicData));
      model.title = "新增设备";
      model.content = EquipmentAddDialog;
      // 重置表单
      Object.assign(equipmentForm, INIT_FORM_equipment);
      model.props = {
        form: equipmentForm,
        basicData: props.basicData,
      };
      model.onConfirm = handleAddEquipmentConfirm;
      model.onCancel = handleCancel;
      model.width = "60%";
      modelVisible.value = true;
      break;
  }
};

// 新增负责人
const handleAddPeopleConfirm = async () => {
  await dialogRef?.value?.dynamicComponentRef?.formRef
    .validate()
    .then(async () => {
      try {
        const res = await request({
          url: "/snow-ops-platform/yhzry/add",
          method: "post",
          data: toRaw(peopleForm),
        });
        if (res.code === "00000") {
          ElMessage.success("新增成功");
          modelVisible.value = false;
          getPeopleList();
        } else {
          throw new Error(res.message);
        }
      } catch (error) {
        console.log(error);
        ElMessage.error(error.message);
      }
    })
    .catch((err) => {
      ElMessage.error("请处理表单中的错误项");
    });
};

// 新增物资
const handleAddMaterialConfirm = async () => {
  await dialogRef?.value?.dynamicComponentRef?.formRef
    .validate()
    .then(async () => {
      try {
        const res = await request({
          url: "/snow-ops-platform/yjwz/add",
          method: "post",
          data: toRaw(materialForm),
        });
        if (res.code === "00000") {
          ElMessage.success("新增成功");
          modelVisible.value = false;
          getMaterialList();
        } else {
          throw new Error(res.message);
        }
      } catch (error) {
        console.log(error);
        ElMessage.error(error.message);
      }
    })
    .catch((err) => {
      ElMessage.error("请处理表单中的错误项");
    });
};

// 新增设备
const handleAddEquipmentConfirm = async () => {
  try {
    const data = {
      equipment: toRaw(equipmentForm),
    };
    console.log("data", data);
    const res = await request({
      url: "/snow-ops-platform/yjsb/add",
      method: "post",
      data: {
        equipment: toRaw(equipmentForm),
      },
    });
    if (res.code === "00000") {
      ElMessage.success("新增成功");
      modelVisible.value = false;
      getEquipmentList();
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    console.log(error);
    ElMessage.error(error.message);
  }
};

// 取消
const handleCancel = () => {
  modelVisible.value = false;
};
</script>
  
  <style>
.detail-container {
  display: flex;
  flex-direction: column;
  gap: 30px;
}
.button-container {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin: 10px 0px 10px 0px;
}
</style>