<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="userName">
          <div class="screen-item">
            <el-select
              filterable
              clearable
              placeholder="请选择人员名称"
              v-model="pageBasicsData.screenForm.userName"
              @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="mobile">
          <div class="screen-item">
            <el-input
              placeholder="请输入手机号码"
              clearable
              v-model="pageBasicsData.screenForm.mobile"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="角色类型" prop="appRole">
          <div class="screen-item">
            <el-select
              filterable
              placeholder="请选择角色类型"
              v-model="pageBasicsData.screenForm.appRole"
            >
              <el-option
                v-for="item in selectItems['appRole']"
                :key="item.key"
                :label="item.value"
                :value="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
                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="1"
          :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"
        @rowButtonClick="rowButtonClick"
        @fetchTableAttr="fetchTableAttr"
        showOverflowTooltip
        :tableButtons="[
          { cnName: '导出', enName: 'export', theme: 'primary', icon: 'top' },
          { cnName: '生成人效报表', enName: 'createEfficiencyStatement', theme: 'success', icon: 'pointer' },
        ]"
        @buttonClick="buttonClick"
      />
    </div>
    <!-- 表格 end-->
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { personEfficiencyCenterService } from "@/ApiService/personEfficiencyCenterService";
import { dropdownService } from "@/ApiService/dropdownService";
import topNumberEfficiencyCom from "@/Components/personEfficiencyCenter/topNumberEfficiencyCom.vue";
//页面基础数据
const pageBasicsData = reactive({
  districtList: [], // 所属站点下拉列表
  personSelectList: [], // 派单and接单人员列表
  loading: true, // 页面加载状态
  tableHeight: 200, //表格高度
  screenForm: {
    // 顶部搜索字段
    timeArr: [],
    districtId: "",
    userName: "",
    mobile: "",
    appRole: "",
    status: "",
  },
});
// 当前行数据
const currentRow = reactive({});
// 任务统计数据
const efficiencyData = ref({});
// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const screenFormRef = ref(); //搜索区ref
// 生命周期
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("暂无站点信息,请配置站点!");
    }
  });
});
//#region watch定义start
// 设置表格高度
watch(
  () => topSearchRef.value,
  (val) => {
    let wHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    nextTick(() => {
      pageBasicsData.tableHeight = wHeight - val.clientHeight - 200;
    });
  }
);
// 站点变化清空其它查询条件
watch(
  () => pageBasicsData.screenForm.districtId,
  (val) => {
    if (val) {
      for (const key in pageBasicsData.screenForm) {
        if (key !== "districtId" && key !== "timeArr") {
          pageBasicsData.screenForm[key] = "";
        }
      }
    }
    fetchTaskPerson(val);
  }
);
//#endregion watch定义end

//#region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  // 导出
  if (enName == "export") {
    setDateFormat();
    const { page, rows } = pageProps;
    personEfficiencyCenterService.userEfficiencyExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
  // 生成人效报表
  if (enName == "createEfficiencyStatement") {
    $messageBox
      .confirm("确定要生成人效报表吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
      .then((res) => {
        return new Promise(() => {
          setDateFormat();
          personEfficiencyCenterService
            .setUserEfficiencyReport({
              ...pageBasicsData.screenForm,
            })
            .then(async (res) => {
              if (res.code == 0) {
                $message.success(res.data);
              } else {
                $message.error(res.err);
              }
            });
        });
      })
      .catch(() => {});
  }
};
// 查询列表
const restSearch = () => {
  pageProps.page = 1;
  nextTick(() => {
    fetchData();
    fetchEfficiencyStatistics();
  });
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  fetchData();
  fetchEfficiencyStatistics();
};
// 获取表格数据
const fetchData = () => {
  setDateFormat();
  const { page, rows } = pageProps;
  return new Promise(() => {
    personEfficiencyCenterService
      .userEfficiencyPageList({
        page,
        rows,
        ...pageBasicsData.screenForm,
      })
      .then((res) => {
        if (res.code == 0) {
          pageBasicsData.loading = false;
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        }
      });
  });
};
// 获取任务统计
const fetchEfficiencyStatistics = () => {
  const { page, rows } = pageProps;
  return new Promise(() => {
    personEfficiencyCenterService
      .taskEfficiencyStatistics({
        page,
        rows,
        ...pageBasicsData.screenForm,
        type: 1,
      })
      .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 fetchTaskPerson = (id) => {
  return new Promise(() => {
    dropdownService.principalList({ districtId: id }).then(async (res) => {
      pageBasicsData.personSelectList = res.data;
    });
  });
};
// 设置查询日期
const setDateFormat = () => {
  let dateArr = pageBasicsData.screenForm.timeArr;
  pageBasicsData.screenForm.createTimeStart = dateArr[0];
  pageBasicsData.screenForm.createTimeEnd = dateArr[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 fetchTableAttr = (tableAttr) => {
  tableHeader.value = tableAttr;
};
// 表格按钮
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow[i] = row[i];
  }
  buttonsClickFun.data[$column.enName]();
};
const {
  tableData,
  pageProps,
  tableHeader,
  buttonsClickFun,
  $message,
  $messageBox,
  $common,
  selectItems,
} = templateHooks(fetchData);
//#endregion 函数定义 end
</script>
<script>
export default {
  name: "PersonStatistics",
};
</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>
