<template>
  <div>
    <!-- 应用数据表格 -->
    <div>
      <BasicTable @register="register">
        <template #toolbar>
          <a-button type="primary" @click="openApplyModals">新增</a-button>
        </template>
        <template #action="{ record, column }">
          <TableAction :actions="createActions(record, column)"/>
        </template>
      </BasicTable>

      <ApplyModal @register="registerApplyModal" @visible-change="ApplyModalVisibleChange"/>
    </div>

    <!-- 应用事件抽屉 -->
    <BasicDrawer @register="registerEventDrawer" title="应用事件" width="90%">
      <div>
        <BasicTable @register="registerEvent">
          <template #toolbar>
            <a-button type="primary" @click="openEventModals">新增</a-button>
          </template>
          <template #action="{ record, column }">
            <TableAction :actions="createActionsEvent(record, column)"/>
          </template>
        </BasicTable>

        <EventModal @register="registerEventModal" @visible-change="EventModalVisibleChange"/>
      </div>
    </BasicDrawer>

    <!-- 事件详情抽屉 -->
    <BasicDrawer @register="registerEventInfoDrawer" title="属性详情" width="70%">
      <PageWrapper title="属性详情页" contentBackground>
        <Description
          size="middle"
          title="应用信息"
          :bordered="true"
          :column="3"
          :data="applyData"
          :schema="applySchema"
        />
        <Divider/>
        <Description
          size="middle"
          title="事件信息"
          :bordered="true"
          :column="3"
          :data="eventData"
          :schema="eventSchema"
        />
        <Divider/>
        <BasicTable @register="eventAppendixTable">
          <template #toolbar>
            <BasicUpload
              :maxSize="20"
              :maxNumber="10"
              :api="uploadApi"
              :uploadParams="paramPages"
              @change="handleBasicUploadChange"
              helpText="单个文件不超过10MB，最多只能上传10个文件"
            />
          </template>
          <template #action="{ record, column }">
            <TableAction :actions="createActionsEventAppendix(record, column)"/>
          </template>
        </BasicTable>
      </PageWrapper>
    </BasicDrawer>
  </div>
</template>

<script lang="ts" setup>
import {
  ActionItem,
  BasicColumn,
  BasicTable,
  EditRecordRow,
  useTable,
} from '/@/components/Table';
import {BasicDrawer, useDrawer} from '/@/components/Drawer';
import TableAction from '/@/components/Table/src/components/TableAction.vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {reactive, ref} from 'vue';
import {cloneDeep} from 'lodash-es';
import {
  applyDelete,
  applyUpdate,
  queryAll,
  queryApplyOne,
} from '/@/api/burialPoint/apply/apply';
import {
  queryPage,
  queryEventOne,
  eventUpdate,
  eventDelete,
} from '/@/api/burialPoint/event/event';
import {applySchema, eventSchema} from './model/data';
import {Apply} from '/@/api/burialPoint/apply/model/applyModel';
import {Events} from '/@/api/burialPoint/event/model/eventModel';
import {useModal} from '/@/components/Modal';
import {PageWrapper} from '/@/components/Page';
import {Description} from '/@/components/Description/index';
import {Divider} from 'ant-design-vue';
import ApplyModal from './modal/applyModal.vue';
import EventModal from './modal/eventModal.vue';
import {BasicUpload} from '/@/components/Upload';
import {uploadApi} from '/@/api/sys/upload';
import {
  downloadAppendix,
  eventAppendixDelete,
  queryListByEventId
} from "/@/api/burialPoint/eventAppendix/eventAppendix";
import {downloadByData} from "/@/utils/file/download";

// 应用

const {createMessage: msg} = useMessage();
const currentApplyEditKeyRef = ref('');

/**
 * 注册表格信息
 */
const columns = [
  {
    title: 'UUID',
    dataIndex: 'uuid',
    editRow: false,
    width: 200,
  },
  {
    title: '应用名称',
    dataIndex: 'applyName',
    editRow: true,
    width: 200,
  },
  {
    title: '应用类别',
    dataIndex: 'applyType',
    editRow: true,
    width: 200,
  },
  // {
  //   title: '应用令牌',
  //   dataIndex: 'token',
  //   editRow: true,
  //   width: 200,
  //   editComponent: 'Select',
  // },
];
const [register, methods] = useTable({
  title: '应用表',
  api: queryAll,
  columns: columns,
  rowKey: 'uuid',
  actionColumn: {
    width: 160,
    title: '操作',
    slots: {customRender: 'action'},
  },
  useSearchForm: true,
  formConfig: {
    labelWidth: 100,
    schemas: [
      {
        field: `applyName`,
        label: `应用名称`,
        component: 'Input',
        colProps: {
          xl: 12,
          xxl: 8,
        },
      },
    ],
  },
  canResize: true,
  pagination: false,
  showIndexColumn: false,
});

/**
 * 应用新增的弹窗
 */
const [registerApplyModal, {openModal: openApplyModal, setModalProps: setApplyModalProps}] =
  useModal();

const openApplyModals = () => {
  setApplyModalProps({
    cancelText: '取消',
    okText: '提交',
  });
  openApplyModal();
};

const ApplyModalVisibleChange = (visible) => {
  if (!visible) {
    methods.reload();
  }
};

/**
 * 控制表格行是否编辑
 * @param record
 * @param column
 */
function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
  if (!record.editable) {
    return [
      {
        label: '事件',
        onClick: handleOpenEvent.bind(null, record.uuid),
      },
      {
        label: '编辑',
        disabled: currentApplyEditKeyRef.value
          ? currentApplyEditKeyRef.value !== record.key
          : false,
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否删除应用',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record, column),
    },
    {
      label: '取消',
      popConfirm: {
        title: '是否取消编辑',
        confirm: handleCancel.bind(null, record, column),
      },
    },
  ];
}

/**
 * 开启表格编辑信息
 */
function handleEdit(record: EditRecordRow) {
  currentApplyEditKeyRef.value = record.key;
  record.onEdit?.(true);
}

/**
 * 删除表格信息
 */
function handleDelete(record: Recordable) {
  applyDelete('?id=' + record.uuid).then((res) => {
    if (res) console.log('删除成功');
    methods.reload();
  });
}

/**
 * 取消表格编辑信息
 */
function handleCancel(record: EditRecordRow) {
  currentApplyEditKeyRef.value = '';
  record.onEdit?.(false, false);
}

/**
 * 表格编辑信息保存
 * @param record
 */
async function handleSave(record: EditRecordRow) {
  // 校验
  msg.loading({content: '正在保存...', duration: 0, key: 'saving'});
  const valid = await record.onValid?.();
  if (valid) {
    try {
      const data = cloneDeep(record.editValueRefs);
      //TODO 此处将数据提交给服务器保存
      const params: Apply = {
        uuid: record.uuid,
        applyName: data?.applyName,
        applyType: data?.applyType,
        tokenId: undefined
      };
      await applyUpdate(params).then(async (res) => {
        // 保存之后提交编辑状态
        if (res) console.log('修改成功');
        const pass = await record.onEdit?.(false, true);
        if (pass) currentApplyEditKeyRef.value = '';
        msg.success({content: '数据已保存', key: 'saving'});
      });
    } catch (error) {
      msg.error({content: '保存失败', key: 'saving'});
    }
  } else {
    msg.error({content: '请填写正确的数据', key: 'saving'});
  }
}

// 事件相关

const currentEventEditKeyRef = ref('');
const paramPages = reactive({
  id: '',
  applyId: '',
});

/**
 * 事件抽屉
 */
const [registerEventDrawer, {openDrawer}] = useDrawer();

/**
 * 操作事件抽屉
 * @param record
 */
function handleOpenEvent(uuid: string) {
  // console.log('打开抽屉');
  // 打开抽屉
  openDrawer();

  paramPages.applyId = uuid;

  methodsEvent.reload();
}

/**
 * 注册表格信息
 */
const columnsEvent = [
  // {
  //   title: 'id',
  //   dataIndex: 'id',
  //   editRow: false,
  //   width: 200,
  // },
  {
    title: '事件编号',
    dataIndex: 'eventCode',
    editRow: false,
    width: 200,
  },
  {
    title: '事件名称',
    dataIndex: 'eventName',
    editRow: true,
    width: 200,
  },
  {
    title: '事件类别',
    dataIndex: 'eventType',
    editRow: true,
    width: 200,
  },
  {
    title: '事件描述',
    dataIndex: 'description',
    editRow: true,
    width: 200,
  },
];
const [registerEvent, methodsEvent] = useTable({
  title: '事件表',
  api: queryPage,
  fetchSetting: {
    pageField: 'pageNum',
    listField: 'eventList',
    totalField: 'totalRow',
  },
  beforeFetch: (params) => {
    params.applyId = paramPages.applyId;
  },
  columns: columnsEvent,
  rowKey: 'id',
  actionColumn: {
    width: 160,
    title: '操作',
    slots: {customRender: 'action'},
  },
  useSearchForm: true,
  formConfig: {
    labelWidth: 100,
    schemas: [
      {
        field: `eventName`,
        label: `事件名称`,
        component: 'Input',
        colProps: {
          xl: 12,
          xxl: 8,
        },
      },
      {
        field: `eventType`,
        label: `事件类型`,
        component: 'Input',
        colProps: {
          xl: 12,
          xxl: 8,
        },
      },
    ],
  },
  canResize: true,
  showIndexColumn: false,
});

/**
 * 添加事件的弹窗
 */
const [registerEventModal, {openModal: openEventModal, setModalProps: setEventModalProps}] =
  useModal();

const openEventModals = () => {
  setEventModalProps({
    cancelText: '取消',
    okText: '提交',
  });
  openEventModal(true, paramPages.applyId);
};

const EventModalVisibleChange = (visible) => {
  if (!visible) {
    methodsEvent.reload();
  }
};

/**
 * 控制表格行是否编辑
 * @param record
 * @param column
 */
function createActionsEvent(record: EditRecordRow, column: BasicColumn): ActionItem[] {
  if (!record.editable) {
    return [
      {
        label: '详情',
        onClick: handleOpenEventInfo.bind(null, record),
      },
      {
        label: '编辑',
        disabled: currentEventEditKeyRef.value
          ? currentEventEditKeyRef.value !== record.key
          : false,
        onClick: handleEditEvent.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否删除事件',
          confirm: handleDeleteEvent.bind(null, record),
        },
      },
    ];
  }
  return [
    {
      label: '保存',
      onClick: handleSaveEvent.bind(null, record, column),
    },
    {
      label: '取消',
      popConfirm: {
        title: '是否取消编辑',
        confirm: handleCancelEvent.bind(null, record, column),
      },
    },
  ];
}

/**
 * 开启表格编辑信息
 */
function handleEditEvent(record: EditRecordRow) {
  currentEventEditKeyRef.value = record.key;
  record.onEdit?.(true);
}

/**
 * 删除表格信息
 */
function handleDeleteEvent(record: Recordable) {
  eventDelete(record.id + '&applyId=' + record.applyId).then((res) => {
    if (res) console.log('删除成功');
    methodsEvent.reload();
    console.log('点击了删除', record);
  });
}

/**
 * 取消表格编辑信息
 */
function handleCancelEvent(record: EditRecordRow) {
  currentEventEditKeyRef.value = '';
  record.onEdit?.(false, false);
}

/**
 * 表格编辑信息保存
 * @param record
 */
async function handleSaveEvent(record: EditRecordRow) {
  // 校验
  msg.loading({content: '正在保存...', duration: 0, key: 'saving'});
  const valid = await record.onValid?.();
  if (valid) {
    try {
      const data = cloneDeep(record.editValueRefs);
      //TODO 此处将数据提交给服务器保存
      const params: Events = {
        id: record.id,
        applyId: record.applyId,
        eventName: data?.eventName,
        eventType: data?.eventType,
        description: data?.description,
        createdTime: '',
        eventCode: ''
      };
      // console.log(params);

      await eventUpdate(params).then(async (res) => {
        if (res) console.log('修改成功');
        // 保存之后提交编辑状态
        const pass = await record.onEdit?.(false, true);
        if (pass) {
          currentEventEditKeyRef.value = '';
        }
        msg.success({content: '数据已保存', key: 'saving'});
      });
    } catch (error) {
      msg.error({content: '保存失败', key: 'saving'});
    }
  } else {
    msg.error({content: '请填写正确的数据', key: 'saving'});
  }
}

/**
 * 事件详情抽屉
 */
const [registerEventInfoDrawer, {openDrawer: openDrawerEventInfo}] = useDrawer();

const applyData = ref<Apply>();
const eventData = ref<Events>();

/**
 * 操作属性详情抽屉
 * @param record
 */
async function handleOpenEventInfo(record: Recordable) {
  // console.log('打开抽屉');
  // 打开抽屉
  openDrawerEventInfo();

  paramPages.id = record.id

  await queryApplyOne(record.applyId).then((res: Apply) => {
    applyData.value = res;
  });
  await queryEventOne(record.id + '&applyId=' + record.applyId).then((res: Events) => {
    eventData.value = res;
  });

  await methodsEventAppendix.reload();
}

/**
 * 附件表信息
 */
const columnsEventAppendix = [
  {
    title: '附件名称',
    dataIndex: 'name',
    editRow: false,
    width: 200,
  },
]

/**
 * 附件表格
 */
const [eventAppendixTable, methodsEventAppendix] = useTable({
  title: '事件附件',
  api: queryListByEventId,
  columns: columnsEventAppendix,
  beforeFetch: (params) => {
    params.eventId = paramPages.id;
    console.log(params)
  },
  pagination: false,
  actionColumn: {
    width: 160,
    title: '操作',
    slots: {customRender: 'action'},
  },
  showIndexColumn: false,
});

/**
 * 控制表格行是否编辑
 * @param record
 * @param column
 */
function createActionsEventAppendix(record: EditRecordRow, column: BasicColumn): ActionItem[] {
  return [
    {
      label: '下载',
      onClick: handleOpenEventAppendixInfo.bind(null, record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否删除事件',
        confirm: handleDeleteEventAppendix.bind(null, record),
      },
    },
  ];
}

function handleBasicUploadChange() {
  methodsEventAppendix.reload()
}

/**
 * 附件下载
 */
async function handleOpenEventAppendixInfo(record: EditRecordRow) {
  await downloadAppendix(record.id).then((res) => {
    downloadByData(res, record.name);
  })
}

/**
 * 删除表格信息
 */
function handleDeleteEventAppendix(record: Recordable) {
  eventAppendixDelete(record.id).then((res) => {
    if (res) console.log('删除成功');
    methodsEventAppendix.reload()
    console.log('点击了删除', record);
  });
}


</script>

<style scoped></style>
