<template>
  <n-modal v-model:show="modalVisible" preset="card" :title="title" style="width: 70%">
    <n-form ref="formRef" label-placement="left" :label-width="80" :model="formModel" :rules="rules">
      <n-grid :cols="48" :x-gap="18">
        <n-form-item-grid-item :span="25" label="指标名称" path="name">
          <n-input v-model:value="formModel.name" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="25" label="分类ID" path="category_id">
          <n-input-number v-model:value="formModel.category_id" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="25" label="是否展示" path="is_show">
          <n-select v-model:value="formModel.is_show" :options="IndicatorsOptions" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="25" label="指标描述" path="description">
          <n-input v-model:value="formModel.description" type="textarea" placeholder="请输入指标描述" />
        </n-form-item-grid-item>
      </n-grid>
      <n-space style="display: flex; flex-direction: column">
        <n-button type="primary" @click="addEventIndicators">添加指标事件</n-button>
        <n-data-table :columns="columns" :data="tableData" />
      </n-space>
      <n-space class="w-full pt-16px" :size="24" justify="end">
        <n-button class="w-72px" @click="closeModal">取消</n-button>
        <n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
      </n-space>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, h } from 'vue';
import type { FormInst, FormItemRule, DataTableColumns } from 'naive-ui';
import { NButton, NTag, NInput, NInputNumber, NSelect } from 'naive-ui';
import {
  EditSelectBoxDataSource,
  EditSelectBoxIsShow,
  EditSelectBoxTriggerOperation,
  IndicatorsOptions,
  EditSelectBoxStartTime
} from '@/constants';
import { createRequiredFormRule } from '@/utils';
import { basicEventList, fetchIndicatorsAdd, fetchIndicatorsEdit } from '@/service/api/event';

export interface Props {
  /** 弹窗可见性 */
  visible: boolean;
  /**
   * 弹窗类型
   * add: 新增
   * edit: 编辑
   */
  type?: 'add' | 'edit';
  /** 编辑的表格行数据 */
  editData?: BackgroundIndicators.Indicators | null;
}

export type ModalType = NonNullable<Props['type']>;

defineOptions({ name: 'TableActionModal' });

const props = withDefaults(defineProps<Props>(), {
  type: 'add',
  editData: null
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const emit = defineEmits<Emits>();

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});

const titles: Record<ModalType, string> = {
  add: '添加指标',
  edit: '编辑指标'
};

const title = computed(() => {
  return titles[props.type];
});

const formRef = ref<HTMLElement & FormInst>();

type FormModel = Pick<
  ApiBackground.Indicators,
  'id' | 'name' | 'category_id' | 'particle_size' | 'is_show' | 'description' | 'event_indicators'
>;

const formModel = reactive<FormModel>(createDefaultFormModel());

const rules: Record<keyof FormModel, FormItemRule | FormItemRule[]> = {
  name: createRequiredFormRule('请输入指标字段名'),
  particle_size: createRequiredFormRule('请选择指标颗粒度'),
  category_id: createRequiredFormRule('请选择分类id'),
  description: createRequiredFormRule('请输入字段描述'),
  is_show: createRequiredFormRule(),
  id: createRequiredFormRule(),
  event_indicators: createRequiredFormRule()
};

const createData = (): RowIndicators.Data[] => [
  {
    event_id: 0,
    event_name: '',
    trigger_operation: 1,
    is_cumulative: 1,
    impact_mode: 1,
    impact_value: 0,
    start_time: 1
  }
];
const tableData = ref(createData());

const selectBoxData: IndicatorsSelectBox.Data = {
  cowEventData: [],
  triggerOperation: EditSelectBoxTriggerOperation,
  isCumulative: EditSelectBoxIsShow,
  impactMode: EditSelectBoxDataSource,
  impactValue: 0,
  eventId: 0,
  eventName: '',
  startTime: EditSelectBoxStartTime
};

function setIndicatorsEventData(data: ApiBackground.BasicCowField[] | null) {
  selectBoxData.cowEventData = data;
}

function getIndicatorsEventData() {
  const data = basicEventList();
  data.then(res => {
    setIndicatorsEventData(res.data);
  });
}

const createColumns = (): DataTableColumns<RowIndicators.Data> => [
  {
    title: '序号',
    key: 'orderNum',
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(
        NTag,
        {
          style: {
            marginRight: '6px',
            background: 'none',
            color: 'rgb(31, 34, 37)'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => index + 1
        }
      );
    }
  },
  {
    title: '事件名称',
    key: 'EventName',
    maxWidth: 300,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(NSelect, {
        options: selectBoxData.cowEventData,
        value: tableData.value[index].event_name,
        onUpdateValue(value: string) {
          tableData.value[index].event_name = value;
        }
      });
    }
  },
  {
    title: '触发操作',
    key: 'triggerOperation',
    maxWidth: 100,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(NSelect, {
        options: selectBoxData.triggerOperation,
        value: tableData.value[index].trigger_operation,
        onUpdateValue(value: number) {
          tableData.value[index].trigger_operation = value;
        }
      });
    }
  },
  {
    title: '累加上期',
    key: 'cumulative',
    maxWidth: 200,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(NSelect, {
        options: selectBoxData.isCumulative,
        value: tableData.value[index].is_cumulative,
        onUpdateValue(value: number) {
          tableData.value[index].is_cumulative = value;
        }
      });
    }
  },
  {
    title: '变更方法',
    key: 'impactMode',
    maxWidth: 200,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(NSelect, {
        options: selectBoxData.impactMode,
        value: tableData.value[index].impact_mode,
        onUpdateValue(value: number) {
          tableData.value[index].impact_mode = value;
        }
      });
    }
  },
  {
    title: '变更值',
    key: 'impactValue',
    maxWidth: 100,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(NInputNumber, {
        value: tableData.value[index].impact_value,
        showButton: false,
        keyboard: {
          ArrowDown: false,
          ArrowUp: false
        },
        onUpdateValue(value) {
          tableData.value[index].impact_value = value;
        }
      });
    }
  },
  {
    title: '开始时间',
    key: 'startTime',
    maxWidth: 200,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return h(NSelect, {
        options: selectBoxData.startTime,
        value: tableData.value[index].start_time,
        onUpdateValue(value: number) {
          tableData.value[index].start_time = value;
        }
      });
    }
  },
  {
    title: '操作',
    key: 'actions',
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    render(row, index) {
      return [
        h(
          NButton,
          {
            // 可在里面写按钮样式
            text: true,
            style: { marginRight: '10px', color: 'red' },
            onClick: () => deleteData(index) // 点击按钮后的回调
          },
          { default: () => '删除' } // 按钮显示名称
        )
      ];
    }
  }
];

const columns = ref(createColumns());

function addEventIndicators() {
  tableData.value.push(createData()[0]);
}
function deleteData(indexKey: number) {
  tableData.value.splice(indexKey, 1);
}

function createDefaultFormModel(): FormModel {
  return {
    id: 0,
    name: '',
    particle_size: null,
    category_id: null,
    is_show: null,
    description: '',
    event_indicators: null
  };
}

function handleUpdateFormModel(model: Partial<FormModel>) {
  Object.assign(formModel, model);
}

function handleUpdateFormModelByModalType() {
  const handlers: Record<ModalType, () => void> = {
    add: () => {
      const defaultFormModel = createDefaultFormModel();
      handleUpdateFormModel(defaultFormModel);
    },
    edit: () => {
      if (props.editData) {
        handleUpdateFormModel(props.editData);
        if (props.editData.event_indicators) {
          tableData.value = props.editData.event_indicators;
        }
      }
    }
  };

  handlers[props.type]();
}

const closeModal = () => {
  tableData.value = [];
  modalVisible.value = false;
};

getIndicatorsEventData();

async function handleSubmit() {
  formRef.value?.validate();
  formModel.event_indicators = tableData.value;
  if (props.type === 'add') {
    const data = fetchIndicatorsAdd(formModel);
    data.then(res => {
      if (res.data) {
        window.$message?.success(`${titles[props.type]}成功！`);
      }
    });
  }

  if (props.type === 'edit') {
    const data = fetchIndicatorsEdit(formModel);
    data.then(res => {
      if (res.data) {
        window.$message?.success(`${titles[props.type]}成功！`);
      }
    });
  }
  closeModal();
}

watch(
  () => props.visible,
  newValue => {
    if (newValue) {
      handleUpdateFormModelByModalType();
    }
  }
);
</script>

<style scoped></style>
