<template>
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" />
  <!-- 服务事项管理 -->
  <div class="regional-grid" v-if="!pageBasicsData.loading">
    <!-- 右侧区域 -->
    <div class="regional-grid-right">
      <!-- 顶部功能按钮 -->
      <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="工具名称" prop="name">
              <div class="screen-item">
                <el-input
                  placeholder="请输入工具名称"
                  clearable
                  v-model="pageBasicsData.screenForm.name"
                ></el-input>
              </div>
            </el-form-item>
            <el-form-item label="分类级别" prop="level">
              <div class="screen-item">
                <el-select
                  filterable
                  clearable
                  placeholder="请选择分类级别"
                  v-model="pageBasicsData.screenForm.level"
                >
                  <el-option
                    :label="item.value"
                    :value="item.key"
                    v-for="item in selectItems['level']"
                    :key="item.key"
                  ></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.value"
                    :value="item.key"
                    v-for="item in selectItems['status']"
                    :key="item.key"
                  ></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="[
            {
              cnName: '新建',
              enName: 'add',
              theme: 'success',
              icon: 'plus',
            },
            {
              cnName: '导出',
              enName: 'export',
              theme: 'primary',
              icon: 'top',
            },
          ]"
          @buttonClick="buttonClick"
        ></qu-table>
      </div>
    </div>
  </div>

  <!-- 新建弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isShowAddDialog"
    title="新建"
    width="600px"
    center
    @close="closeAddDialog"
  >
    <el-form
      class="dialog-form"
      label-width="130px"
      ref="addRef"
      :model="addForm"
    >
      <el-form-item
        label="所属站点"
        prop="districtId"
        :rules="{
          required: true,
          message: '请选择所属站点',
          trigger: 'change',
        }"
      >
        <el-select
          v-model="addForm.districtId"
          style="width: 350px"
          clearable
          filterable
          placeholder="请选择"
        >
          <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">
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="addForm.level"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['level']"
            :key="item.key"
          ></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
          v-model="addForm.parentId"
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          @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 v-model="addForm.name" style="width: 350px" />
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="status"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          v-model="addForm.status"
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['status']"
            :key="item.key"
          ></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" type="warning" @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"
    center
    @close="closeEditDialog"
  >
    <el-form
      class="dialog-form"
      label-width="130px"
      ref="editRef"
      :model="editForm"
    >
      <el-form-item
        label="所属站点"
        prop="districtName"
        v-if="editForm.level > 1"
        :rules="{
          required: true,
          message: '请选择所属站点',
          trigger: 'change',
        }"
      >
        <el-select
          v-model="editForm.districtName"
          style="width: 350px"
          clearable
          :disabled="true"
          filterable
          placeholder="请选择"
        >
        </el-select>
      </el-form-item>
      <el-form-item label="分类级别" prop="level">
        <el-select
          style="width: 350px"
          filterable
          clearable
          :disabled="true"
          placeholder="请选择"
          v-model="editForm.level"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['level']"
            :key="item.key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="editForm.level > 1"
        label="上级分类"
        prop="parentName"
        :rules="{
          required: true,
          message: '请选择上级分类',
          trigger: 'change',
        }"
      >
        <el-select
          v-model="editForm.parentName"
          style="width: 350px"
          filterable
          clearable
          :disabled="true"
          placeholder="请选择"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="工具名称"
        prop="name"
        :rules="{
          required: true,
          message: '请输入对象名称',
          trigger: 'change',
        }"
      >
        <el-input v-model="editForm.name" style="width: 350px" />
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="status"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          v-model="editForm.status"
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['status']"
            :key="item.key"
          ></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" type="warning" @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, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { toolManageService } from "@/ApiService/basicInfoService";
import { dropdownService } from "@/ApiService/dropdownService";

// 页面基础数据
const pageBasicsData = reactive({
  tableHeight: 200, //表格高度
  loading: true, // 加载状态
  screenForm: {
    // 顶部搜索字段
    districtId: "",
    name: "",
    level: "",
    status: "",
  },
  isShowAddDialog: false, //新增弹窗
  isShowEditDialog: false, //编辑弹窗
  districtList: [], // 所属站点列表
  superiorList: [], // 上级分类下拉列表
});

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

// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const addRef = ref(); // 新增弹窗ref
const editRef = ref(); //编辑弹窗ref
const screenFormRef = ref(); //搜索区ref元素

onMounted(() => {
  //获取站点数据
  fetchDistricts();
  // 表格行内按钮
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      pageBasicsData.isShowEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("确定要删除此数据么？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          toolManageService
            .removeTools({
              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] = "";
        }
      }
    }
  }
);
// 监听添加时所属站点change
watch(
  () => addForm.districtId,
  (val) => {
    if (val) {
      fetchParentObject(val);
    }
  }
);
// 监听添加时所属站点change
watch(
  () => addForm.level,
  (val) => {
    addForm.parentId = "";
  }
);
// #endregion watch定义end

// #region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    pageBasicsData.isShowAddDialog = true;
  }
  if (enName == "export") {
    const { page, rows } = pageProps;
    const { districtId, name, level, status } = pageBasicsData.screenForm;
    toolManageService.toolsExport({
      page,
      rows,
      districtId,
      name,
      level,
      status,
    });
  }
};

// 添加表单提交
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(() => {
          toolManageService.addOrUpdateTools(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(() => {
          toolManageService.addOrUpdateTools(editForm).then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              closeEditDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        });
    }
  });
};
// 关闭添加弹窗事件
const closeAddDialog = () => {
  pageBasicsData.isShowAddDialog = false;
  addRef.value.resetFields();
};
// 关闭编辑弹窗事件
const closeEditDialog = () => {
  pageBasicsData.isShowEditDialog = false;
  editRef.value.resetFields();
};
// 获取所属站点
const fetchDistricts = () => {
  return new Promise(() => {
    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();
        } else {
          $message.error("暂无站点信息,请配置站点!");
        }
      }
    });
  });
};
// 获取列表数据
const fetchData = () => {
  const { page, rows } = pageProps;
  toolManageService
    .toolsPageList({
      page,
      rows,
      ...pageBasicsData.screenForm,
    })
    .then((res) => {
      if (res.code == 0) {
        pageBasicsData.loading = false;
        tableData.value = res.data.rows;
        pageProps.records = res.data.records;
      }
    });
};
// 获取上级分类
const fetchParentObject = (id) => {
  dropdownService.getParentTools({ districtId: id }).then((res) => {
    if (res.code == 0) {
      pageBasicsData.superiorList = res.data;
    }
  });
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  pageBasicsData.screenForm.districtId = pageBasicsData.districtList[0].id;
  fetchData();
};
// 自定义表格头
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,
  restSearch,
  tableHeader,
  pageChange,
  buttonsClickFun,
  $message,
  $messageBox,
  $router,
  selectItems,
} = templateHooks(fetchData);
// #endregion 函数定义 end
</script>
<script>
export default {
  name: "ToolMange",
};
</script>
<style lang="scss" scoped>
.regional-grid {
  box-sizing: border-box;
  .regional-grid-right {
    height: calc(100vh - var(--page-top-offset));
    flex: 1;
    padding: 10px;
    background-color: var(--color-bg-card);
    .grid-right-search {
      padding: var(--spacing-md) var(--spacing-lg);
      display: flex;
      align-items: center;
    }
    .el-form {
      margin: 8px 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;
    }
  }
}
.generated {
  display: flex;
  .generated-left {
    padding-right: 60px;
    padding-top: 20px;
    margin-bottom: 20px;
    border: 1px solid #dcdfe6;
  }
  .generated-right {
    margin-left: 20px;
    padding-top: 13%;
  }
}
</style>
