<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    :title="title"
    @cancel="handleCancel"
    :centered="true"
    :useWrapper="true"
    :footer="null"
  >
    <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" :loading="loading" contentFullHeight="true" style="height: 100%; overflow-y: auto">
              <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 && !saveStatus" type="link" @click="handleSubmit(1)">保存并关闭</a-button>
                <a-button v-show="!isDetail && !saveStatus" type="link" @click="handleSubmit(2)">保存</a-button>
                <a-button v-show="!isDetail && saveStatus" type="link" @click="addNext()">继续添加</a-button>
              </template>
              <BasicForm @register="registerForm" />
            </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"
              :loading="loading"
              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" />
                <vxe-column field="pbItem" width="40%" title="项目" />
                <vxe-column field="pbExample" 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 { ref, computed, unref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { columns, formSchema } from '../data/AuditProblem.data';
  import { list, deleteOne, saveOrUpdate } from '../api/AuditProblem.api';
  import ShowFileCotent from './ShowFileContent.vue';

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

  const tableData = ref([]);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    //labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  //表单赋值
  const fileId = ref();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = data?.isDetail;
    tableData.value = [];

    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, defaultFullscreen: true });

    if (!isUpdate.value) {
      tableData.value = data.allData;
    } else {
      if (data.allData) {
        if (data.record.fileId) {
          tableData.value = data.allData.filter((item) => item.fileId == data.record.fileId);
        } else {
          tableData.value = data.allData;
        }
      }
    }

    fileId.value = data.docFile?.fileId || data.docFile?.id;
    refShowFileCotent.value.setDocFile(data?.docFile);

    const newData = JSON.parse(JSON.stringify(data.record));
    if (isUpdate.value && newData['actIds']) {
      let actIds = newData['actIds'].split(',').map(Number);
      let caNams = newData['caName'].split(',');
      newData['actIds'] = [caNams, actIds];
    }
    await setFieldsValue({
      ...newData,
    });
    setProps({ disabled: data?.isDetail });
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : unref(isDetail) ? '查看' : '修改'));
  //表单提交事件
  async function handleSubmit(flag) {
    try {
      let values = await validate();
      values['fileId'] = refShowFileCotent.value.getFileId();
      setModalProps({ confirmLoading: true });
      //提交表单
      let newData = await saveOrUpdate(values, isUpdate.value);

      if (isUpdate.value) {
        emit('success', isUpdate.value, values);
      } else {
        tableData.value.unshift(newData);
      }

      saveStatus.value = true;
      if (flag == 1) {
        saveStatus.value = false;
        await resetFields();
        closeModal();
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleCancel() {
    emit('success', isUpdate.value);
    closeModal();
  }
  function handleSuccess() {
    reload();
  }
  function onEdit() {
    isDetail.value = false;
    setProps({ disabled: isDetail.value });
  }
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  const curSelRowIndex = ref();
  const currentChangeEvent = async ({ rowIndex }) => {
    curSelRowIndex.value = rowIndex;
    const row = JSON.parse(JSON.stringify(tableData.value[rowIndex]));
    if (!row['labels'] || !row['labelNames']) {
      await resetFields();
    }
    await setFieldsValue({
      ...row,
    });
  };

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

  async function addNext() {
    isUpdate.value = false;
    saveStatus.value = false;
    await resetFields();
  }
</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;
  }
</style>
