<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
                v-model="pageBasicsData.screenForm.name"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="对象名称" prop="objectName">
            <div class="screen-item">
              <el-input
                placeholder="请输入对象名称"
                clearable
                :disabled="!!gridCascaderValue"
                v-model="pageBasicsData.screenForm.objectName"
              ></el-input>
            </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>

  <!-- 新建弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isShowAddDialog"
    title="新建"
    width="660px"
    @close="closeAddDialog"
  >
    <el-form
      style="border-top: 1px solid #dcdfe6; border-bottom: 1px solid #dcdfe6"
      label-width="130px"
      ref="addRef"
      :model="addForm"
    >
      <el-scrollbar height="440px" always>
        <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="currentName"
          :rules="{
            required: true,
            message: '请选择对象名称',
            trigger: 'change',
          }"
        >
          <el-cascader
            style="width: 350px"
            ref="objectNameRef"
            clearable
            v-model="addForm.currentName"
            :options="pageBasicsData.addTreeData[0].childrenNode"
            :props="pageBasicsData.objectNameProps"
            @change="objectHandleChange"
            @focus="
              () => {
                if (pageBasicsData.addTreeData[0].childrenNode.length <= 0) {
                  $message.warning(
                    '当前选择的所属站点暂无区域网格,请重新选择!'
                  );
                }
              }
            "
          >
            <template #default="{ data }">
              <span>{{ data.name }}</span>
            </template>
          </el-cascader>
        </el-form-item>
        <div
          style="margin-top: 30px"
          class="generated"
          v-for="(matter, index) in addForm.matterList"
          :key="index"
        >
          <div class="generated-left">
            <el-form-item
              label="事项名称"
              :prop="`matterList[${index}].name`"
              :rules="{
                required: true,
                message: '请输入事项名称',
                trigger: 'change',
              }"
            >
              <el-input style="width: 350px" v-model="matter.name" />
            </el-form-item>
            <el-form-item
              label="排序序号"
              :prop="`matterList[${index}].sort`"
              :rules="[
                { required: true, message: '请输入排序序号,只能为数字类型!' },
                { type: 'number', message: '只能为数字类型!' },
              ]"
            >
              <el-input
                style="width: 350px"
                placeholder="请输入排序序号,只能为数字类型!"
                v-model.number="matter.sort"
              />
            </el-form-item>
            <el-form-item
              label="停/启用状态"
              :prop="`matterList[${index}].status`"
              :rules="{
                required: true,
                message: '请选择停/启用状态',
                trigger: 'change',
              }"
            >
              <el-select
                style="width: 350px"
                filterable
                clearable
                placeholder="请选择"
                v-model="matter.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="`matterList[${index}].memo`">
              <el-input
                v-model="matter.memo"
                style="width: 350px"
                type="textarea"
                autosize
                maxlength="500"
                placeholder="请输入备注信息(非必填,限500字以内)"
              />
            </el-form-item>
          </div>
          <div class="generated-right">
            <el-icon
              color="#666666"
              size="18px"
              style="display: block"
              @click="addMatterForm"
              ><plus
            /></el-icon>
            <el-icon
              color="#666666"
              size="18px"
              style="display: block; margin-top: 10px"
              @click="removeMatterForm(matter)"
              ><remove
            /></el-icon>
          </div>
        </div>
      </el-scrollbar>
    </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"
      style="
        border-top: 1px solid #dcdfe6;
        border-bottom: 1px solid #dcdfe6;
        padding-bottom: 40px;
      "
      label-width="130px"
      ref="editRef"
      :model="editForm"
    >
      <el-form-item
        style="padding-top: 40px"
        label="所属站点"
        prop="districtId"
        :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="objectName"
        :rules="{
          required: true,
          message: '请选择对象名称',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          clearable
          :disabled="true"
          filterable
          placeholder="请选择对象名称"
          v-model="editForm.objectName"
        >
        </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: '请输入排序序号,只能为数字类型!' },
          { 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, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { serveMatterManageService } from "@/ApiService/basicInfoService";
import { dropdownService } from "@/ApiService/dropdownService";

// 页面基础数据
const pageBasicsData = reactive({
  treeData: [
    {
      childrenNode: [],
    },
  ], // 左侧树结构数据
  addTreeData: [
    {
      childrenNode: [],
    },
  ], // 添加时树结构数据
  tableHeight: 200, //表格高度
  loading: true, // 加载状态
  screenForm: {
    // 顶部搜索字段
    districtId: "",
    name: "",
    objectName: "",
    status: "",
    treeFlag: 0,
  },
  buttonList: [
    // 顶部按钮列表
    {
      cnName: "新建",
      enName: "add",
      theme: "success",
      icon: "plus",
    },
    {
      cnName: "导出",
      enName: "export",
      theme: "primary",
      icon: "top",
    },
  ],
  isShowAddDialog: false, //新增弹窗
  isShowEditDialog: false, //编辑弹窗
  districtList: [], // 所属站点列表
  classifyLevelList: [
    {
      key: "一级",
      value: 1,
    },
    {
      key: "二级",
      value: 2,
    },
  ],
  statusList: [
    {
      key: "停用",
      value: 0,
    },
    {
      key: "启用",
      value: 1,
    },
  ],
  objectNameProps: {
    // 对象名称级联配置
    expandTrigger: "hover",
    value: "id",
    label: "name",
    children: "childrenNode",
    checkStrictly: true,
  },
});

// 新增弹窗字段
let addForm = reactive({
  districtId: "",
  objectId: "",
  currentName: "",
  matterList: [
    {
      id: "",
      memo: "",
      name: "",
      sort: "",
      status: "",
    },
  ],
});
// 编辑弹窗字段
const editForm = reactive({});

// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const objectNameRef = ref();
const addRef = ref(); // 新增弹窗ref,表单校验
const editRef = ref(); // 新增弹窗ref,表单校验
const screenFormRef = ref(); //搜索区ref元素
const gridCascaderRef = ref(); // 网格级联选择器ref
const gridCascaderValue = ref(""); // 网格级联选择器选中值

// 网格级联选择器选项数据（来自左侧树结构数据）
const gridTreeOptions = ref([]);

onMounted(() => {
  fetchDistricts();
  // 表格行内按钮
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      pageBasicsData.isShowEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("确定要删除此数据么？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          serveMatterManageService
            .removeMatter({
              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 = "";
    }
  }
);
watch(
  () => addForm.districtId,
  (val) => {
    if (val) {
      fetchTree(val, true);
    }
  }
);
// #endregion watch定义end

// #region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    addForm.matterList = [
      {
        id: "",
        memo: "",
        name: "",
        sort: "",
        status: "",
      },
    ];
    pageBasicsData.isShowAddDialog = true;
  }
  if (enName == "export") {
    const { page, rows } = pageProps;
    serveMatterManageService.matterExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
};
// 新增级联change事件
const objectHandleChange = () => {
  let checkArr = objectNameRef.value.getCheckedNodes();
  let objectProps = {};
  checkArr.forEach((item) => {
    objectProps.objectId = item.value;
    objectProps.objectName = item.label;
  });
  return objectProps;
};
// 服务事项添加
const addMatterForm = () => {
  if (!addForm.districtId) {
    $message.warning("请先选择所属站点后,再进行批量添加!");
    return;
  }
  addForm.matterList.push({
    id: "",
    memo: "",
    name: "",
    sort: "",
    status: "",
  });
};
// 服务事项移除
const removeMatterForm = (item) => {
  if (addForm.matterList.length <= 1) return;
  const index = addForm.matterList.indexOf(item);
  if (index !== -1) {
    addForm.matterList.splice(index, 1);
  }
};

// 添加表单提交
const submitForm = () => {
  addRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          addForm.objectName = objectHandleChange().objectName;
          addForm.objectId = objectHandleChange().objectId;
          serveMatterManageService.addMatter(addForm).then((res) => {
            if (res.code == 0) {
              closeAddDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        })
        .catch(() => {});
    }
  });
};
// 编辑表单提交
const editSubmitForm = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          serveMatterManageService.updateMatter(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 = () => {
  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;
  serveMatterManageService
    .matterPageList({
      page,
      rows,
      ...pageBasicsData.screenForm,
    })
    .then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.loading = false;
        tableData.value = res.data.rows;
        pageProps.records = res.data.records;
      }
    });
};
// 网格级联选择器 change 事件
const gridCascaderChange = (val) => {
  pageBasicsData.screenForm.objectName = val || "";
  pageBasicsData.screenForm.treeFlag = val ? 1 : 0;
};
// 左侧树结构数据
const fetchTree = (id, isAdd) => {
  const { districtId } = pageBasicsData.screenForm;
  dropdownService
    .getObjectTree({ districtId: id ? id : districtId })
    .then(async (res) => {
      if (res.code == 0) {
        let newData = [];
        newData.push(res.data);
        if (!isAdd) {
          pageBasicsData.treeData = newData;
          gridTreeOptions.value = pageBasicsData.treeData[0].childrenNode || [];
        } else {
          pageBasicsData.addTreeData = newData;
          setTreeData(pageBasicsData.addTreeData[0].childrenNode);
        }
      }
    });
};
// 递归设置树结构
const setTreeData = (arr) => {
  arr.forEach((item) => {
    if (item.childrenNode?.length) {
      item.disabled = true;
    } else {
      setTreeData(item.childrenNode);
    }
  });
};
//查询
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,
} = templateHooks(fetchData);
// #endregion 函数定义 end
</script>
<script>
export default {
  name: "ServeMatterManage",
};
</script>
<style lang="scss" scoped>
.regional-grid {
  height: calc(100vh - var(--page-top-offset));
  box-sizing: border-box;
  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: 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>
