<template>
  <div class="guns-layout">
    <div class="guns-layout-content" style="padding: 0">
      <div class="fill-header">
        <a-space :size="16">
          <a-button class="border-radius" @click="back" :loading="loading">返回</a-button>
          <template v-for="item in operationList" :key="item.key">
            <a-space class="op-item" @click="operationClick(item)" v-if="item.key != 'upload'">
              <icon-font :icon-class="item.icon" fontSize="20px" color="var(--primary-color)" />
              <span>{{ item.name }}</span>
            </a-space>
            <a-upload name="file" :customRequest="customRequest" :showUploadList="false" v-else>
              <a-space class="op-item">
                <icon-font :icon-class="item.icon" fontSize="20px" color="var(--primary-color)" />
                <span style="font-size: 16px;">{{ item.name }}</span>
              </a-space>
            </a-upload>
            <a-divider type="vertical" class="divider" />
          </template>
        </a-space>
        <a-space :size="16">
          <a-button type="primary" class="border-radius" :loading="loading" @click="save()">提交</a-button>
          <!-- <a-button class="border-radius" :loading="loading" @click="addItem" v-if="currentType == 'add'">新增</a-button> -->
          <a-button class="border-radius" :loading="loading" @click="save('add')">提交并新增</a-button>
        </a-space>
      </div>
      <div class="fill-name">
        {{ currentBusinessName }}
      </div>
      <div class="fill-bottom">
        <div class="fill-bottom-content">
          <a-spin :spinning="loading" :delay="100">
            <template v-for="(item, index) in formDataList" :key="index">
              <MoreFormViewer
                v-show="pageNo == index + 1"
                v-model:form="item.formDetail"
                :isEdit="isEdit"
                :formDesignConfigList="formDesignConfigList"
                ref="moreFormViewerRef"
              />
            </template>
          </a-spin>
        </div>
      </div>
      <div class="fill-page" v-if="false">
        <a-pagination
          :current="pageNo"
          :page-size="pageSize"
          :total="total"
          v-if="total > 0"
          class="pagination"
          @change="pageSizeChange"
          :show-total="total => `共${total}条`"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineAsyncComponent } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { PreviewApi } from '../../preview/api/PreviewApi';
import { message } from 'ant-design-vue';

const MoreFormViewer = defineAsyncComponent(() => import('../../../form/preview/more-form-viewer.vue'));

const route = useRoute();
const router = useRouter();

const currentBusinessId = ref('');

const currentBusinessName = ref('');

const currentType = ref('add');

const operationList = ref([
  {
    key: 'download',
    name: '下载模板',
    icon: 'icon-fill-xiazaimoban'
  },
  {
    key: 'upload',
    name: '批量上传',
    icon: 'icon-fill-piliangshangchuan'
  },
  {
    key: 'clear',
    name: '清除当前',
    icon: 'icon-fill-qingchudangqian'
  },
  {
    key: 'delete',
    name: '删除当前',
    icon: 'icon-fill-shanchudangqian'
  },
  {
    key: 'deleteAll',
    name: '删除所有',
    icon: 'icon-fill-shanchusuoyou'
  },
  {
    key: 'reload',
    name: '加载上次记录',
    icon: 'icon-fill-jiazaishangcijilu'
  }
]);

const loading = ref(false);

const tableConfig = ref({});

const formDataList = ref([]);

const isEdit = ref(false);

const formDesignConfigList = ref([]);

const pageNo = ref(1);

const pageSize = ref(1);

const total = ref(0);

const moreFormViewerRef = ref();

const backUrling = ref('');

onMounted(() => {
  const { businessId, type, backUrl } = route.query;
  if (backUrl) backUrling.value = decodeURIComponent(backUrl);
  if (!(businessId && type)) return back();
  currentBusinessId.value = businessId;
  currentType.value = type;
  getTableConfig();
});

const back = () => {
  if (backUrling.value) {
    router.push({
      path: backUrling.value,
      query: {
        businessId: currentBusinessId.value
      }
    });
  } else {
    router.push('/mid/fill/data');
  }
};

// 获取表格业务配置
const getTableConfig = () => {
  loading.value = true;
  PreviewApi.getConfig({ businessId: currentBusinessId.value })
    .then(res => {
      if (res.data) {
        currentBusinessName.value = res.data.businessName;
        tableConfig.value = res.data;
        if (res.data?.formDesignConfigList) {
          formDesignConfigList.value = JSON.parse(JSON.stringify(res.data.formDesignConfigList));
        }
        addItem();
      }
    })
    .finally(() => (loading.value = false));
};

const addItem = () => {
  loading.value = true;
  let obj = {
    formDetail: {}
  };
  // 设置表单的值
  formDesignConfigList.value.forEach(item => {
    obj.formDetail[item.formDefinitionId] = {};
  });
  formDataList.value.push(obj);
  pageNo.value = formDataList.value?.length;
  total.value = formDataList.value?.length;
  loading.value = false;
};

// 切换分页
const pageSizeChange = (page, pageSize) => {
  pageNo.value = page;
};

// 校验是否必填
const validate = () => {
  return new Promise(resolve => {
    let arr = [];
    moreFormViewerRef.value.forEach((key, index) => {
      arr.push(key.validate());
    });

    Promise.all(arr)
      .then(result => {
        if (result.indexOf(false) >= 0) {
          resolve(false);
        } else {
          resolve(true);
        }
      })
      .catch(e => {
        message.warning(e.errorFields[0].errors[0]);
        resolve(false);
      });
  });
};

const save = (flag = '') => {
  if (formDataList.value.length == 0) return message.warning('填报信息不能为空');
  validate().then(res => {
    if (!res) return;
    loading.value = true;
    let params = {
      businessId: currentBusinessId.value,
      formDetail: formDataList.value[0].formDetail
    };
    PreviewApi.save(params)
      .then(result => {
        message.success(result.message);
        if (flag == 'add') {
          formDataList.value = [];
          total.value = 0;
          pageNo.value = 1;
          addItem();
        } else {
          back();
        }
      })
      .finally(() => (loading.value = false));
  });
};

// 操作点击
const operationClick = item => {
  switch (item.key) {
    case 'download':
      downloadFile();
      break;
    case 'upload':
      break;
    case 'clear':
      clear();
      break;
    case 'delete':
      remove();
      break;
    case 'deleteAll':
      removeAll();
      break;
    case 'reload':
      getLastLog();
      break;
  }
};

const downloadFile = async () => {
  return;
  await FillDataApi.downloadExcelTemplate({ businessId: currentBusinessId.value });
};

const clear = () => {
  let obj = {
    formDetail: {}
  };
  // 设置表单的值
  formDesignConfigList.value.forEach(item => {
    obj.formDetail[item.formDefinitionId] = {};
  });
  formDataList.value[pageNo.value - 1] = obj;
};

const remove = () => {
  formDataList.value.splice(pageNo.value - 1, 1);
  total.value = formDataList.value?.length;
  if (formDataList.value?.length == 0 || formDataList.value?.length == 1) {
    pageNo.value = 1;
  } else if (formDataList.value[pageNo.value]) {
  } else {
    pageNo.value = pageNo.value - 1;
  }

  if (formDataList.value.length == 0) {
    addItem();
  }
};

const removeAll = () => {
  formDataList.value = [];
  total.value = 0;
  pageNo.value = 1;
  addItem();
};

// 加载上次记录
const getLastLog = () => {
  return;
  loading.value = true;
  FillDataApi.getUserLastFiling({ businessId: currentBusinessId.value })
    .then(res => {
      clear();
      if (res.data.formDetail) {
        formDataList.value[pageNo.value - 1].formDetail = res.data.formDetail;
      }
    })
    .finally(() => (loading.value = false));
};

// 上传Excel
const customRequest = options => {
  return;
  loading.value = true;
  let params = new FormData();
  params.append('businessId', currentBusinessId.value);
  params.append('file', options.file);
  FillDataApi.uploadAndPreviewData(params)
    .then(res => {
      if (res.code == '00000') {
        message.success(res.message);
        if (res.data?.length > 0) {
          formDataList.value = res.data.map(item => {
            return { formDetail: item };
          });
          pageNo.value = 1;
          total.value = formDataList.value.length;
        }
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>

<style scoped lang="less">
.fill-header {
  display: flex;
  height: 70px;
  padding: 12px 16px;
  align-items: center;
  color: #60666b;
  font-size: 16px;
  justify-content: space-between;
  border-bottom: 1.5px solid rgba(197, 207, 209, 0.4);

  .op-item {
    cursor: pointer;
    color: var(--primary-color);
  }

  .divider {
    width: 1.2px;
    height: 16px;
    background: #c5cfd1;
  }
}
.fill-name {
  margin: 16px auto;
  color: #1b2c45;
  text-align: center;
  font-size: 18px;
  height: 30px;
}
.fill-bottom {
  width: 100%;
  height: calc(100% - 122px);
  margin-bottom: 16px;
  overflow: auto;

  .fill-bottom-content {
    margin: 0 auto;
    height: 100%;
    width: 800px;

    :deep(.more-form-box) {
      overflow: unset !important;
    }
  }
}
.fill-page {
  height: 50px;
  padding: 0 32px;
  text-align: right;
}
</style>
