<!-- 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 #emptyText> 暂无数据 </template>
          <template #action="{ record }">
            <button @click="handleEdit(record, 'goaf')" class="action-btn" title="编辑">
              <SvgIcon name="edit" />
            </button>
            <button @click="handleEdit(record, 'goaf-limit')" class="action-btn" title="详细参数">
              <SvgIcon name="data" />
            </button>
            <!-- <button @click="handleAdd({ goafId: record.id, mineCode: last(expandedRowKeys) }, '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" title="删除">
                <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" title="编辑">
          <SvgIcon name="edit" />
        </button>
        <button @click="handleEdit(record, 'coal-limit')" class="action-btn" title="详细参数">
          <SvgIcon name="data" />
        </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" title="删除">
            <SvgIcon name="delete" />
          </button>
        </a-popconfirm>
      </template>
    </BasicTable>
  </Flex>
  <BasicModal width="60%" @register="registerModal" @ok="handleSubmit" title="预警参数设置">
    <BasicForm v-if="modalSign === 'coal'" @register="registerCoalForm">
      <template #relation="{ model, field }">
        <RelationBuilder class="h-full" v-model="model[field]" />
      </template>
    </BasicForm>
    <BasicForm v-else-if="modalSign === 'coal-limit'" @register="registerCoalLimitForm">
      <template #InputRangeGoaf="{ model, field, schema }">
        <a-form-item v-if="model[field]">
          <a-input-group>
            <a-input-number v-model:value="model[field][`lowerLimit`]" 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][`upperLimit`]" style="width: calc(50% - 100px); border-left: 0" placeholder="-" />
          </a-input-group>
        </a-form-item>
      </template>
    </BasicForm>
    <BasicForm v-else-if="modalSign === 'goaf'" @register="registerGoafForm"> </BasicForm>
    <BasicForm v-else-if="modalSign === 'goaf-limit'" @register="registerGoafLimitForm">
      <template #InputRangeGoaf="{ model, field, schema }">
        <a-form-item v-if="model[field]">
          <a-input-group>
            <a-input-number v-model:value="model[field][`lowerLimit`]" 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][`upperLimit`]" style="width: calc(50% - 100px); border-left: 0" placeholder="-" />
          </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,
    schemasCoalExpression,
    schemasGoafLimit,
    searchFormSchema,
    // limitationModel,
    schemasGoafInfo,
  } from './algorithm.data';
  import {
    // addCoalSeamAlarmRule,
    deleteCoalSeamAlarmRule,
    deleteGoafDataLimit,
    getCoalSeam,
    getGoafList,
    // updateCoalSeamAlarmRule,
    getCoalSeamAlarmRule,
    // getGoafDataLimit,
    // patchGoafDataLimit,
    patchCoalSeamAlarmRule,
    patchCoalLimit,
    patchGoafLimit,
    updateGoaf,
    // fetchGoafLimit,
    fetchCoalLimit,
  } from './algorithm.api';
  import { Flex } from 'ant-design-vue';
  // import { PlusOutlined } from '@ant-design/icons-vue';
  import { last, isString } from 'lodash-es';
  import { message } from 'ant-design-vue';
  import { SvgIcon } from '/@/components/Icon';
  import RelationBuilder from './components/RelationBuilder.vue';

  type ModalSign = 'coal' | 'coal-limit' | 'goaf' | 'goaf-limit';

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

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

  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    tableProps: {
      immediate: false,
      api: getCoalSeam,
      columns: columnsCoalAlarm,
      rowKey: 'id',
      showIndexColumn: true,
      formConfig: {
        autoSearch: true,
        // 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' },
    },
    immediate: false,
    beforeFetch(p) {
      p.coalSeamId = expandedRowKeys.value[0];
    },
  });

  const [registerCoalForm, coalFormContext] = useForm({
    model: {},
    schemas: schemasCoalExpression,
    showResetButton: false,
    showSubmitButton: false,
    colon: false,
    compact: true,
  });
  const [registerCoalLimitForm, coalLimitContext] = useForm({
    model: {},
    schemas: schemasGoafLimit,
    showResetButton: false,
    showSubmitButton: false,
    colon: false,
    compact: true,
  });
  const [registerGoafForm, goafFormContext] = useForm({
    model: {},
    schemas: schemasGoafInfo,
    showResetButton: false,
    showSubmitButton: false,
    colon: false,
    compact: true,
  });
  const [registerGoafLimitForm, goafLimitContext] = useForm({
    model: {},
    schemas: schemasGoafLimit,
    showResetButton: false,
    showSubmitButton: false,
    colon: false,
    compact: true,
  });

  const modalSign = ref<ModalSign>('coal');

  const editionPropsMap = new Map([
    [
      'coal',
      {
        submitFunc: (record) => coalFormContext.validate().then((res) => patchCoalSeamAlarmRule(Object.assign(record, res))),
        fieldFunc: (params) => getCoalSeamAlarmRule(params).then((r) => coalFormContext.setFieldsValue(last(r))),
      },
    ],
    [
      'coal-limit',
      {
        submitFunc: (record) => coalLimitContext.validate().then((res) => patchCoalLimit(Object.assign(record, res))),
        fieldFunc: (params) => fetchCoalLimit(params.id, last(expandedRowKeys.value)).then((r) => coalLimitContext.setFieldsValue(r)),
      },
    ],
    [
      'goaf',
      {
        submitFunc: (record) => goafFormContext.validate().then((res) => updateGoaf(Object.assign(record, res))),
        fieldFunc: (params) => goafFormContext.setFieldsValue(params),
      },
    ],
    [
      'goaf-limit',
      {
        submitFunc: (record) => goafLimitContext.validate().then((res) => patchGoafLimit(Object.assign(record, res))),
        fieldFunc: (params) => fetchCoalLimit(params.id, last(expandedRowKeys.value)).then((r) => goafLimitContext.setFieldsValue(r)),
      },
    ],
  ]);

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

  const modalPropsMap = new Map<ModalSign, Partial<ModalProps>>([
    ['coal', { title: '预警参数设置', loading: true, visible: true, height: 600 }],
    ['coal-limit', { title: '预警参数设置', loading: true, visible: true, height: 300 }],
    ['goaf', { title: '超限预警设置', loading: true, visible: true, height: 300 }],
    ['goaf-limit', { title: '超限预警设置', loading: true, visible: true, height: 300 }],
  ]);

  const submitResolver = ref<() => Promise<unknown>>();

  // 点击编辑后，获取对应的表单和弹窗配置
  async function handleEdit(record, sign: ModalSign) {
    modalSign.value = sign;
    setModalProps(modalPropsMap.get(sign) as ModalProps);
    const { fieldFunc, submitFunc } = editionPropsMap.get(sign)!;
    submitResolver.value = () => submitFunc(record);

    await nextTick();
    await fieldFunc(record);

    setModalProps({ loading: false });
  }
  // async function handleAdd(record, sign: string) {
  //   if (!modalPropsMap.has(sign)) return;
  //   if (!editionPropsMap.has(sign)) return;
  //   setModalProps(modalPropsMap.get(sign) as ModalProps);
  //   const { schemas, submitFunc } = editionPropsMap.get(sign)!;
  //   await nextTick();
  //   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 });
  // }

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

  const [registerModal, { setModalProps }] = useModal();

  function handleSubmit() {
    if (submitResolver.value) {
      submitResolver
        .value()
        .then(() => {
          message.success('操作成功');
          setModalProps({ visible: false });
        })
        .catch((e) => {
          message.error(isString(e) ? e : '操作失败');
        });
    }
  }
</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>
