<template>
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" />
  <!-- 对象数据管理 -->
  <div class="regional-grid" v-if="!pageBasicsData.loading">
    <!-- 顶部功能按钮 -->
    <div class="grid-right-btn" ref="topSearchRef">
      <!-- 搜索区域 -->
      <qu-search-area :model="pageBasicsData.screenForm" @search="restSearch" @reset="clearScreen">
          <el-form-item label="所属站点" prop="districtId">
            <div class="screen-item">
              <el-select
                filterable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.districtId"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in pageBasicsData.districtList"
                  :key="item.id"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="对象分类">
            <el-cascader
              ref="gridCascaderRef"
              v-model="gridCascaderValue"
              :options="gridTreeOptions"
              :props="{
                children: 'childrenNode',
                label: 'name',
                value: 'name',
                checkStrictly: true,
                emitPath: false,
              }"
              clearable
              filterable
              placeholder="请选择对象分类"
              style="width: 200px"
              @change="gridCascaderChange"
            />
          </el-form-item>
          <el-form-item label="对象名称" prop="name">
            <div class="screen-item">
              <el-input
                placeholder="请输入对象名称"
                clearable
                :disabled="!!gridCascaderValue"
                v-model="pageBasicsData.screenForm.name"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="分类级别" prop="level">
            <div class="screen-item">
              <el-select
                clearable
                filterable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.level"
              >
                <el-option
                  :label="item.key"
                  :value="item.value"
                  v-for="item in pageBasicsData.classifyLevelList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="停/启用状态" prop="status">
            <div class="screen-item">
              <el-select
                filterable
                clearable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.status"
              >
                <el-option
                  :label="item.key"
                  :value="item.value"
                  v-for="item in pageBasicsData.statusList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
        </qu-search-area>
    </div>

    <!-- 表格 -->
    <div class="main-table">
      <qu-table
        :custom="true"
        :showPage="true"
        :showIndex="true"
        :height="pageBasicsData.tableHeight"
        :tableData="tableData"
        :tableHeader="tableHeader"
        :pageProps="pageProps"
        @pageChange="pageChange"
        :rowButtons="rowButtons"
        @rowButtonClick="rowButtonClick"
        @fetchTableAttr="fetchTableAttr"
        :tableButtons="pageBasicsData.buttonList"
        @buttonClick="buttonClick"
      ></qu-table>
    </div>
  </div>

  <!-- 导入对象数据弹窗 -->
  <div v-if="pageBasicsData.isImportDialog">
    <el-dialog
      width="600px"
      title="导入对象数据"
      v-model="pageBasicsData.isImportDialog"
    >
      <fileUploadCom
        templateUrl="https://xiaoqu-public-file.oss-cn-beijing.aliyuncs.com/objectModel.xlsx"
        :action="pageBasicsData.action"
        :districtId="pageBasicsData.screenForm.districtId"
        v-model:isImportDialog="pageBasicsData.isImportDialog"
        @importSubmit="importSubmit"
      ></fileUploadCom>
    </el-dialog>
  </div>
  <!-- 新建弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isShowAddDialog"
    title="新增"
    width="600px"
    @close="closeAddDialog"
  >
    <el-form
      class="dialog-form"
      label-width="130px"
      ref="addRef"
      :model="addForm"
    >
      <el-form-item
        style="padding-top: 40px"
        label="所属站点"
        prop="districtId"
        :rules="{
          required: true,
          message: '请选择所属站点',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          placeholder="请选择"
          v-model="addForm.districtId"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in pageBasicsData.districtList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="分类级别"
        prop="level"
        :rules="{
          required: true,
          message: '请选择分类级别',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="addForm.level"
        >
          <el-option
            :label="item.key"
            :value="item.value"
            v-for="item in pageBasicsData.classifyLevelList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="addForm.level > 1"
        label="上级分类"
        prop="parentId"
        :rules="{
          required: true,
          message: '请选择上级分类',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="addForm.parentId"
          @focus="
            () => {
              if (pageBasicsData.superiorList.length <= 0) {
                $message.warning('当前选择的所属站点暂无上级分类,请重新选择!');
              }
            }
          "
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in pageBasicsData.superiorList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="对象名称"
        prop="name"
        :rules="{
          required: true,
          message: '请输入对象名称',
          trigger: 'change',
        }"
      >
        <el-input style="width: 350px" v-model="addForm.name" />
      </el-form-item>
      <el-form-item
        label="排序序号"
        prop="sort"
        :rules="[
          {
            required: true,
            message: '请输入排序序号,只能为数字类型!',
            trigger: 'blur',
          },
          { type: 'number', message: '只能为数字类型!' },
        ]"
      >
        <el-input style="width: 350px" v-model.number="addForm.sort" />
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="status"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="addForm.status"
        >
          <el-option
            :label="item.key"
            :value="item.value"
            v-for="item in pageBasicsData.statusList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input
          v-model="addForm.memo"
          style="width: 350px"
          type="textarea"
          autosize
          maxlength="500"
          placeholder="请输入备注信息(非必填,限500字以内)"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button style="width: 90px" @click="closeAddDialog">取消</el-button>
        <el-button style="width: 90px" type="primary" @click="submitForm"
          >提交</el-button
        >
      </span>
    </template>
  </el-dialog>
  <!-- 编辑弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isShowEditDialog"
    title="编辑"
    width="600px"
    @close="closeEditDialog"
  >
    <el-form
      class="dialog-form"
      label-width="130px"
      ref="editRef"
      :model="editForm"
    >
      <el-form-item
        style="padding-top: 40px"
        label="所属站点"
        prop="districtName"
        :rules="{
          required: true,
          message: '请选择所属站点',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          :disabled="true"
          filterable
          placeholder="请选择"
          v-model="editForm.districtName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="分类级别"
        prop="level"
        :rules="{
          required: true,
          message: '请选择分类级别',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          :disabled="true"
          placeholder="请选择"
          v-model="editForm.level"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="editForm.level > 1"
        label="上级分类"
        prop="parentName"
        :rules="{
          required: true,
          message: '请选择上级分类',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          :disabled="true"
          clearable
          placeholder="请选择"
          v-model="editForm.parentName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="对象名称"
        prop="name"
        :rules="{
          required: true,
          message: '请输入对象名称',
          trigger: 'change',
        }"
      >
        <el-input style="width: 350px" v-model="editForm.name" />
      </el-form-item>
      <el-form-item
        label="排序序号"
        prop="sort"
        :rules="[
          {
            required: true,
            message: '请输入排序序号,只能为数字类型!',
            trigger: 'blur',
          },
          { type: 'number', message: '只能为数字类型!' },
        ]"
      >
        <el-input
          style="width: 350px"
          placeholder="请输入排序序号,只能为数字类型"
          v-model.number="editForm.sort"
        />
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="status"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="editForm.status"
        >
          <el-option
            :label="item.key"
            :value="item.value"
            v-for="item in pageBasicsData.statusList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input
          v-model="editForm.memo"
          style="width: 350px"
          type="textarea"
          autosize
          maxlength="500"
          placeholder="请输入备注信息(非必填,限500字以内)"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button style="width: 90px" @click="closeEditDialog">取消</el-button>
        <el-button style="width: 90px" type="primary" @click="editSubmitForm"
          >提交</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { objectManageService } from "@/ApiService/basicInfoService";
import { dropdownService } from "@/ApiService/dropdownService";
import fileUploadCom from "@/Components/basicInfo/fileUploadCom.vue";
import $api from "@/Apis/api";

// 页面基础数据
const pageBasicsData = reactive({
  treeData: [{ childrenNode: [] }], // 网格树结构数据
  tableHeight: 200, //表格高度
  loading: true, // 加载状态
  screenForm: {
    // 顶部搜索字段
    districtId: "",
    name: "",
    level: "",
    status: "",
    treeFlag: 0,
    objectName: "",
  },
  buttonList: [
    // 顶部按钮列表
    {
      cnName: "新建",
      enName: "add",
      theme: "success",
      icon: "plus",
    },
    {
      cnName: "导出",
      enName: "export",
      theme: "primary",
      icon: "top",
    },
    {
      cnName: "导入",
      enName: "import",
      theme: "warning",
      icon: "bottom",
    },
  ],
  isImportDialog: false, // 导入弹窗
  isShowAddDialog: false, //新增弹窗
  isShowEditDialog: false, //新增弹窗
  districtList: [], // 所属站点列表
  superiorList: [], // 上级分类下拉列表
  classifyLevelList: [
    {
      key: "一级",
      value: 1,
    },
    {
      key: "二级",
      value: 2,
    },
  ],
  statusList: [
    {
      key: "停用",
      value: 0,
    },
    {
      key: "启用",
      value: 1,
    },
  ],
  action: "",
});

// 网格级联选择器
const gridCascaderValue = ref('');
const gridCascaderRef = ref();

// 网格级联选择器数据（来自树结构）
const gridTreeOptions = computed(() => pageBasicsData.treeData[0]?.childrenNode || []);

// 网格级联选择器变更事件
const gridCascaderChange = (val) => {
  pageBasicsData.screenForm.treeFlag = val ? 1 : 0;
  pageBasicsData.screenForm.objectName = val || '';
  pageBasicsData.screenForm.name = val || '';
};

// 新增弹窗字段
let addForm = reactive({
  districtId: "",
  level: "",
  parentId: "",
  parentName: "",
  name: "",
  sort: "",
  status: "",
  memo: "",
});
// 编辑弹窗字段
const editForm = reactive({});

// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const addRef = ref(); // 新增弹窗ref,表单校验
const editRef = ref(); // 新增弹窗ref,表单校验
const screenFormRef = ref(); //搜索区ref元素

onMounted(() => {
  const devKey = $common.devKey;
  const baseUrl = devKey ? "/api" : import.meta.env.VITE_APP_API_ORIGIN;
  const uploadUrl = $api.basicInfo.objectDataManage.uploadFileObject;
  pageBasicsData.action = baseUrl + uploadUrl;
  fetchDistricts();
  // 表格行内按钮
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      pageBasicsData.isShowEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("确定要删除此数据么？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          objectManageService
            .removeObject({
              id: editForm.id,
            })
            .then((res) => {
              if (res.code == 0) {
                $message.success(res.data);
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        })
        .catch(() => {});
    },
  };
});

// #region watch定义start
// 设置表格高度
watch(
  () => topSearchRef.value,
  (val) => {
    let wHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    nextTick(() => {
      pageBasicsData.tableHeight = wHeight - val.clientHeight - 184;
    });
  }
);
// 站点变化清空其它查询条件
watch(
  () => pageBasicsData.screenForm.districtId,
  (val) => {
    if (val) {
      for (const key in pageBasicsData.screenForm) {
        if (key != "districtId") {
          pageBasicsData.screenForm[key] = "";
        }
      }
      gridCascaderValue.value = '';
      fetchTree();
    }
  }
);
// 监听添加时所属站点change
watch(
  () => addForm.districtId,
  (val) => {
    addForm.parentId = "";
    if (val) {
      fetchParentObject(val);
    }
  }
);

watch(
  () => addForm.level,
  () => {
    addForm.parentId = "";
  }
);
// #endregion watch定义end

// #region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    pageBasicsData.isShowAddDialog = true;
  }
  if (enName == "export") {
    const { page, rows } = pageProps;
    objectManageService.objectExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
  if (enName == "import") {
    pageBasicsData.isImportDialog = true;
  }
};

// 添加表单提交
const submitForm = () => {
  if (addForm.parentId) {
    pageBasicsData.superiorList.forEach((item) => {
      if (item.id == addForm.parentId) {
        addForm.parentName = item.name;
      }
    });
  } else {
    delete addForm.parentId;
    delete addForm.parentName;
  }
  addRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          objectManageService.addOrUpdateObject(addForm).then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              closeAddDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        });
    }
  });
};
// 编辑表单提交
const editSubmitForm = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          objectManageService.addOrUpdateObject(editForm).then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              closeEditDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        });
    }
  });
};
// 关闭添加弹窗事件
const closeAddDialog = () => {
  addRef.value.resetFields();
  pageBasicsData.isShowAddDialog = false;
};
// 关闭编辑弹窗事件
const closeEditDialog = () => {
  editRef.value.resetFields();
  pageBasicsData.isShowEditDialog = false;
};
// 导入网格
const importSubmit = (file) => {
  objectManageService.batchAddObject(file).then((res) => {
    if (res.code == 0) {
      $message.success(res.data);
      pageBasicsData.isImportDialog = false;
      fetchData();
    } else {
      $message.error(res.err);
    }
  });
};
// 获取所属站点
const fetchDistricts = () => {
  dropdownService.getDistrict().then(async (res) => {
    if (res.code == 0) {
      pageBasicsData.districtList = res.data;
      if (pageBasicsData.districtList?.length) {
        pageBasicsData.screenForm.districtId =
          pageBasicsData.districtList[0].id;
        fetchData();
        fetchTree();
      } else {
        $message.error("暂无站点信息,请配置站点!");
      }
    }
  });
};
// 获取列表数据
const fetchData = () => {
  const { page, rows } = pageProps;
  objectManageService
    .objectPageList({
      page,
      rows,
      ...pageBasicsData.screenForm,
    })
    .then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.loading = false;
        tableData.value = res.data.rows;
        pageProps.records = res.data.records;
      }
    });
};

// 网格树结构数据
const fetchTree = () => {
  const { districtId } = pageBasicsData.screenForm;
  dropdownService.getObjectTree({ districtId }).then(async (res) => {
    if (res.code == 0) {
      let newData = [];
      newData.push(res.data);
      pageBasicsData.treeData = newData;
    }
  });
};
// 获取上级分类
const fetchParentObject = (id) => {
  dropdownService.getParentObject({ districtId: id }).then((res) => {
    if (res.code == 0) {
      pageBasicsData.superiorList = res.data;
    }
  });
};
//查询
const restSearch = () => {
  pageProps.page = 1;
  fetchData();
  fetchTree();
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  gridCascaderValue.value = '';
  pageBasicsData.screenForm.objectName = '';
  pageBasicsData.screenForm.treeFlag = 0;
  fetchData();
  fetchTree();
};

// 自定义表格头
const fetchTableAttr = (tableAttr) => {
  tableHeader.value = tableAttr;
};
// 表格按钮
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    editForm[i] = row[i];
  }
  buttonsClickFun.data[$column.enName]();
};
const {
  tableData,
  rowButtons,
  pageProps,
  tableHeader,
  pageChange,
  buttonsClickFun,
  $message,
  $messageBox,
  $common,
} = templateHooks(fetchData);
// #endregion 函数定义 end
</script>
<script>
export default {
  name: "ObjectDataManage",
};
</script>
<style lang="scss" scoped>
.regional-grid {
  box-sizing: border-box;
  height: calc(100vh - var(--page-top-offset));
  padding: var(--spacing-md);
  background-color: var(--color-bg-card);
  overflow: auto;

  .grid-right-search {
    padding: var(--spacing-md) var(--spacing-lg);
    display: flex;
    align-items: center;
  }
  .el-form {
    margin: var(--spacing-sm) 0;
  }
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.dialog-item {
  width: 100%;
  display: flex;
  align-items: center;
  margin-left: 30px;
  .dialog-item-left {
    margin-right: 30px;
    div {
      margin-bottom: 30px;
    }
  }
  .dialog-item-right {
    .el-button {
      margin-bottom: 26px;
    }
  }
}
:deep(.el-upload-list__item-status-label) {
  position: absolute;
  right: -25px;
  top: 0;
  line-height: inherit;
}
:deep(.el-upload-list__item .el-icon--close) {
  position: absolute;
  top: 5px;
  right: -10px;
  cursor: pointer;
  opacity: 0.75;
  color: #292d3e;
}
</style>
