<template>
  <!-- 骨架屏 -->
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" animated />
  <!-- 人员人效统计 -->
  <div class="task-box" v-if="!pageBasicsData.loading">
    <div ref="topSearchRef">
      <!-- 顶部功能按钮 start-->
      <qu-button-group
        :buttonList="[
          { cnName: '导出', enName: 'export', theme: 'primary', icon: 'top' },
          {
            cnName: '积分设置',
            enName: 'setIntegral',
            theme: 'success',
            icon: 'setting',
          },
        ]"
        @buttonClick="buttonClick"
      />
      <!-- 顶部功能按钮 end-->

      <!-- 搜索区域 start-->
      <div class="search-area">
        <el-form
          ref="screenFormRef"
          :model="pageBasicsData.screenForm"
          inline
          size="small"
        >
          <el-form-item label="人员名称" prop="userName">
            <div class="screen-item">
              <el-select
                filterable
                clearable
                placeholder="请选择人员名称"
                v-model="pageBasicsData.screenForm.userName"
              >
                <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
                clearable
                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>
            <el-button type="primary" icon="Search" round @click="restSearch"
              >查询</el-button
            >
            <el-button round icon="Refresh" type="warning" @click="clearScreen"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- 搜索区域 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="false"
        :showIndex="false"
        showSelect
        :height="pageBasicsData.tableHeight"
        :tableData="tableData"
        :tableHeader="tableHeader"
        @rowButtonClick="rowButtonClick"
        showOverflowTooltip
        @selectionChange="selectionChange"
      />
    </div>
    <!-- 表格 end-->
    <div
      style="
        border-top: 1px solid #dcdfe6;
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <el-button
        type="warning"
        round
        style="margin: 20px 0; width: 80px"
        @click="closeLookDialog"
        >返回</el-button
      >
    </div>
    <!-- 积分设置 start -->
    <div v-if="setPointDialog">
      <el-dialog
        v-model="setPointDialog"
        title="积分设置"
        width="600px"
        @close="setIntegralDialog"
      >
        <el-form label-width="130px" ref="setIntegralRef" :model="setPointForm">
          <el-form-item
            label="核对方式"
            prop="type"
            :rules="{
              required: true,
              message: '请选择核对方式',
              trigger: 'change',
            }"
          >
            <el-select
              style="width: 350px"
              filterable
              clearable
              placeholder="请选择"
              v-model="setPointForm.type"
            >
              <el-option
                v-for="item in [
                  { key: 0, value: '核加' },
                  { key: 1, value: '核减' },
                ]"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="积分"
            prop="point"
            :rules="[
              {
                required: true,
                message: '请输入积分',
                trigger: 'change',
              },
              {
                validator: verifyWageHour,
              },
            ]"
          >
            <el-input
              v-model="setPointForm.point"
              style="width: 350px"
              placeholder=""
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button style="width: 90px" @click="setPointDialog = false"
              >取消</el-button
            >
            <el-button
              style="width: 90px"
              type="primary"
              @click="setIntegralSubmit"
              >提交</el-button
            >
          </span>
        </template>
      </el-dialog>
      <!-- 积分设置 end -->
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { dropdownService } from "@/ApiService/dropdownService";
import { pageService } from "@/ApiService/pageService.js";
import { personEfficiencyCenterService } from "@/ApiService/personEfficiencyCenterService";
import topNumberEfficiencyCom from "@/Components/personEfficiencyCenter/topNumberEfficiencyCom.vue";
const props = defineProps({
  showLookDialog: {
    type: Boolean,
    default: false,
  },
  recordingId: {
    type: [Number, String],
    default: "",
  },
  districtId: {
    type: [Number, String],
  },
  buttonId: {
    type: [Number, String],
  },
  statisticsStartTime: {
    type: [Number, String],
    default: "",
  },
  statisticsEndTime: {
    type: [Number, String],
    default: "",
  },
});
const $emits = defineEmits(["update:showLookDialog"]);
const closeLookDialog = (obj) => {
  $emits("update:showLookDialog", false);
};
const setPointDialog = ref(false);
//页面基础数据
const pageBasicsData = reactive({
  loading: false, // 页面加载状态
  tableHeight: 200, //表格高度
  personSelectList: [],
  screenForm: {
    userName: "",
    mobile: "",
    appRole: "",
    recordingId: props.recordingId,
    type: 1,
  },
});
// 任务统计数据
const efficiencyData = ref({});
// 当前行数据
const currentRow = reactive({});
// 积分设置
const setPointForm = reactive({
  type: "",
  point: "",
  efficiencyDetailIds: [],
});
const tableHeader = ref([]);
const selectItems = ref([]);
// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const screenFormRef = ref(); //搜索区ref
const setIntegralRef = ref(); // 积分设置ref

//#region watch定义start
// 设置表格高度
watch(
  () => topSearchRef.value,
  (val) => {
    let wHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    nextTick(() => {
      pageBasicsData.tableHeight = wHeight - val.clientHeight - 250;
    });
  }
);
//#endregion watch定义end

//#region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "export") {
    const { page, rows } = pageProps;
    personEfficiencyCenterService.efficiencyDetailExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
  if (enName == "setIntegral") {
    if (!setPointForm.efficiencyDetailIds.length) {
      $message.error("请选择需要设置积分的人员后,再进行设置");
      return;
    }
    setPointDialog.value = true;
  }
};

onMounted(() => {
  fetchPeopleListHeader();
  fetchData();
  fetchEfficiencyStatistics();
  fetchTaskPerson();
});
const setIntegralSubmit = () => {
  console.log(setPointForm);
  setIntegralRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          return new Promise(() => {
            personEfficiencyCenterService
              .setEfficiencyDetailPoint({
                ...setPointForm,
              })
              .then(async (res) => {
                if (res.code == 0) {
                  setPointDialog.value = false;
                  fetchData();
                  fetchEfficiencyStatistics();
                  $message.success(res.data);
                  setIntegralDialog();
                } else {
                  $message.error(res.err);
                }
              });
          });
        })
        .catch(() => {});
    }
  });
};
// 表格选中项
const selectionChange = (data) => {
  if (data.length) {
    setPointForm.efficiencyDetailIds = data.map((row) => row.id);
  } else {
    setPointForm.efficiencyDetailIds = [];
  }
};
// 自定义积分校验规则
const verifyWageHour = (rule, value, callback) => {
  if (value) {
    value = value.toString();
    if (isNaN(Number(value))) {
      callback(new Error("积分必须为数字值!"));
    } else if (Number(value) <= 0) {
      callback(new Error("积分不能小于0!"));
    } else if (value.indexOf(".") > 0) {
      let index = value.indexOf(".");
      let str = value.slice(index + 1);
      if (str && str.length > 2) {
        callback(new Error("小数点后只能输入两位!"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } else {
    callback(new Error("请输入积分!"));
  }
};
// 关闭工时设置弹窗
const setIntegralDialog = () => {
  // setIntegralRef.value.resetFields();
  for (const key in setPointForm) {
    if (setPointForm[key] != "efficiencyDetailIds") {
      setPointForm[key] = "";
    }
  }
};
// 查询列表
const restSearch = () => {
  pageProps.page = 1;
  nextTick(() => {
    fetchData();
    fetchEfficiencyStatistics();
  });
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  fetchData();
  fetchEfficiencyStatistics();
};
const fetchPeopleListHeader = () => {
  const { buttonId } = props;
  if (!buttonId) {
    $message.error("缺少按钮ID,获取子页面表格表头字段失败");
    return;
  }
  pageService.queryButtonFieldByButton({ buttonId }).then((res) => {
    if (res.code == 0) {
      tableHeader.value = res.data;
      selectItems.value = $common.selectItems(tableHeader.value);
    } else {
      $message.error(res.err);
    }
  });
};
// 获取任务统计
const fetchEfficiencyStatistics = () => {
  const { page, rows } = pageProps;
  return new Promise(() => {
    personEfficiencyCenterService
      .taskEfficiencyStatistics({
        districtId: props.districtId,
        type: 1,
        createTimeStart: $common.fomatDateTime(props.statisticsStartTime),
        createTimeEnd: $common.fomatDateTime(props.statisticsEndTime),
        ...pageBasicsData.screenForm,
      })
      .then(async (res) => {
        if (res.code == 0) {
          efficiencyData.value = res.data;
        }
      });
  });
};
// 获取任务人员
const fetchTaskPerson = () => {
  return new Promise(() => {
    dropdownService
      .principalList({ districtId: props.districtId })
      .then(async (res) => {
        pageBasicsData.personSelectList = res.data;
      });
  });
};
// 获取表格数据
const fetchData = () => {
  return new Promise(() => {
    personEfficiencyCenterService
      .efficiencyDetailList({
        ...pageBasicsData.screenForm,
      })
      .then((res) => {
        if (res.code == 0) {
          pageBasicsData.loading = false;
          tableData.value = res.data;
          pageProps.records = res.data.records;
        }
      });
  });
};
// 表格按钮
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow[i] = row[i];
  }
  buttonsClickFun.data[$column.enName]();
};
const {
  tableData,
  pageProps,
  pageChange,
  buttonsClickFun,
  $message,
  $messageBox,
  $common,
} = templateHooks(fetchData);
//#endregion 函数定义 end
</script>
<script>
export default {
  name: "statementDetailCom",
};
</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>
