<template>
  <div class="page">
    <!-- {{props.props.propsData.isCad}} -->
    <div class="title">商品基础信息</div>
    <a-form
      style="margin-top: 30px"
      :model="formState"
      name="basic"
      :label-col="{ span: 2 }"
      :wrapper-col="{ span: 8 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="商品名称"
        name="Username"
        :rules="[{ required: true, message: 'Please input your username!' }]"
      >
        <a-input v-model:value="formState.username" />
      </a-form-item>

      <a-form-item
        label="商品简介"
        name="password"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <a-input-password v-model:value="formState.password" />
      </a-form-item>

      <a-form-item
        label="商品示图"
        name="picurl"
        :rules="[{ required: true, message: 'Please input your password!' }]"
        :wrapper-col="{ offset: 0, span: 8 }"
        class="Up"
      >
        <div class="clearfix">
          <a-upload
            class="clearfix-up"
            v-model:file-list="fileList"
            action="/api/file/upload"
            list-type="picture-card"
            @preview="handlePreview"
             @change="handleChange"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">Upload</div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :title="previewTitle"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
          <div>
            <p class="warin">
              建议图片比例为4:3,大小不超过200M,图片仅支持JPG、JPEG、PNG格式
            </p>
          </div>
        </div>
      </a-form-item>
      <a-form-item
        label="商品详情"
        name="password"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <div style="display: none">
          <a-upload
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            :multiple="true"
            :file-list="fileList"
            @change="handleChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              Upload
            </a-button>
          </a-upload>
        </div>

        <QuillEditor
          id="editorId"
          ref="myQuillEditor"
          v-model:content="content"
          theme="snow"
          contentType="html"
          :options="options"
        />

        <div class="editor-text">
          <p>1、商品描述需符合《中华人民共和国广告法》</p>
          <p>
            2、详情图片宽度750,高度不超过5000,每张图片最大不超过1M,图片仅支持JPG、JPEG、PNG格式。
          </p>
        </div>
      </a-form-item>
      <a-form-item
        name="商品价格"
        :wrapper-col="{ offset: 0, span: 8 }"
        label="Password"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <div>
          <a-radio-group v-model:value="value" @change="onSelectPlain">
            <a-radio :value="1">免费</a-radio>
            <a-radio :value="2">收费</a-radio>
          </a-radio-group>
        </div>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 0, span: 8 }" v-if="value === 2">
        <div>
          <div>划线价</div>
          <a-input-number
            v-model:value="crossedPrice"
            style="width: 200px"
            :min="0"
            :max="10"
            :step="0.01"
            string-mode
          />
        </div>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 0, span: 1 }" v-if="value === 2">
        <div>
          <div>售卖价</div>
          <a-input-number
            v-model:value="sellingPrice"
            style="width: 200px"
            :min="0"
            :max="10"
            :step="0.01"
            string-mode
          />
        </div>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset:0 , span: 8 }">
        <a-button type="primary" html-type="submit" @click="onSubmit">Submit</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import {  reactive, ref,defineEmits,shallowRef,defineExpose } from "vue";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import type { UploadProps, RadioGroupProps } from "ant-design-vue";
import { QuillEditor, Quill } from "@vueup/vue-quill";
import {onCreateGoods} from '@/api/index'
import "@vueup/vue-quill/dist/vue-quill.snow.css";
    interface FormState {
    username: string;
    password: string;
    remember: boolean;
    picurl:string;
    }
    interface Props {
    props: Object;
  }

    function getBase64(file: File) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
    }
    const plainOptions = [
    { label: "免费", value: true },
    { label: "收费", value: true },
    ];
    const props = defineProps<Props>();
    const emit= defineEmits(['onBack']);
    let content = ref("");
    const myQuillEditor = ref(null);
    const crossedPrice = ref<Number>(1);
    const sellingPrice = ref<Number>(1);
    const value = ref<number>(1);
    const previewVisible = ref(false);
    const previewImage = ref("");
    const previewTitle = ref("");
    const fileList = ref<UploadProps["fileList"]>([
      {
        uid: "-1",
        name: "image.png",
        status: "done",
        url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
      },
    ]);
    const options = reactive({
      modules: {
        toolbar: {
          container: [
            [{ size: ["small", false, "large"] }],
            ["bold", "italic", "underline"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            ["link", "image"],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
          ],
          handlers: {
            image: function (value: any) {
              if (value) {
                // 调用element图片上传
                // document.querySelector(".editor-img-uploader>.el-upload").click();
              } else {
                Quill.format("image", true);
              }
            },
          },
        },
        history: {
          delay: 1000,
          maxStack: 50,
          userOnly: false,
        },
      },
    });

    const handleCancel = () => {
      previewVisible.value = false;
      previewTitle.value = "";
    };
    const handlePreview = async (file: any) => {
      if (!file.url && !file.preview) {
        file.preview = (await getBase64(file.originFileObj)) as string;
      }
      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
      previewTitle.value =
        file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
    };
    const formState = reactive<FormState>({
      username: "",
      password: "",
      remember: true,
    });
    const onFinish = (values: any) => {
      console.log("Success:", values);
    };

    const onFinishFailed = (errorInfo: any) => {
      console.log("Failed:", errorInfo);
    };
    const handleChange = (info: any) => {
      let resFileList = [...info.fileList];

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      resFileList = resFileList.slice(-2);

      // 2. read from response and show file link
      resFileList = resFileList.map((file) => {
        if (file.response) {
          // Component will show file.url as link
           formState.picurl = file.response.url;
        }
        file.response.data
        
        return file;
      });

      fileList.value = resFileList;
    };
    const onSelectPlain = (e: any) => {
      value.value = e.target.value;
    };
    const onSubmit =async ()=>{
        // emit('onBack')
        const params = {

        }
      const data =  await onCreateGoods(params)
      console.log(data,'data');
      
    };

    defineExpose({
      formState,
      onFinish,
      onFinishFailed,
      previewVisible,
      previewImage,
      fileList,
      handleCancel,
      handlePreview,
      previewTitle,
      options,
      content,
      handleChange,
      plainOptions,
      value,
      onSelectPlain,
      crossedPrice,
      sellingPrice,
      onSubmit,
    });

</script>
<style lang="less" scoped>
.page {
  width: 100%;
  .title {
    text-align: left;
  }
  .clearfix {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;
    .ant-upload-picture-card-wrapper {
      display: flex;
    }
  }
  .Up {
    display: flex;
    .warin {
      font-family: SourceHanSansSC;
      font-weight: 400;
      font-size: 12px;
      color: rgb(154, 154, 154);
      font-style: normal;
      letter-spacing: 0px;
      line-height: 17px;
      text-decoration: none;
    }
  }
  .editor-text {
    border-radius: 3px;
    font-size: 14px;
    padding: 0px;
    text-align: center;
    background: rgb(239, 239, 239);
    display: flex;
    align-items: baseline;
    flex-direction: column;
    > p {
      margin-left: 5px;
      margin-top: 10px;
      margin-bottom: 10px;
      font-weight: 400;
      font-size: 12px;
      color: rgb(154, 154, 154);
      flex: 1;
    }
  }
}
</style>
