<template>
  <BasicModal v-bind="$attrs" title="选择发行编号（原材料检验标准）" :width="960" @register="registerModal" @ok="handleOk">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import type { FormSchema } from '/@/components/Table';
  import { list as mixerPsList, queryById as queryMixerPsById } from '../../mesXslMixerPsCompile/MesXslMixerPsCompile.api';
  import { columns as mixerPsColumns } from '../../mesXslMixerPsCompile/MesXslMixerPsCompile.data';
  import { useMessage } from '/@/hooks/web/useMessage';

  const emit = defineEmits(['register', 'select']);
  const { createMessage } = useMessage();

  /** 密炼PS类型：原材料检验标准 */
  const PS_TYPE_RAW_INSPECT_STD = 'raw_inspect_std';

  const selectSearchSchema: FormSchema[] = [
    { label: 'PS编码', field: 'psCode', component: 'JInput', colProps: { span: 8 } },
    { label: '标题', field: 'title', component: 'JInput', colProps: { span: 8 } },
  ];

  const selectedRow = ref<Recordable | null>(null);

  const [registerTable, { reload, getSelectRowKeys, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys }] = useTable({
    api: mixerPsList,
    columns: mixerPsColumns.slice(0, 7),
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      labelWidth: 90,
      schemas: selectSearchSchema,
    },
    pagination: { pageSize: 10 },
    canResize: false,
    showIndexColumn: false,
    immediate: true,
    beforeFetch: (params) => ({
      ...params,
      psType: PS_TYPE_RAW_INSPECT_STD,
    }),
    rowSelection: {
      type: 'radio',
      columnWidth: 48,
      onChange: (_keys, rows) => {
        selectedRow.value = rows?.[0] ?? null;
      },
    },
    clickToRowSelect: true,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    selectedRow.value = null;
    clearSelectedRowKeys?.();
    setModalProps({ confirmLoading: false });
    const psId = data?.psCompileId as string | undefined;
    if (psId) {
      setSelectedRowKeys?.([psId]);
      try {
        const raw = await queryMixerPsById({ id: psId });
        const row = (raw as Recordable)?.psCode != null ? raw : (raw as Recordable)?.result;
        if (row) {
          selectedRow.value = row;
        }
      } catch {
        // ignore
      }
    }
    reload();
  });

  async function handleOk() {
    const keys = (getSelectRowKeys?.() || []) as string[];
    let row = selectedRow.value || ((getSelectRows?.() || []) as Recordable[])[0];
    if (!row && keys.length) {
      try {
        const raw = await queryMixerPsById({ id: keys[0] });
        row = (raw as Recordable)?.psCode != null ? raw : (raw as Recordable)?.result;
      } catch {
        // ignore
      }
    }
    if (!row?.id) {
      createMessage.warning('请选择一条密炼PS');
      return;
    }
    if (row.psType && row.psType !== PS_TYPE_RAW_INSPECT_STD) {
      createMessage.warning('仅可选择类型为原材料检验标准的密炼PS');
      return;
    }
    emit('select', {
      psCompileId: row.id,
      issueNumber: row.psCode || '',
      issueDate: row.issueDate || undefined,
      issueDeptId: row.sendDeptId || undefined,
      issueDeptName: row.sendDeptId_dictText || undefined,
    });
    closeModal();
  }
</script>
