<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose @cancel="handleCancel" :centered="true">
    <div style="background-color: #ececec; padding: 10px">
      <a-row :gutter="10">
        <a-col :span="10">
          <a-card :bordered="false">
            <div :style="{ overflow: 'hidden', height: '75vh' }">
              <FileViewer ref="refShowFileCotent" />
            </div>
          </a-card>
        </a-col>
        <a-col :span="7">
          <a-card :bordered="false">
            <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="handleSubmit">保存</a-button>
            </template>
            <div :style="{ overflow: 'hidden', height: '67vh' }">
              <BasicForm @register="registerForm" />
            </div>
          </a-card>
        </a-col>
        <a-col :span="7">
          <div :style="{ overflow: 'hidden', height: '80vh', background: '#fff', padding: '10px' }">
            <blockquote class="info"> 已添加的最佳实践 </blockquote>
            <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="95%"
            >
              <vxe-column type="seq" width="60" />
              <vxe-column field="content" width="30%" title="最佳实践" />
              <vxe-column field="exeRule" 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>
          </div>
        </a-col>
      </a-row>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import FileViewer from '/@/components/onlinePreview/FileViewer.vue';

  import { formSchema } from '../data/AuditBestPractice.data';
  import { deleteOne, saveOrUpdate } from '../api/AuditBestPractice.api';

  const refShowFileCotent = ref();
  const oldData = ref({});
  const tableData = ref([]);

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

  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = 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);
    if (isUpdate.value && data.record['actIds']) {
      let actIds = data.record['actIds'].split(',').map(Number);
      let caNams = data.record['caName'].split(',');
      data.record['actIds'] = [caNams, actIds];
    }

    await resetFields();
    if (isUpdate.value) {
      await setFieldsValue({
        ...data.row,
      });
    }

    setProps({ disabled: data?.isDetail });
  });

  const title = computed(() => (!unref(isUpdate) ? '新建行业实践' : unref(isDetail) ? '查看行业实践' : '修改行业实践'));

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      values['fileId'] = refShowFileCotent.value.getFileId();
      setModalProps({ confirmLoading: true });
      //提交表单
      const retData = await saveOrUpdate(values, isUpdate.value);
      await resetFields();
      handleSuccess();
      if (isUpdate.value) {
        emit('success', isUpdate.value, values);
        closeModal();
      } else {
        tableData.value.unshift(retData);
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleCancel() {
    emit('success', isUpdate.value);
    closeModal();
  }
  function handleSuccess() {}
  async function handleDelete(record) {
    tableData.value = tableData.value.filter((item) => item.id !== record.id);
    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,
    });
  };
  function onEdit() {
    isDetail.value = false;
    setProps({ disabled: isDetail.value });
  }
</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>
