<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="选择商品" :wrapper-col="{ offset: 0, span: 8 }" name="sub" :rules="rulesRef.sub"
                :label-col="{ span: 1 }">
                <div style="width:100%;display: flex;align-items: center;">
                    <a-select v-model:value="formState.sub" mode="multiple" style="width: 100%" placeholder="请选择商品"  @change="handleChanges">
                       <a-select-option   v-for="item in optionss" :itemKey="item" :value="item.goodsid" :label="item.goodsid">
                       {{item.subject}}
                        </a-select-option>
                    </a-select>
                </div>
            </a-form-item>
            <a-form-item label="商品描述" name="shortname" :rules="rulesRef.shortname" :label-col="{ span: 1 }">
                <a-input v-model:value="formState.shortname" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 0, span: 8 }">
                <a-button type="primary" html-type="submit" @click="onSubmit">确定</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref, defineEmits, defineExpose, toRaw, onMounted,} from "vue";
import { message, UploadProps, Upload } from "ant-design-vue";
import { Form } from 'ant-design-vue';
import { onCreateGoods, onSelectGoods } from '@/api/index'
import { getUid } from "@/utils/userInfo";
const useForm = Form.useForm;
interface FormState {
    subject: string,
    shortname: string;
    remember: boolean;
    body: string,
    picurl: string,
    markingprice: string,
    price: string,
    sub: any,
}

const plainOptions = [
    { label: "免费", value: true },
    { label: "收费", value: true },
];
const props = defineProps();
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"]>([

]); let 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>({
    subject: '',
    shortname: "",
    remember: true,
    body: "",
    picurl: "",
    markingprice: "",
    price: "",
    sub: []
});
const optionss = ref([])
const rulesRef = reactive({
    subject: [
        {
            required: true,
            message: '请输入商品名称!',
        },
    ],
    shortname: [
        {
            required: true,
            message: '请输入商品简介!',
        },
    ],
    body: [
        {
            required: true,
            message: '请输入商品详情!',
        },
    ],
    picurl: [
        {
            validateOnRuleChange: true,
            message: '请上传商品示图!',
        },
    ],
    markingprice: [
        {
            required: true,
            message: '请输入划线价格',
        },
    ],
    price: [
        {
            required: true,
            message: '请输入售卖价格',
        },
    ],
    sub: [
        {
            required: true,
            message: '请选择商品',
        },
    ],
});
const { resetFields, validate } = useForm(formState, rulesRef);

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.data;
        }

        return file;
    });

    fileList.value = resFileList;
};
const onSelectPlain = (e: any) => {
    formState.price = "0"
    // free 0
    value.value = e.target.value;

};
const onEditorChange = (e: any) => {
    console.log(e.html, 'e');
}
const handleChanges = (value: string) => {
    console.log(`selected ${value}`);
};
const beforeUpload: UploadProps['beforeUpload'] = file => {
    if (!(file.type.includes('png') || file.type.includes('jpeg') || file.type.includes('jpg'))) {
        message.error(`${file.name}不是png/jpef/jpg格式`);
        return Upload.LIST_IGNORE;
    }
};
const onSubmit = () => {
    validate()
        .then(async () => {
            const uid = getUid()
            const prarms = {
                ...toRaw(formState),
                uid,
                parent: 0
            }
            const data: any = await onCreateGoods(JSON.stringify(prarms))
            if (data.state === 1) {
                resetFields()
                fileList.value = []
                message.success(data.message)
                emit('onBack')
            }
        })
        .catch(err => {
            console.log('error', err);
        });

};
onMounted(async () => {
    const uid = getUid()
    const data = await onSelectGoods(uid)
    optionss.value = data.data
    return options
})

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

</script>
<style lang="less" scoped>
.page {
    width: 100%;

    .title {
        padding-top: 20px;
        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;
        }
    }

    .please {
        min-width: 140px;
        height: 30px;
        background-color: @primary-color;
        color: white;
        margin-left: 20px;
        display: flex;
        align-items: center;
        padding: 5px;
    }
}
</style>
