<template>
  <div class="container">
    <el-form label-position="left">
      <template v-for="(item, index) in fromData">
        <template v-if="item.type === 'upload'">
          <el-form-item :label="item.title" label-width="200px">
            <FileUpload
              v-model:modelValue="item.content"
              v-model:loaderData="loaderData"
            />
          </el-form-item>
        </template>
        <template v-if="item.type === 'input'">
          <el-form-item
            :label="item.title"
            label-width="200px"
            :required="item.title == '手机号'"
            v-if="item.title == '手机号'"
          >
            <el-input
              v-model="item.content"
              :placeholder="'请输入' + item.title"
              type="text"
            />
          </el-form-item>
          <el-form-item
            :label="item.title"
            label-width="200px"
            :required="item.title == '微信号' || item.title == '需要设计的内容'"
            v-else
          >
            <el-input
              v-model="item.content"
              :placeholder="'请输入' + item.title"
            />
          </el-form-item>
        </template>
      </template>
      <el-button type="primary" @click="saveData" :disabled="isSubmit"
        >确认</el-button
      >
      <el-button type="primary" @click="handleDownload(loaderData)"
        >下载全部文件</el-button
      >
    </el-form>
    <div style="text-align: center; margin-top: 50px">
      闽ICP备2023014112号-1
    </div>
  </div>
</template>

<script setup>
import { getFormData, saveFormData } from "../api/index";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { handleBatchDownload } from "../utils/downFile";
const baseUrl = "https://dfdiyfile.oss-cn-fuzhou.aliyuncs.com/";
import { ref } from "vue";
import FileUpload from "../components/FileUpload/index";
const { currentRoute } = useRouter();
const tid = currentRoute.value.query.tid;
const userId = currentRoute.value.query.userId;

const fromData = ref([]);
const uploadList = ref([]);
const CeErpOrderFormData = ref({});
const loaderData = ref([]);

const isSubmit = ref(false);
async function saveData() {
  if (isSubmit.value) {
    return;
  }
  isSubmit.value = true;
  setTimeout(() => {
    isSubmit.value = false;
  }, 2000);
  let mobile = false;
  let wx = false;
  let need_content = false;
  let mobile_number = "123";
  fromData.value?.map((item) => {
    console.log("🚀 ~ fromData.value?.map ~ item:", item);
    if (item.title == "手机号" && !item?.content) {
      mobile = true;
    }
    if (item.title == "手机号" && item?.content) {
      mobile_number = item?.content;
    }
    if (item.title == "微信号" && !item?.content) {
      wx = true;
    }
    if (item.title == "需要设计的内容" && !item?.content) {
      need_content = true;
    }
  });
  if (need_content) {
    return ElMessage({
      message: "需要设计的内容不能为空",
      type: "error",
    });
  }
  if (mobile && wx) {
    return ElMessage({
      message: "手机号或者微信号不能都为空",
      type: "error",
    });
  }
  let regex =
    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  //!regex.test(mobile_number)
  if (mobile_number != "123" && mobile_number.length > 20) {
    return ElMessage({
      message: "请输入正确手机号",
      type: "error",
    });
  }
  try {
    let data = await saveFormData({
      id: CeErpOrderFormData.value ? CeErpOrderFormData.value.id : 0,
      tid,
      userId,
      content: JSON.stringify(fromData.value),
    });
    if (data.type === "success") {
      ElMessage({
        message: "保存成功",
        type: "success",
      });
    }
  } catch (error) {
    ElMessage({
      message: error.result,
      type: "error",
    });
  }
}
async function getData() {
  if (!tid) {
    return ElMessage({
      message: "获取不到参数",
      type: "error",
    });
  }
  try {
    let data = await getFormData({ tid });
    if (data.code === 200) {
      let product = data.product;
      CeErpOrderFormData.value = data.CeErpOrderFormData;
      let info = {};
      let json_info = `[{"title":"logo文件上传/模板截图/设计素材上传等等~","type":"upload"},
            {"title":"需要设计的内容","type":"input"},
            {"title":"手机号","type":"input"},
            {"title":"微信号","type":"input"},
            {"title":"请上传微信二维码","type":"upload"}]`;
      if (!product) {
        product = {
          FormJson: json_info,
        };
      }
      let fromdata = true;
      CeErpOrderFormData.value.content = CeErpOrderFormData.value.content.replace(/\n/g, ' ')
      if (CeErpOrderFormData.value && CeErpOrderFormData.value.content) {
        console.log(
          "🚀 ~ getData ~ CeErpOrderFormData.value.content:",
          CeErpOrderFormData.value.content
        );
        try {
          CeErpOrderFormData.value = {
            content: JSON.parse(CeErpOrderFormData.value.content),
            id: CeErpOrderFormData.value.ID,
            tid: CeErpOrderFormData.value.tid,
          };

          CeErpOrderFormData.value?.content.map((item) => {
            if (
              item.type == "upload" &&
              item.content &&
              typeof item.content == "string"
            ) {
              item.content?.split(",")?.map((e) => {
                loaderData.value.push(baseUrl + e);
              });
            }
          });
        } catch (error) {
          console.error("getData ~ error:", error);
          fromdata = false;
          ElMessage({
            message: "数据解析错误",
            type: "error",
          });
        }
      }
      product.FormJson = json_info;
      if (product && product.FormJson != "") {
        let formJson = JSON.parse(product.FormJson);
        let need = true;
        formJson.map((item) => {
          if (item.type === "upload") {
            item.content = [];
          } else {
            item.content = "";
          }
          if (fromdata) {
            if (CeErpOrderFormData.value && CeErpOrderFormData.value.content) {
              CeErpOrderFormData.value.content.map((e) => {
                if (e.title === item.title && e.type === item.type) {
                  item.content = e.content;
                }
              });
            }
          }

          if (item.title == "手机号") {
            need = false;
          }
          if (item.title == "微信号") {
            need = false;
          }
        });

        if (need) {
          formJson.push(
            ...[
              { title: "手机号", type: "input" },
              { title: "微信号", type: "input" },
            ]
          );
        }
        fromData.value = formJson;
      }
    }
  } catch (error) {
    console.log("🚀 ~ file: info.vue:15 ~ getData ~ error:", error);
  }
}
function handleDownload(data) {
  handleBatchDownload(data);
}
getData();
</script>

<style scoped lang="scss">
.container {
  max-width: 1400px;
  margin: 0 auto;
}
</style>
