<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="请求地址">
      <el-input v-model="form.url" />
    </el-form-item>
    <el-form-item label="请求方法">
      <el-select
        v-model="form.method"
      >
        <el-option
          label="get"
          value="get"
        />
        <el-option
          label="post"
          value="post"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="请求参数" v-if="form.method === 'get'">
      <el-input v-model="form.params" placeholder="默认为表单数据(不建议修改)" />
    </el-form-item>
    <el-form-item label="请求参数" v-if="form.method === 'post'">
      <el-input v-model="form.data" placeholder="默认为表单数据(不建议修改)" />
    </el-form-item>
    <el-form-item label="结果储存字段名">
      <el-input v-model="form.fieldName" />
    </el-form-item>

    <el-form-item>
      <template #label>
        <div style="line-height: 32px">
          <el-text>储存数据字段</el-text>
          <el-tooltip placement="top">
            <template #content>
              若下一层使用 [] 获取，则 [] 内的字段请使用'' 或""包裹
            </template>
            <el-icon style="margin-left: 4px">
              <Warning />
            </el-icon>
          </el-tooltip>
        </div>
      </template>
      <el-input v-model="form.keys" placeholder="请仔细核对层级关系" />
    </el-form-item>
    <el-form-item label="结果储存为">
      <el-select
        v-model="form.storageLocation"
      >
        <el-option
          label="页面"
          value="page"
        />
        <el-option
          label="当前方法"
          value="now"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="是否为分页数据">
      <el-switch v-model="form.isTotal" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import request from '@/utils/request';

const form = ref({
  url: '',
  method: 'get',
  params: '',
  data: '',
  fieldName: '',
  storageLocation: 'now',
  keys: '',
  isTotal: true
});

const setParams = (e) => {
  if (e === 'get') {
    return `params: ${form.value.params ? form.value.params : 'formData'} `;
  } else if (e === 'post') {
    return `data: ${form.value.data ? form.value.data : 'formData'} }`;
  } else {
    return ``;
  }
};

const setRes = () => {
  if (form.value.storageLocation === 'page') {
    return `formDataOperation.set('${form.value.fieldName}',${form.value.fieldName}${form.value.keys ? ('.' + form.value.keys) : ''})`;
  } else {
    return `localData['${form.value.fieldName}'] = ${form.value.fieldName}${form.value.keys}`;
  }
};


const onSubmit = () => {
  return `const ${form.value.fieldName} = await request({
    url: '${form.value.url}',
    method: '${form.value.method}',
    ${setParams(form.value.method)}
  })
  ${setRes()}
  ${form.value.isTotal ? `localData.total = ${form.value.fieldName}.total` : ''}
  `;
};


defineExpose({ onSubmit });
</script>
