<template>
  <div class="flex flex-col h-full">
    <div class="page-action">
      <t-button
        v-if="perm.BUTTON_BatchSubmit"
        theme="primary"
        :disabled="!selectedRowKeys.length"
        @click="multSubmit"
        >批量提交</t-button
      >
      <t-button
        v-if="perm.BUTTON_BatchExport"
        theme="primary"
        @click="multExport"
        >批量导出</t-button
      >
    </div>
    <SearchForm :fields="fields" :params="params" :search="mixinSearch">
      <template #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          :filterParams="{ statusList: ['PUBLISH'] }"
        ></select-service-unit>
      </template>
      <template #supplier="{ item, params }">
        <select-supplier v-model="params[item.prop]"> </select-supplier>
      </template>
      <template #creator="{ item, params }">
        <select-filter-user v-model="params[item.prop]"> </select-filter-user>
      </template>
    </SearchForm>

    <div class="flex-1 page-wrap">
      <p class="page-wrap-tips">
        <t-space :size="0">
          <span>
            <ErrorCircleFilledIcon /> 考勤总计：{{ statisticsInfo.dingCount }}
          </span>
          <span>已提交：{{ statisticsInfo.submitCount }}</span>
          <span>待提交：{{ statisticsInfo.willSubmitCount }}</span>
          <span>累计人天：{{ statisticsInfo.totalActualDays }}天</span>
          <span
            >累计工时：{{ statisticsInfo.totalWorkHours?.toFixed(1) }}小时</span
          >
          <template #separator>
            <t-divider layout="vertical" />
          </template>
        </t-space>
      </p>

      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableList"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #sopNo="{ col, row }">
          <more-content
            :content="row[col.colKey]"
            @action="openDetailDialog(row)"
          ></more-content>
        </template>
        <template #archivesInfo="{ col, row }">
          <more-content
            :content="row[col.colKey]"
            @action="openDetailDialog(row)"
          ></more-content>
        </template>
        <template #role="{ col, row }">
          {{ roleTypeFilter(row[col.colKey]) }}
        </template>
        <template #enter-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #outer-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #submit-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #status="{ col, row }">
          {{ attendanceSubmitStatusFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations" @click.stop>
            <template v-if="perm.LINK_Submit">
              <t-link
                :disabled="
                  row.submitStatus !== 'WILL_SUBMIT' &&
                  row.submitStatus !== 'AGREE_WITHDRAW'
                "
                theme="primary"
                hover="color"
                @click="handleSubmit(row)"
              >
                提交
              </t-link>
            </template>
            <template v-if="perm.LINK_Reject">
              <t-link
                :disabled="row.submitStatus !== 'ALREADY_SUBMIT'"
                theme="primary"
                hover="color"
                @click="handleWithdraw(row)"
              >
                撤回
              </t-link>
              <t-link
                :disabled="row.submitStatus !== 'APPLY_WITHDRAW'"
                theme="primary"
                hover="color"
                @click="handleCancelWithdraw(row)"
              >
                取消撤回
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>
    <detail-dialog
      v-model:visible="showDetailDialog"
      :row="curRow"
    ></detail-dialog>
  </div>
</template>

<script setup name="WorkAttendance">
import { computed, onMounted, reactive, ref } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { ErrorCircleFilledIcon } from 'tdesign-icons-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import {
  workAttendanceListApi,
  workAttendanceInfoApi,
  workAttendanceSubmitApi,
  workAttendanceExportApi,
  workAttendanceWithdrawApi,
  workAttendanceCancelWithdrawApi,
} from '@/api/work-hours';
import {
  timestampFilter,
  attendanceSubmitStatusFilter,
  roleTypeFilter,
} from '@/utils/filter';
import { randomCode } from '@/utils/tool';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();
import DetailDialog from './detail-dialog.vue';

const showDetailDialog = ref(false);
const curRow = ref({});

const selectedRowKeys = ref([]);
const selectedRowDatas = ref([]);
const selectChange = (value, { selectedRowData }) => {
  selectedRowKeys.value = value;
  selectedRowDatas.value = selectedRowData.map((item) => getSelectedData(item));
};
const openDetailDialog = (row) => {
  curRow.value = row;
  showDetailDialog.value = true;
};

function getSelectedData(data) {
  return {
    serviceUnitId: data.serviceUnitId,
    sopNo: data.sopNo,
    userArchivesId: data.archivesId,
  };
}

const fields = ref([
  {
    prop: 'serviceUnitId',
    label: '服务单元',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'dingSubmitStatusDesc',
    label: '提交状态',
    type: 'select',
    labelWidth: 110,
    colSpan: 6,
    options: [
      {
        value: '已提交',
        label: '已提交',
      },
      {
        value: '未提交',
        label: '未提交',
      },
    ],
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'submitUserId',
    label: '提交人',
    type: 'select',
    labelWidth: 110,
    colSpan: 6,
    cell: 'creator',
  },
  {
    prop: 'archivesName',
    label: '姓名',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 3,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
          getStatisticsInfo();
        },
      },
    ],
  },
  {
    prop: 'supplierId',
    label: '所属供应商',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
    cell: 'supplier',
  },
  {
    prop: 'customName',
    label: '客户名称',
    labelWidth: 110,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'sopNo',
    label: 'SOP流水号',
    labelWidth: 110,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'violationHoursLimit',
    type: 'number',
    label: '违规工时',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      theme: 'column',
      decimalPlaces: 0,
      max: 1000000,
      min: 0,
      label: '>',
      style: 'width: 100%',
    },
  },
  {
    prop: 'dingExceptionLimit',
    type: 'number',
    label: '考勤异常数',
    labelWidth: 90,
    colSpan: 6,
    attrs: {
      theme: 'column',
      decimalPlaces: 0,
      max: 1000000,
      min: 0,
      label: '>',
      style: 'width: 100%',
    },
  },
  {
    prop: 'remainLimit',
    type: 'number',
    label: '剩余补卡次数',
    labelWidth: 110,
    colSpan: 6,
    attrs: {
      theme: 'column',
      decimalPlaces: 0,
      max: 1000000,
      min: 0,
      label: '>',
      style: 'width: 100%',
    },
  },
  {
    prop: 'exceptionLimit',
    type: 'number',
    label: '待处理异常数',
    labelWidth: 110,
    colSpan: 6,
    attrs: {
      theme: 'column',
      decimalPlaces: 0,
      max: 1000000,
      min: 0,
      label: '>',
      style: 'width: 100%',
    },
  },
]);
const mixinSearch = () => {
  search();
  getStatisticsInfo();
};
const params = reactive({
  serviceUnitId: '',
  dingSubmitStatusDesc: '',
  submitUserId: '',
  archivesName: '',
  supplierId: '',
  customName: '',
  sopNo: '',
  violationHoursLimit: null,
  dingExceptionLimit: null,
  remainLimit: null,
  exceptionLimit: null,
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
  },
  { colKey: 'serviceUnitName', title: '服务单元', width: 160 },
  { colKey: 'sopNo', title: 'SOP流水号', width: 200 },
  { colKey: 'customName', title: '客户名称', width: 120 },
  { colKey: 'province', title: '省份', width: 120 },
  { colKey: 'city', title: '城市', width: 120 },
  { colKey: 'approachTime', title: '进场时间', cell: 'enter-time', width: 180 },
  {
    colKey: 'departureTime',
    title: '撤场时间',
    cell: 'outer-time',
    width: 180,
  },
  {
    colKey: 'archivesInfo',
    title: '姓名（人员档案号）',
    width: 260,
  },
  { colKey: 'roleType', title: '项目角色', width: 120, cell: 'role' },
  { colKey: 'supplierName', title: '供应商' },
  { colKey: 'actualDays', title: '实际出勤（天）', width: 140 },
  { colKey: 'weekdays', title: '工作日（天）', width: 130 },
  { colKey: 'weekends', title: '周末（天）', width: 120 },
  { colKey: 'legalHolidays', title: '法定节假日（天）', width: 160 },
  { colKey: 'workHours', title: '累计工时（小时）', width: 140 },
  { colKey: 'violationDays', title: '违规工时（天）', width: 140 },
  { colKey: 'dingExceptionCount', title: '考勤异常数（天）', width: 150 },
  { colKey: 'remainCount', title: '剩余补卡次数', width: 120 },
  { colKey: 'exceptionCount', title: '待处理异常数', width: 120 },
  { colKey: 'submitStatus', title: '提交状态', cell: 'status', width: 120 },
  { colKey: 'submitUserName', title: '提交人', width: 120 },
  {
    colKey: 'submitTime',
    title: '提交时间',
    cell: 'submit-time',
    width: 180,
  },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 180,
  },
];

const { pagination, tableData, fetchData, search, onChange } = useFetchTable(
  workAttendanceListApi,
  {
    fetchDataHandle: () => {
      selectedRowKeys.value = [];
      selectedRowDatas.value = [];
    },
    params,
  }
);

const tableList = computed(() => {
  return tableData.value.map((item) => {
    return { ...item, id: randomCode() };
  });
});

let statisticsInfo = ref({});
const getStatisticsInfo = async () => {
  const res = await workAttendanceInfoApi(params);
  statisticsInfo.value = res || {};
};

const multSubmit = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择要提交的记录');
    return;
  }
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要提交选择的所有记录吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'success',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await workAttendanceSubmitApi(selectedRowDatas.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const multExport = () => {
  // if (!selectedRowKeys.value.length) {
  //   MessagePlugin.error('请选择要导出的记录');
  //   return;
  // }
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要导出查询的所有记录吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'info',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await workAttendanceExportApi(params).catch(() => {});
      if (!res) return;
      MessagePlugin.success('导出任务提交成功，请前往任务管理中下载');
    },
  });
};

const handleSubmit = (row) => {
  const confirmDia = DialogPlugin({
    header: '提交提示',
    body: `该工时数据提交后就可以进行工时统计结算，且该工时数据无法进行任何修改操作，您要继续提交吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'success',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await workAttendanceSubmitApi([getSelectedData(row)]).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
      getStatisticsInfo();
    },
  });
};
const handleWithdraw = (row) => {
  const confirmDia = DialogPlugin({
    header: '撤回提示',
    body: `您确定要撤回这条已提交的工时数据吗？您操作撤回后，还需要工时管理人员同意撤回，这条工时数据才能被真正撤回。`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await workAttendanceWithdrawApi(getSelectedData(row)).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const handleCancelWithdraw = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要取消撤回当前记录吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await workAttendanceCancelWithdrawApi(
        getSelectedData(row)
      ).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};

onMounted(() => {
  getStatisticsInfo();
});
</script>
