<template>
  <!-- 骨架屏 -->
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" />
  <!-- 任务人效统计 -->
  <div class="task-box" v-if="!pageBasicsData.loading">
    <div ref="topSearchRef">
      <!-- 搜索区域 start-->
      <qu-search-area :model="pageBasicsData.screenForm" @search="restSearch" @reset="clearScreen">
        <el-form-item prop="timeArr" label="查询日期">
          <qu-time-select v-model.date="pageBasicsData.screenForm.timeArr" />
        </el-form-item>
        <el-form-item label="所属站点" prop="districtId">
          <div class="screen-item">
            <el-select
              filterable
              placeholder="请选择"
              v-model="pageBasicsData.screenForm.districtId"
            >
              <el-option
                v-for="item in pageBasicsData.districtList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="任务派单号" prop="no">
          <div class="screen-item">
            <el-input
              placeholder="请输入任务派单号"
              clearable
              v-model="pageBasicsData.screenForm.no"
            ></el-input>
          </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="taskScene">
          <div class="screen-item">
            <el-cascader
              ref="taskSceneRef"
              collapse-tags
              :show-all-levels="false"
              clearable
              v-model="pageBasicsData.screenForm.taskScene"
              :options="pageBasicsData.taskSceneList"
              :props="pageBasicsData.areaGridSelectProps"
              @change="taskSceneHandleChange"
              @focus="
                () => {
                  if (pageBasicsData.taskSceneList.length <= 0) {
                    $message.warning(
                      '当前选择的所属站点暂无任务位置,请重新选择!'
                    );
                  }
                }
              "
            >
              <template #default="{ data }">
                <span>{{ data.name }}</span>
              </template>
            </el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <div class="screen-item">
            <el-select
              filterable
              clearable
              placeholder="请选择任务类型"
              v-model="pageBasicsData.screenForm.taskType"
            >
              <el-option
                v-for="item in selectItems['taskType']"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="派发方式" prop="manualAllocation">
          <div class="screen-item">
            <el-select
              filterable
              clearable
              placeholder="请选择派发方式"
              v-model="pageBasicsData.screenForm.manualAllocation"
            >
              <el-option
                v-for="item in selectItems['manualAllocation']"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="接单人员" prop="taskAcceptUser">
          <div class="screen-item">
            <el-select
              filterable
              clearable
              placeholder="请选择接单人员"
              v-model="pageBasicsData.screenForm.taskAcceptUser"
              @focus="
                () => {
                  if (pageBasicsData.personSelectList?.length <= 0) {
                    $message.warning('当前选择的所属站点暂无任务接单人员!');
                  }
                }
              "
            >
              <el-option
                v-for="item in pageBasicsData.personSelectList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></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
                v-for="item in selectItems['status']"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
      </qu-search-area>
      <!-- 搜索区域 end-->

      <!-- 任务统计区域 start-->
      <div v-if="Object.keys(efficiencyData).length">
        <topNumberEfficiencyCom
          :statisticsType="0"
          :efficiencyData="efficiencyData"
        />
      </div>
      <!-- 任务统计区域 end-->
    </div>

    <!-- 表格 start-->
    <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"
        showOverflowTooltip
        :tableButtons="[{ cnName: '导出', enName: 'export', theme: 'primary', icon: 'top' }]"
        @buttonClick="buttonClick"
      />
    </div>
    <!-- 表格 end-->
  </div>
  <!-- 查看任务详情 start-->
  <div v-if="showLookDialog">
    <el-dialog v-model="showLookDialog" title="任务详情" fullscreen>
      <purifierTaskDetailCom
        v-model:showLookDialog="showLookDialog"
        :taskDetailData="taskDetailData"
        :taskType="currentRow.taskType"
        v-if="currentRow.taskType <= 4"
      />
      <patrolTaskDetail :detail="taskDetailData" v-else />
      <template #footer v-if="currentRow.taskType == 5">
        <el-button
          style="width: 90px; margin-right: 48%"
          type="warning"
          round
          @click="showLookDialog = false"
          >取消</el-button
        >
      </template>
    </el-dialog>
  </div>
  <!-- 查看任务详情 end-->
</template>
<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { personEfficiencyCenterService } from "@/ApiService/personEfficiencyCenterService";
import {
  purifierTaskService,
  userReportTaskService,
  patrolTaskService,
} from "@/ApiService/taskCenterService";
import { dropdownService } from "@/ApiService/dropdownService";
import topNumberEfficiencyCom from "@/Components/personEfficiencyCenter/topNumberEfficiencyCom.vue";
import purifierTaskDetailCom from "@/Components/taskCenter/purifierTaskDetailCom.vue";
import patrolTaskDetail from "@/Components/taskCenter/patrolTask/patrolTaskDetail.vue";
//页面基础数据
const pageBasicsData = reactive({
  districtList: [], // 所属站点下拉列表
  taskSceneList: [], // 任务场景下拉列表
  personSelectList: [], // 派单and接单人员列表
  loading: true, // 页面加载状态
  tableHeight: 200, //表格高度
  screenForm: {
    // 顶部搜索字段
    timeArr: [],
    districtId: "",
    no: "",
    name: "",
    taskScene: [],
    taskType: "",
    manualAllocation: "",
    taskAcceptUser: "",
    status: [],
  },
  areaGridSelectProps: {
    value: "gridId",
    label: "name",
    children: "childNode",
    checkStrictly: true,
    multiple: true,
  },
});
// 当前行数据
const currentRow = reactive({});
// 任务详情
const taskDetailData = ref({});
// 查看任务弹窗
const showLookDialog = ref(false);
// 任务统计数据
const efficiencyData = ref({});
// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const screenFormRef = ref(); //搜索区ref
const taskSceneRef = ref(); // 任务场景ref

//#region watch定义start
// 设置表格高度
watch(
  () => topSearchRef.value,
  (val) => {
    let wHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    nextTick(() => {
      pageBasicsData.tableHeight = wHeight - val.clientHeight - 240;
    });
  }
);
// 站点变化清空其它查询条件
watch(
  () => pageBasicsData.screenForm.districtId,
  (val) => {
    if (val) {
      for (const key in pageBasicsData.screenForm) {
        if (key !== "districtId" && key !== "timeArr") {
          pageBasicsData.screenForm[key] = "";
        }
      }
    }
    // 获取任务位置
    fetchTaskScene(val);
    // 获取人员
    fetchTaskPerson(val);
  }
);
//#endregion watch定义end
// 生命周期
onMounted(() => {
  //获取站点数据
  fetchDistricts().then((res) => {
    if (res.code == 0 && res.data.length) {
      pageBasicsData.districtList = res.data;
      pageBasicsData.screenForm.districtId = pageBasicsData.districtList[0].id;
      //设置默认查询时间
      setDefaultCancelDialog();
      // 获取列表数据
      fetchData();
      // 获取任务统计
      fetchEfficiencyStatistics();
    } else {
      $message.error("暂无站点信息,请配置站点!");
    }
  });
  // 顶部按钮
  buttonsClickFun.data = {
    // 查看
    taskDetail: () => {
      lookTask();
    },
  };
});
//#region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  // 导出
  if (enName == "export") {
    setDateFormat();
    personEfficiencyCenterService.taskEfficiencyExport({
      ...pageBasicsData.screenForm,
    });
  }
};
// 任务场景级联事件
const taskSceneHandleChange = () => {
  let checkArr = taskSceneRef.value.getCheckedNodes();
  let gridAndScenes = [];
  checkArr.forEach((item) => {
    gridAndScenes.push({
      gridId: item.data.gridId,
      id: item.data.id,
      isscene: item.data.isscene,
      level: item.data.level,
      sceneId: item.data.sceneId,
    });
  });
  pageBasicsData.screenForm.gridAndScenes = gridAndScenes;
};
// 获取表格数据
const fetchData = () => {
  setDateFormat();
  const { page, rows } = pageProps;
  return new Promise(() => {
    personEfficiencyCenterService
      .taskEfficiencyPageList({
        page,
        rows,
        ...pageBasicsData.screenForm,
      })
      .then((res) => {
        if (res.code == 0) {
          pageBasicsData.loading = false;
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        }
      });
  });
};
// 查询列表
const restSearch = () => {
  pageProps.page = 1;
  nextTick(() => {
    fetchData();
    fetchEfficiencyStatistics();
  });
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  pageBasicsData.screenForm.districtId = pageBasicsData.districtList[0].id;
  delete pageBasicsData.screenForm.gridAndScenes;
  setDefaultCancelDialog();
  fetchData();
  fetchEfficiencyStatistics();
};
// 设置查询日期字段
const setDateFormat = () => {
  pageBasicsData.screenForm.createTimeStart =
    pageBasicsData.screenForm.timeArr[0];
  pageBasicsData.screenForm.createTimeEnd =
    pageBasicsData.screenForm.timeArr[1];
};
// 默认时间设置
const setDefaultCancelDialog = () => {
  const start = new Date(new Date().toLocaleDateString());
  const end = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  pageBasicsData.screenForm.timeArr = [
    $common.fomatDateTime(start),
    $common.fomatDateTime(end),
  ];
};
// 查看任务
const lookTask = () => {
  let requestMethods = "";
  if (currentRow.taskType <= 2) {
    requestMethods = purifierTaskService.look;
  } else if (currentRow.taskType <= 4) {
    requestMethods = userReportTaskService.look;
  } else {
    requestMethods = patrolTaskService.look;
  }
  return new Promise(() => {
    requestMethods({ id: currentRow.id }).then(async (res) => {
      if (res.code == 0) {
        taskDetailData.value = res.data;
        showLookDialog.value = true;
      }
    });
  });
};
// 获取任务场景
const fetchTaskScene = (id) => {
  return new Promise(() => {
    dropdownService.gridSceneTree({ districtId: id }).then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.taskSceneList = res.data.childNode;
      }
    });
  });
};
// 获取任务人员
const fetchTaskPerson = (id) => {
  return new Promise(() => {
    dropdownService.principalList({ districtId: id }).then(async (res) => {
      pageBasicsData.personSelectList = res.data;
    });
  });
};
// 获取任务统计
const fetchEfficiencyStatistics = () => {
  const { page, rows } = pageProps;
  return new Promise(() => {
    personEfficiencyCenterService
      .taskEfficiencyStatistics({
        page,
        rows,
        ...pageBasicsData.screenForm,
        type: 0,
      })
      .then(async (res) => {
        if (res.code == 0) {
          efficiencyData.value = res.data;
        }
      });
  });
};
// 获取所属站点
const fetchDistricts = () => {
  return new Promise((resolve) => {
    dropdownService.getDistrict().then(async (res) => {
      resolve(res);
    });
  });
};
// 自定义表格头
const fetchTableAttr = (tableAttr) => {
  tableHeader.value = tableAttr;
};
// 表格按钮
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow[i] = row[i];
  }
  buttonsClickFun.data[$column.enName]();
};
const {
  tableData,
  rowButtons,
  pageProps,
  tableHeader,
  pageChange,
  buttonsClickFun,
  $message,
  $messageBox,
  $common,
  selectItems,
} = templateHooks(fetchData);
//#endregion 函数定义 end
</script>
<script>
export default {
  name: "TaskStatistics",
};
</script>
<style lang="scss" scoped>
.task-box {
  box-sizing: border-box;
  height: calc(100vh - 146px);
  flex: 1;
  padding: 10px;
  background-color: #fff;
  .search-area {
    padding: 10px 0 10px 10px;
    display: flex;
    align-items: center;
  }
}
</style>
