<template>
  <div class="user-manage">
    <div class="main-container">
      <div class="top-screen" ref="topScreenRef">
        <qu-search-area :model="screenForm" @search="restSearch" @reset="clearScreen(screenFormRef, ['districtId'])">
          <el-form-item label="所属站点" prop="districtId">
            <div class="screen-item">
              <district-screen v-model:districtId="screenForm.districtId" ref="districtScreenRef"
                @districtChange="districtChange"></district-screen>
            </div>
          </el-form-item>
          <el-form-item label="班组名称" prop="workGroupName">
            <div class="screen-item">
              <el-input v-model="screenForm.workGroupName" clearable></el-input>
            </div>
          </el-form-item>
        </qu-search-area>
      </div>
      <div class="main-table">
        <el-skeleton :rows="10" v-if="!isLoaded" :throttle="500" />
        <qu-table :tableData="tableData" v-model:tableHeader="tableHeader" :height="tableHeight" :pageProps="pageProps"
          :rowButtons="rowButtons" @rowButtonClick="rowButtonClick" @pageChange="pageChange" @sortChange="sortChange"
          v-loading="tableLoading" v-if="isLoaded" :tableButtons="tableButtons" @buttonClick="buttonClick"></qu-table>
      </div>
      <div v-if="showEditForm">
        <el-dialog :title="currentRow.data.id ? '编辑' : '新建'" v-model="showEditForm" width="30%">
          <team-edit-form-com :currentRow="currentRow" ref="editFormRef" v-model:showEditForm="showEditForm"
            @OK="fetchData"></team-edit-form-com>
        </el-dialog>
      </div>
      <div v-if="showSetPeopleForm">
        <el-dialog title="设置班组人员" v-model="showSetPeopleForm" fullscreen>
          <choose-team-user-form :defaultProps="defaultProps" :currentRow="currentRow"
            v-model:showSetPeopleForm="showSetPeopleForm" @OK="fetchData"></choose-team-user-form>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "teamManage",
};
</script>
<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from "vue";
import templateHooks from "@/Hooks/templateHooks";
import teamEditFormCom from "@/Components/userCenter/teamEditFormCom.vue";
import chooseTeamUserForm from "@/Components/userCenter/chooseTeamUserFormCom.vue";
import { workGroupService } from "@/ApiService/userCenterService.ts";
import { dropdownService } from "@/ApiService/dropdownService.js";
const districtScreenRef = ref();
const isLoaded = ref(false);
const tableLoading = ref(false);
const serviceAreaProps = reactive({
  multiple: true,
  children: "childNode",
  label: "name",
  value: "id",
  emitPath: false,
});
const serviceAreaOptions = ref([]);
const eventData = ref([]);
const showEditForm = ref(false);
const showSetPeopleForm = ref(false);
const editFormRef = ref();
const tableHeight = ref(500);
const showTeamUserList = ref(false);
const defaultProps = computed(() => {
  return {
    teamId: currentRow.data.id,
    buttonId: currentButton.data.buttonId,
  };
});
const topScreenRef = ref();
// 数据定义 end
const buttonClick = (button) => {
  buttonsClickFun.data[button.enName]();
};
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow.data[i] = row[i];
  }
  // let serviceAreas = [];
  // currentRow.data.serviceAreas.map((item) => {
  //   serviceAreas.push(item.gridIdAndLevel);
  // });
  // currentRow.data.serviceAreas = serviceAreas;
  currentButton.data = $column;
  buttonsClickFun.data[$column.enName]();
};
const fetchData = () => {
  if (!screenForm.districtId) {
    isLoaded.value = true;
    tableLoading.value = false;
    return;
  }
  const { page, rows, sord, sidx } = pageProps;
  tableLoading.value = true;
  let serviceAreas = null;

  workGroupService
    .pageList({ page, rows, sord, sidx, ...screenForm, serviceAreas })
    .then(
      (res) => {
        if (res.code == 0) {
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        } else {
          $message.error(res.err);
        }
        isLoaded.value = true;
        tableLoading.value = false;
      },
      () => {
        isLoaded.value = true;
        tableLoading.value = false;
      }
    );
};
const fetchGridTree = () => {
  dropdownService
    .gridTree({ districtId: screenForm.districtId })
    .then((res) => {
      if (res.code == 0) {
        serviceAreaOptions.value = res.data.childNode;
      } else {
        $message.error(res.err);
      }
    });
};
const fetchMatter = () => {
  dropdownService
    .selectMatter({ districtId: screenForm.districtId })
    .then((res) => {
      if (res.code == 0) {
        eventData.value = res.data;
      } else {
        $message.error(res.err);
      }
    });
};

// 监听站点变化
const districtChange = (obj) => {
  screenForm.serviceEvents = "";
  screenForm.serviceAreas = "";
  if (obj) {
    fetchGridTree();
    fetchMatter();
  } else {
    serviceAreaOptions.value = [];
    eventData.value = [];
  }
};

const {
  $route,
  $router,
  $store,
  $common,
  $message,
  $messageBox,
  screenForm,
  screenFormRef,
  selectItems,
  tableData,
  tableHeader,
  tableButtons,
  currentButton,
  rowButtons,
  currentRow,
  pageProps,
  buttonsClickFun,
  pageChange,
  sortChange,
  clearScreen,
  restSearch,
} = templateHooks(fetchData);
// 函数定义 end

onMounted(() => {
  buttonsClickFun.data = {
    add: () => {
      for (let i in currentRow.data) {
        currentRow.data[i] = null;
      }
      showEditForm.value = true;
    },
    export: () => {
      workGroupService.groupExport({ ...screenForm });
    },
    edit: () => {
      showEditForm.value = true;
    },
    delete: () => {
      console.log(currentRow);
      $messageBox
        .confirm("此操作将永久删除该数据，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          workGroupService
            .deleteWorkGroup({ id: currentRow.data.id })
            .then((res) => {
              if (res.code == 0) {
                $message.success("删除成功");
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        });
    },
    setTeamUser: () => {
      console.log(currentRow.data);
      currentRow.data.workMember = [];
      showSetPeopleForm.value = true;
    },
  };
  nextTick(() => {
    districtScreenRef.value.fetchDistricts().then((res) => {
      if (res && res.length != 0) {
        screenForm.districtId = res[0].id;
        fetchGridTree();
        fetchMatter();
      }
      fetchData();
    });
  });
});
watch(tableButtons, (val) => {
  console.log($route.name);
  if ($route.name == "teamManage") {
    if (val && val.length != 0) {
      nextTick(() => {
        const windowHeight = document.body.clientHeight;
        console.log(topScreenRef.value.clientHeight);
        tableHeight.value =
          windowHeight -
          topScreenRef.value.clientHeight -
          170;
      });
    }
  }
});
// 生命周期 end
</script>
