<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <Flex class="algorithm-model h-full">
    <!-- <EnfMineTree class="flex-grow-1" @select="onTreeSelect" /> -->
    <!--引用表格-->
    <BasicTable class="flex-grow-1" :expandedRowKeys="expandedRowKeys" :ellipsis="true" @register="registerTable">
      <!-- <template #formTitle>
        <a-button type="primary" @click="handleEdit({}, 'coal')">
          <PlusOutlined />
          新增
        </a-button>
        矿区CODE级联选择器占位符
      </template> -->
      <template #expandedRowRender>
        <BasicTable @register="registerInnerTable">
          <template #action="{ record }">
            <button @click="handleEdit({ goafId: record.id }, 'goaf')" class="action-btn">
              <SvgIcon name="edit" />
            </button>
            <button @click="handleAdd({ goafId: record.id }, 'goaf')" class="action-btn ml-1">
              <PlusOutlined />
            </button>
            <a-popconfirm title="确认删除？" @confirm="handleDelete(record, 'coal')">
              <button @click="handleDelete(record, 'goaf')" class="action-btn ml-1">
                <SvgIcon name="delete" />
              </button>
            </a-popconfirm>
          </template>
        </BasicTable>
      </template>

      <template #action="{ record }">
        <button @click="handleEdit({ coalSeamId: record.id, mineCode: record.mineCode }, 'coal')" class="action-btn">
          <SvgIcon name="edit" />
        </button>
        <button @click="handleAdd({ coalSeamId: record.id, mineCode: record.mineCode }, 'coal')" class="action-btn ml-1">
          <PlusOutlined />
        </button>
        <a-popconfirm title="确认删除？" @confirm="handleDelete(record, 'coal')">
          <button class="action-btn ml-1">
            <SvgIcon name="delete" />
          </button>
        </a-popconfirm>
      </template>
    </BasicTable>
  </Flex>
  <BasicModal width="60%" :height="600" @register="registerModal" @ok="handleSubmit" title="预警参数设置">
    <BasicForm @register="registerForm">
      <template #InputRangeNumber="{ model, field, schema }">
        <a-form-item>
          <a-input-group>
            <a-input-number v-model:value="model[`${field}Start`]" style="width: calc(50% - 100px)" placeholder="-" />
            <a-input style="width: 200px; border-left: 0; pointer-events: none; color: inherit" :value="schema.groupName" disabled />
            <a-input-number v-model:value="model[`${field}End`]" style="width: calc(50% - 100px); border-left: 0" placeholder="-" />
          </a-input-group>
        </a-form-item>
      </template>
      <template #InputGreaterNumber="{ model, field, schema }">
        <a-form-item>
          <a-input-group>
            <a-input-number style="width: calc(50% - 100px)" placeholder="-" disabled />
            <a-input style="width: 200px; border-left: 0; pointer-events: none; color: inherit" :value="schema.groupName" disabled />
            <a-input-number v-model:value="model[field]" style="width: calc(50% - 100px); border-left: 0" placeholder="-" />
          </a-input-group>
        </a-form-item>
      </template>
      <template #InputLowerNumber="{ model, field, schema }">
        <a-form-item>
          <a-input-group>
            <a-input-number v-model:value="model[field]" style="width: calc(50% - 100px)" placeholder="-" />
            <a-input style="width: 200px; border-left: 0; pointer-events: none; color: inherit" :value="schema.groupName" disabled />
            <a-input-number style="width: calc(50% - 100px); border-left: 0" placeholder="-" disabled />
          </a-input-group>
        </a-form-item>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { nextTick, provide, ref } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  // import EnfMineTree from './components/EnfMineTree.vue';
  import { useModal, BasicModal, ModalProps } from '/@/components/Modal';
  import { useForm, BasicForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columnsCoalAlarm, columnsGoafLimit, schemasCoalAlarm, schemasGoafLimit, searchFormSchema } from './algorithm.data';
  import {
    addCoalSeamAlarmRule,
    deleteCoalSeamAlarmRule,
    deleteGoafDataLimit,
    getCoalSeam,
    getGoafList,
    updateGoafDataLimit,
    addGoafDataLimit,
    updateCoalSeamAlarmRule,
    getCoalSeamAlarmRule,
    getGoafDataLimit,
  } from './algorithm.api';
  import { Flex } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { last } from 'lodash-es';

  import { SvgIcon } from '/@/components/Icon';

  const { prefixCls } = useDesign('algorithm-list');
  provide('prefixCls', prefixCls);

  // 为了更好的控制展开逻辑
  const expandedRowKeys = ref<string[]>([]);

  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    tableProps: {
      api: getCoalSeam,
      columns: columnsCoalAlarm,
      rowKey: 'id',
      showIndexColumn: true,
      formConfig: {
        showResetButton: false,
        schemas: searchFormSchema,
        schemaGroupNames: ['常规查询'],
      },
      onExpand(expanded, record) {
        // 展开最多一行
        if (expanded) {
          expandedRowKeys.value = [record.id];
          nextTick(reloadInner);
        } else {
          expandedRowKeys.value = [];
        }
      },
    },
  });
  //注册table数据
  const [registerTable] = tableContext;
  const [registerInnerTable, { reload: reloadInner }] = useTable({
    api: getGoafList,
    columns: columnsGoafLimit,
    rowKey: 'id',
    pagination: false,
    showActionColumn: true,
    actionColumn: {
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    beforeFetch(p) {
      p.coalSeamId = expandedRowKeys.value[0];
    },
  });

  const formPropsMap = new Map([
    [
      'coal',
      {
        schemas: schemasCoalAlarm,
        submitFunc: (res) => (res.id ? updateCoalSeamAlarmRule(res) : addCoalSeamAlarmRule(res)),
        fetchRecord: (params) => getCoalSeamAlarmRule(params).then((r) => last(r)),
      },
    ],
    [
      'goaf',
      {
        schemas: schemasGoafLimit,
        submitFunc: (res) => (res.id ? updateGoafDataLimit(res) : addGoafDataLimit(res)),
        fetchRecord: (params) => getGoafDataLimit(params).then((r) => last(r)),
      },
    ],
  ]);
  const modalPropsMap = new Map<string, Partial<ModalProps>>([
    ['coal', { title: '预警参数设置', visible: true, loading: true }],
    ['goaf', { title: '超限预警设置', visible: true, loading: true }],
  ]);
  const submitResolver = ref<(res: any) => Promise<void>>();
  // 点击编辑后，获取对应的表单和弹窗配置
  async function handleEdit(record, sign: string) {
    if (!modalPropsMap.has(sign)) return;
    if (!formPropsMap.has(sign)) return;
    setModalProps(modalPropsMap.get(sign) as ModalProps);
    const { schemas, fetchRecord, submitFunc } = formPropsMap.get(sign)!;
    const res = await fetchRecord(record);
    await resetSchema(schemas);

    await nextTick();

    await setFieldsValue(res);

    await nextTick();

    // 不要使用setFormProps因为它会错误的触发submit方法
    // await setFormProps({ submitFunc });
    submitResolver.value = (res) => submitFunc(Object.assign(res, record));

    setModalProps({ loading: false });
  }
  async function handleAdd(record, sign: string) {
    if (!modalPropsMap.has(sign)) return;
    if (!formPropsMap.has(sign)) return;
    setModalProps(modalPropsMap.get(sign) as ModalProps);
    const { schemas, submitFunc } = formPropsMap.get(sign)!;
    await resetSchema(schemas);

    await nextTick();

    await resetFields();

    await nextTick();

    // 不要使用setFormProps因为它会错误的触发submit方法
    // await setFormProps({ submitFunc });
    submitResolver.value = (res) => submitFunc(Object.assign(res, record));

    setModalProps({ loading: false });
  }

  const deletionPropsMap = new Map<string, { api: (id: string) => Promise<void> }>([
    ['coal', { api: (id) => deleteCoalSeamAlarmRule({ id }) }],
    ['goaf', { api: (id) => deleteGoafDataLimit({ id }) }],
  ]);

  function handleDelete(record, sign: string) {
    if (!deletionPropsMap.has(sign)) return;
    deletionPropsMap.get(sign)?.api(record.id);
  }

  const [registerModal, { setModalProps }] = useModal();
  const [registerForm, { resetFields, setFieldsValue, validate, resetSchema }] = useForm({
    model: {},
    schemas: schemasCoalAlarm,
    showResetButton: false,
    showSubmitButton: false,
    colon: false,
    compact: true,
  });

  function handleSubmit() {
    return validate().then((res) => {
      submitResolver.value && submitResolver.value(res);
    });
  }
</script>

<style lang="less">
  @import './index.less';

  .ant-input-group {
    display: flex;
    text-align: center;
    .ant-input-number {
      min-width: 100px;
      &:first-child {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      &:last-child {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
  }
</style>
