<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :destroyOnClose="true"
    :centered="true"
    :useWrapper="true"
    :footer="null"
    @cancel="handleCancel"
    title="新建或编辑条目"
  >
    <div style="background-color: #ececec; padding: 5px; overflow-y: auto">
      <a-row :gutter="8">
        <a-col :span="!isCollapsedLeft ? 8 : 4">
          <div :style="{ overflow: 'hidden', height: '87vh' }">
            <ShowFileCotent ref="refShowFileCotent" @toggle-collapse="toggleCollapseLeft" />
          </div>
        </a-col>
        <a-col :span="isCollapsed ? (isCollapsedLeft ? 17 : 13) : isCollapsedLeft ? 13 : 9">
          <div :style="{ overflow: 'hidden', height: '87vh' }">
            <a-card :bordered="false" contentFullHeight="true" style="height: 100%; overflow-y: hidden">
              <template #title>
                <p style="font-size: 14px">
                  {{ title }}
                </p>
              </template>
              <template #extra>
                <a-button v-show="isDetail" type="link" @click="onEdit()">编辑</a-button>
                <a-button v-show="!isDetail" type="link" @click="handleSave()" :loading="loading" :disabled="loading">保存</a-button>
                <a-button v-show="!isDetail" type="link" @click="addNext()" :loading="loading" :disabled="loading">保存并继续添加</a-button>
                <a-button v-show="!isDetail" type="link" @click="handleSaveAndClose()" :loading="loading" :disabled="loading">保存并关闭</a-button>
              </template>
              <div style="height: 75vh; overflow-y: auto; margin-top: 5px" :loading="loading">
                <BasicForm @register="registerForm" />
                <a-divider style="height: 2px; background-color: #ececec" />
                <AuditCheckpoint ref="refAuditCheckpoint" :is-update="isUpdate" :is-detail="isDetail" />
              </div>
            </a-card>
          </div>
        </a-col>
        <a-col :span="!isCollapsed ? 7 : 3">
          <div :style="{ overflow: 'hidden', height: '87vh', background: '#fff' }">
            <a-card
              :bordered="false"
              contentFullHeight="true"
              style="height: 100%; overflow-y: hidden"
              :bodyStyle="{ height: '100%', padding: '10px 0px', margin: '0px 10px' }"
            >
              <template #title><span>已添加的条目</span></template>
              <template #extra
                ><a href="#" @click="toggleCollapse">{{ isCollapsed ? '<展开' : '收起>' }}</a></template
              >
              <vxe-table
                :data="tableData"
                ref="tableRef"
                size="small"
                show-overflow
                :show-radio="true"
                :row-config="{ isCurrent: true, isHover: true }"
                @current-change="currentChangeEvent"
                :columnConfig="{ resizable: true }"
                :scroll-y="{ enabled: true, gt: 50 }"
                :radio-config="{ highlight: true }"
                height="90%"
              >
                <vxe-column type="seq" width="60" sortable />
                <vxe-column field="item" width="40%" title="条目" />
                <vxe-column field="content" title="内容" />
                <vxe-column title="操作" width="100" show-overflow>
                  <template #default="{ row }">
                    <vxe-button mode="text" icon="vxe-icon-delete" @click="handleDelete(row)" />
                  </template>
                </vxe-column>
              </vxe-table>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref, nextTick } from 'vue';
  import { VXETable } from 'vxe-table';
  import { formSchema } from '../data/AuditComplianeItem.data';
  import { deleteOne, saveOrUpdate, queryItemCheckMethodByItemId } from '../api/AuditComplianeItem.api';
  import { batchDeleteNoTip } from '../api/AuditCheckMethodItem.api';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import ShowFileCotent from './ShowFileContent.vue';
  import AuditCheckpoint from './AuditCheckpoint.vue';

  const refShowFileCotent = ref();
  const refAuditCheckpoint = ref();
  const oldData = ref({});
  const tableData = ref([]);
  const loading = ref(false);
  const tableRef = ref();
  const checkMethods = ref([]);

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema, removeSchemaByFiled, appendSchemaByField }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const fileId = ref();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    oldData.value = data;
    tableData.value = data?.docFile?.child;
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, defaultFullscreen: true });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = data?.isDetail;
    fileId.value = data.docFile?.fileId || data.docFile?.id;
    refShowFileCotent.value.setDocFile(data?.docFile);

    await resetFields();
    checkMethods.value = [];

    appendSchemaByField(
      {
        field: `cgrp`,
        label: '分组',
        component: 'JTreeSelect',
        componentProps: {
          dict: 'audit_file_content_categories,name,id',
          pidField: 'parent_id',
          hasChildField: 'has_child',
          condition: '{"file_id":"' + fileId.value + '"}',
        },
      },
      ''
    );

    if (isUpdate.value) {
      //data.record["fileId"] =  fileId.value
      await setFieldsValue({
        ...data.record,
      });
      const curItemAry = tableData.value.filter((obj) => obj.id == data.record.id);
      const $table = tableRef.value;
      $table.setCurrentRow(curItemAry[0]);
      await setCheckMethods(data.record.id);
      await refAuditCheckpoint.value.setData(checkMethods.value, isDetail.value);
    } else {
      await refAuditCheckpoint.value.setData(null);
    }

    await refAuditCheckpoint.value.setDetail(isDetail.value);

    setProps({ disabled: isDetail.value });
  });

  const title = computed(() => (!unref(isUpdate) ? '新建合规条目' : unref(isDetail) ? '查看合规条目' : '修改合规条目'));

  async function handleSaveAndClose() {
    await handleSubmit();
    setTimeout(async () => {
      await resetFields();
      loading.value = false;
      handleCancel();
    }, 1000);
  }

  async function handleSave() {
    await handleSubmit();
    setTimeout(async () => {
      loading.value = false;
    }, 500);
  }

  async function addNext() {
    await handleSubmit();
    setTimeout(async () => {
      await resetFields();
      await refAuditCheckpoint.value.setData(null);
      isUpdate.value = false;
    }, 500);
  }

  async function handleSubmit() {
    try {
      let values = await validate();
      loading.value = true;
      setTimeout(async () => {
        values['fileId'] = refShowFileCotent.value.getFileId();
        let checkMethods = await refAuditCheckpoint.value.getData();
        if (checkMethods) {
          values['checkMethods'] = checkMethods;
          await removeFromDb(checkMethods);
        }
        const retData = await saveOrUpdate(values, isUpdate.value);

        await setFieldsValue({
          ...retData,
        });

        if (isUpdate.value) {
          //emit('success', temUpdate, values);
          const selIndex = tableData.value?.findIndex((item) => item.id == retData.id);
          if (selIndex > -1) {
            tableData.value[selIndex]['item'] = retData.item;
            tableData.value[selIndex]['content'] = retData.content;
            tableData.value[selIndex]['id'] = retData.id;
          }
        } else {
          if (!tableData.value) {
            tableData.value = [];
          }
          await tableData.value.unshift(retData);
        }
        isUpdate.value = true;
        VXETable.modal.message({ content: '保存成功', status: 'success' });
        loading.value = false;
      }, 1000);
    } finally {
      setTimeout(async () => {
        loading.value = false;
        setModalProps({ confirmLoading: false });
      }, 5000);
    }
  }

  function handleSuccess() {}

  async function handleDelete(record) {
    const type = await VXETable.modal.confirm('您确定要删除该数据?');
    if (type == 'confirm') {
      tableData.value = tableData.value.filter((item) => item.id !== record.id);
      await deleteOne({ id: record.id }, handleSuccess);
      emit('success', false);
    }
  }

  const currentChangeEvent = async ({ row }) => {
    isUpdate.value = true;
    if (!row['labels'] || !row['labelNames']) {
      await resetFields();
    }
    await setFieldsValue({
      ...row,
    });
    await setCheckMethods(row.id);
    await refAuditCheckpoint.value.setData(checkMethods.value);
  };

  function onEdit() {
    isDetail.value = false;
    refAuditCheckpoint.value.setDetail(isDetail.value);
    setProps({ disabled: isDetail.value });
  }
  async function setCheckMethods(itemid) {
    checkMethods.value = await queryItemCheckMethodByItemId({ fileId: fileId.value, id: itemid });
  }

  const isCollapsed = ref(false);
  const isCollapsedLeft = ref(false);
  function toggleCollapse() {
    isCollapsed.value = !isCollapsed.value;
  }
  function toggleCollapseLeft() {
    isCollapsedLeft.value = !isCollapsedLeft.value;
  }

  function handleCancel() {
    removeSchemaByFiled('cgrp');
    closeModal();
    emit('success', isUpdate.value);
  }

  async function removeFromDb(checkMethods) {
    if (!checkMethods || checkMethods.length === 0) return;
    let idAry: Array<number> = [];
    for (const checkItem of checkMethods) {
      const delAry = checkItem.deleteMethodItems;
      if (delAry && delAry.length > 0) {
        idAry.push(...delAry.map((item) => item.id));
      }
    }
    if (idAry.length > 0) {
      await batchDeleteNoTip({ ids: idAry.join(',') });
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  ::v-deep .file-content table {
    border: 1px solid;
    width: 100%;
  }
  ::v-deep .file-content tr {
    border: 1px solid;
  }
  ::v-deep .file-content td {
    border: 1px solid;
  }
  body {
    overflow: hidden;
  }
  .layout {
    background: #fff;
    height: calc(90vh - 110px);
    margin: 10px 10px 0px 10px;
    overflow: hidden;
  }
  .resizable-sider {
    position: relative;
    background: #f0f2f5;
  }

  .sider-content {
    background-color: #fff;
    padding: 16px;
    height: calc(90vh - 88px);
    overflow-y: auto;
  }

  .resizer {
    position: absolute;
    top: 0;
    right: 0;
    width: 5px;
    height: 100%;
    cursor: ew-resize;
    background-color: #d9d9d9;
  }
  .content {
    background: #fff;
    padding: 24px;
    overflow: auto;
  }
  ::-webkit-scrollbar {
    /* 隐藏滚动条 */
    display: none;
  }
  .floating-button {
    position: fixed;
    top: 60px;
    right: 25px;
    z-index: 1000;
  }

  .ant-modal-content .ant-modal-footer {
    display: none;
  }
</style>
