<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <a-checkbox v-model:checked="groupByMachine" @change="onGroupByMachineChange">按机台统计</a-checkbox>
        <a-button
          style="margin-left: 8px"
          type="primary"
          v-auth="'xslmes:mes_xsl_manual_small_material_demand_plan:exportXls'"
          preIcon="ant-design:export-outlined"
          @click="onExportXls"
        >
          导出
        </a-button>
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="xslmes-mesXslManualSmallMaterialDemandPlan" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import {
    baseColumns,
    machineColumns,
    searchFormSchema,
    superQuerySchema,
  } from './MesXslManualSmallMaterialDemandPlan.data';
  import { list, getExportUrl } from './MesXslManualSmallMaterialDemandPlan.api';

  const queryParam = reactive<any>({ groupByMachine: 0 });
  const groupByMachine = ref(false);

  const { tableContext, onExportXls } = useListPage({
    tableProps: {
      title: '人工小料需求计划',
      api: list,
      columns: baseColumns,
      canResize: true,
      formConfig: {
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam, {
          groupByMachine: groupByMachine.value ? 1 : 0,
        });
      },
    },
    exportConfig: {
      name: '人工小料需求计划',
      url: getExportUrl,
      params: queryParam,
    },
  });

  const [registerTable, { reload, setColumns }] = tableContext;
  const superQueryConfig = reactive(superQuerySchema);

  onMounted(() => {
    applyColumns();
  });

  function applyColumns() {
    setColumns(groupByMachine.value ? machineColumns : baseColumns);
  }

  function onGroupByMachineChange() {
    queryParam.groupByMachine = groupByMachine.value ? 1 : 0;
    applyColumns();
    reload();
  }

  function handleSuperQuery(params) {
    Object.keys(params).forEach((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
</script>
