<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="pageBasicsData.treeData[0].childNode"
              :props="{
                children: 'childNode',
                label: 'name',
                value: 'gridId',
                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="gridLevel">
            <div class="screen-item">
              <el-select
                filterable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.gridLevel"
              >
                <el-option
                  :label="item.key"
                  :value="item.value"
                  v-for="item in pageBasicsData.gridRankList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="负责人" prop="userId">
            <div class="screen-item">
              <el-select
                filterable
                clearable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.userId"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in pageBasicsData.princiPalList"
                  :key="item.id"
                ></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/gridModel.xlsx"
        :action="pageBasicsData.action"
        :districtId="pageBasicsData.screenForm.districtId"
        v-model:isImportDialog="pageBasicsData.isImportDialog"
        @importSubmit="importSubmit"
      ></fileUploadCom>
    </el-dialog>
  </div>

  <!-- 新建弹窗 -->
  <el-dialog
    title="新建"
    width="600px"
    v-model="pageBasicsData.isShowAddDialog"
    @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="superiorId">
        <el-cascader
          style="width: 350px"
          ref="gridRef"
          clearable
          v-model="addForm.superiorId"
          :options="pageBasicsData.addTreeData[0].childNode"
          :props="pageBasicsData.areaGridSelectProps"
          @change="gridHandleChange"
          @focus="
            () => {
              if (pageBasicsData.addTreeData[0].childNode.length <= 0) {
                $message.warning('当前选择的所属站点暂无上级网格,请重新选择!');
              }
            }
          "
        >
          <template #default="{ data }">
            <span>{{ data.name }}</span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="网格等级" prop="gridLevel">
        <el-input
          :disabled="true"
          style="width: 350px"
          v-model.number="addForm.gridLevel"
        />
      </el-form-item>
      <el-form-item
        label="网格名称"
        prop="name"
        :rules="[
          { required: true, message: '请输入网格名称!', trigger: 'blur' },
        ]"
      >
        <el-input style="width: 350px" v-model="addForm.name" />
      </el-form-item>
      <el-form-item
        label="网格排序"
        prop="orderby"
        :rules="[
          { required: true, message: '请输入排序序号,只能为数字类型!' },
          { type: 'number', message: '只能为数字类型!' },
        ]"
      >
        <el-input
          style="width: 350px"
          placeholder="请输入排序序号,只能为数字类型!"
          v-model.number="addForm.orderby"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="userIds">
        <el-input
          style="width: 350px"
          v-model="addForm.userIds"
          v-if="pageBasicsData.functionaryList.length <= 0"
        />
        <div
          style="width: 350px; border: 1px solid #dcdfe6; border-radius: 5px"
          v-else
        >
          <el-tag
            style="margin: 5px"
            v-for="tag in pageBasicsData.functionaryList"
            :key="tag.name"
            :type="tag.type"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        <el-button
          type="primary"
          size="small"
          round
          style="margin-left: 5px"
          @click="goSelectPrincipal(1)"
          >去选择</el-button
        >
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input
          v-model="addForm.note"
          style="width: 350px"
          type="textarea"
          autosize
          maxlength="500"
          placeholder="请输入备注信息(非必填,限500字以内)"
          show-word-limit
        />
      </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"
          filterable
          :disabled="true"
          placeholder="请选择"
          v-model="editForm.districtName"
        >
          <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="上级网格"
        v-if="
          pageBasicsData.treeData[0].childNode.length > 0 &&
          editForm.superiorName
        "
        prop="superiorName"
      >
        <el-input
          style="width: 350px"
          clearable
          :disabled="true"
          v-model="editForm.superiorName"
        />
      </el-form-item>
      <el-form-item
        label="网格等级"
        prop="gridLevel"
        :rules="{
          required: true,
          message: '请选择网格等级',
          trigger: 'change',
        }"
      >
        <el-input
          :disabled="true"
          style="width: 350px"
          v-model.number="editForm.gridLevel"
        />
      </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="orderby"
        :rules="[
          {
            required: true,
            message: '请输入排序序号,只能为数字类型!',
            trigger: 'blur',
          },
          { type: 'number', message: '只能为数字类型!' },
        ]"
      >
        <el-input
          style="width: 350px"
          placeholder="请输入排序序号,只能为数字类型!"
          v-model.number="editForm.orderby"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="userIds">
        <div
          v-if="editForm.userIds?.length > 0"
          style="width: 350px; border: 1px solid #dcdfe6; border-radius: 5px"
        >
          <el-tag
            style="margin: 5px"
            v-for="tag in editForm.userIds"
            :key="tag.id"
            :type="tag.type"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        <el-input style="width: 350px" v-else></el-input>
        <el-button
          type="primary"
          size="small"
          round
          style="margin-left: 5px"
          @click="goSelectPrincipal(2)"
          >去选择</el-button
        >
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input
          v-model="editForm.note"
          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>

  <!-- 选择负责人 -->
  <div v-if="pageBasicsData.showSelectPrincipal">
    <el-dialog
      v-model="pageBasicsData.showSelectPrincipal"
      title="选择负责人"
      fullscreen
    >
      <selectPrincipal
        @closePrincipalDialog="closePrincipalDialog"
        :districtId="addForm.districtId || editForm.districtId"
        :selectedPersonnel="editForm.userIds"
      />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import selectPrincipal from "@/Components/basicInfo/selectPrincipal.vue";
import fileUploadCom from "@/Components/basicInfo/fileUploadCom.vue";
import { regionalGridManageService } from "@/ApiService/basicInfoService";
import { dropdownService } from "@/ApiService/dropdownService";
import $api from "@/Apis/api";

//页面基础数据
const pageBasicsData = reactive({
  treeData: [{ childNode: [] }], // 左侧树结构数据
  addTreeData: [{ childNode: [] }], // 添加时树结构数据
  tableHeight: 200, //表格高度
  loading: true, // 页面加载状态
  screenForm: {
    // 顶部搜索字段
    districtId: "",
    name: "",
    gridLevel: 1,
    userId: "",
    gridId: "",
  },
  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, //编辑弹窗
  showSelectPrincipal: false, // 选择负责人弹窗弹窗
  districtList: [], // 所属站点列表
  gridRankList: [
    // 网格级别下拉列表
    {
      key: "一级",
      value: 1,
    },
    {
      key: "二级",
      value: 2,
    },
    {
      key: "三级",
      value: 3,
    },
  ],
  princiPalList: [], // 负责人下拉列表
  functionaryList: [], // 已选负责人列表
  areaGridSelectProps: {
    expandTrigger: "hover",
    value: "gridId",
    label: "name",
    children: "childNode",
    checkStrictly: true,
  },
  action: "",
});
// 新增弹窗字段
let addForm = reactive({
  districtId: "",
  superiorId: "",
  superiorName: "",
  gridLevel: 1,
  name: "",
  orderby: "",
  userIds: [],
  note: "",
});
// 编辑弹窗字段
const editForm = reactive({});

// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const gridRef = ref(); // 上级网格ref
const addRef = ref(); // 新增弹窗ref,
const editRef = ref(); // 编辑弹窗ref,
const screenFormRef = ref(); //搜索区ref
const searchAreaRef = ref(); // 搜索区组件ref
const gridCascaderValue = ref(''); // 网格级联选择器值
const gridCascaderRef = ref(); // 网格级联选择器ref

onMounted(() => {
  const devKey = $common.devKey;
  const baseUrl = devKey ? "/api" : import.meta.env.VITE_APP_API_ORIGIN;
  const uploadUrl = $api.basicInfo.regionalGridManage.uploadFile;
  pageBasicsData.action = baseUrl + uploadUrl;
  //获取站点数据
  fetchDistricts();
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      pageBasicsData.isShowEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("确定要删除此数据么？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          regionalGridManageService
            .delete({
              id: editForm.id,
              gridLevel: editForm.gridLevel,
            })
            .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] = "";
        }
      }
    }
    pageBasicsData.screenForm.gridLevel = 1;
    gridCascaderValue.value = '';
  }
);
// 监听添加时所属站点change
watch(
  () => addForm.districtId,
  (val) => {
    addForm.superiorId = "";
    if (val) {
      fetchPrinciPalList(val);
      fetchSpecialGridTreeByAdd(val);
    }
  }
);
// 监听上级网格change
watch(
  () => addForm.superiorId,
  (val) => {
    if (!val) {
      addForm.gridLevel = 1;
    }
  }
);
//#endregion watch定义end

//#region 函数定义start

// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    editForm.userIds = [];
    pageBasicsData.functionaryList = [];
    pageBasicsData.isShowAddDialog = true;
  }
  if (enName == "export") {
    const { page, rows } = pageProps;
    regionalGridManageService.gridExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
  if (enName == "import") {
    pageBasicsData.isImportDialog = true;
  }
};

// 添加表单提交
const submitForm = () => {
  addRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          if (pageBasicsData.functionaryList.length > 0) {
            pageBasicsData.functionaryList.forEach((item) => {
              addForm.userIds.push({ id: item.id });
            });
          }
          regionalGridManageService.add(addForm).then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              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(() => {
          regionalGridManageService.update(editForm).then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              closeEditDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        })
        .catch(() => {});
    }
  });
};
// 网格级别
const gridHandleChange = () => {
  let checkArr = gridRef.value.getCheckedNodes();
  checkArr.forEach((item) => {
    addForm.superiorId = item.value;
    addForm.gridLevel = item.level + 1;
  });
};
// 关闭添加弹窗事件
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();
          fetchTree();
        } else {
          $message.error("暂无站点信息,请配置站点!");
        }
      }
    });
  });
};
// 获取列表数据
const fetchData = () => {
  const { page, rows } = pageProps;
  fetchPrinciPalList();
  return new Promise(() => {
    regionalGridManageService
      .pageList({
        page,
        rows,
        ...pageBasicsData.screenForm,
      })
      .then((res) => {
        if (res.code == 0) {
          pageBasicsData.loading = false;
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        }
      });
  });
};

// 左侧树结构点击事件（保留，逻辑复用于级联选择器）
const nodeClick = ({ dom }) => {
  pageBasicsData.screenForm.gridLevel = dom.gridLevel + 1;
  pageBasicsData.screenForm.gridId = dom.gridId;
  pageBasicsData.screenForm.userId = "";
  fetchData();
};
// 网格级联选择器 change 事件
const gridCascaderChange = (val) => {
  if (!val) {
    pageBasicsData.screenForm.gridId = '';
    pageBasicsData.screenForm.gridLevel = 1;
    return;
  }
  const checkedNodes = gridCascaderRef.value?.getCheckedNodes();
  if (checkedNodes && checkedNodes.length > 0) {
    const node = checkedNodes[0].data;
    pageBasicsData.screenForm.gridLevel = node.gridLevel + 1;
    pageBasicsData.screenForm.gridId = node.gridId;
    pageBasicsData.screenForm.userId = '';
  }
};
// 左侧树结构数据
const fetchTree = () => {
  const { districtId } = pageBasicsData.screenForm;
  return new Promise(() => {
    dropdownService.gridTree({ districtId }).then(async (res) => {
      if (res.code == 0) {
        let newData = [];
        newData.push(res.data);
        pageBasicsData.treeData = newData;
      }
    });
  });
};
// 区域网格级联数据
const fetchSpecialGridTreeByAdd = (id) => {
  return new Promise(() => {
    dropdownService
      .specialGridTreeByAdd({ districtId: id })
      .then(async (res) => {
        if (res.code == 0) {
          let newData = [];
          newData.push(res.data);
          pageBasicsData.addTreeData = newData;
        }
      });
  });
};

// 导入网格
const importSubmit = (file) => {
  regionalGridManageService.batchAdd(file).then((res) => {
    if (res.code == 0) {
      $message.success(res.data);
      pageBasicsData.isImportDialog = false;
      fetchData();
    } else {
      $message.error(res.err);
    }
  });
};
// 选择负责人
const goSelectPrincipal = (val) => {
  if (val == 1) {
    if (!addForm.districtId) {
      $message.warning("清选择所属站点后再进行选择!");
      return;
    }
  } else {
    if (!editForm.districtId) {
      $message.warning("清选择所属站点后再进行选择!");
      return;
    }
  }
  pageBasicsData.showSelectPrincipal = true;
};
// 获取负责人下拉
const fetchPrinciPalList = (id) => {
  const { districtId } = pageBasicsData.screenForm;
  return new Promise(() => {
    dropdownService
      .principalList({ districtId: (id ||= districtId) })
      .then(async (res) => {
        if (res.code == 0) {
          pageBasicsData.princiPalList = res.data;
        }
      });
  });
};
// 关闭负责人弹窗
const closePrincipalDialog = (val) => {
  if (val?.length > 0) {
    let list = [];
    val.forEach((item) => {
      list.push({
        id: item.id,
        name: item.name,
        mobile: item.mobile,
      });
    });
    editForm.userIds = list;
    pageBasicsData.functionaryList = list;
  }
  pageBasicsData.showSelectPrincipal = false;
};

//查询
const restSearch = () => {
  pageProps.page = 1;
  delete pageBasicsData.screenForm.gridId;
  fetchData();
  fetchTree();
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  pageBasicsData.screenForm.districtId = pageBasicsData.districtList[0].id;
  pageBasicsData.screenForm.gridId = "";
  gridCascaderValue.value = '';
  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: "RegionalGridManage",
};
</script>
<style lang="scss" scoped>
.regional-grid {
  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: 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>
