<template>
    <!-- 新增/修改项目文件 -->
    <div id="addProjectDialog">
        <el-dialog
            :title="dialogType === 'create' ? '添加项目' : '修改项目'"
            :visible.sync="addProjectVisible"
            width="570px"
            :before-close="handleClose"
        >
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="" prop="localName">
                    <el-input v-model="form.localName" placeholder="请输入项目名称" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-upload class="avatar-uploader" accept="image/*" action="#" :show-file-list="false"
                               :http-request="uploadImg">
                        <img v-if="form.picInfo.key" :src="form.picInfo.key | getImage" class="avatar"/>
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleClick">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import {Vue, Component, Prop, Emit, Watch, Ref} from "vue-property-decorator";
import tools from "@/utils/maintain";
import {imageUploadUrl, imageGetUrl} from "@/api/imageservice";
import {projectCreate, projectUpdate} from "@/api/datacenter";
import {ElForm} from "element-ui/types/form";

@Component({
    name: "AddProjectDialog",
    components: {},
    filters: {
        getImage(key: string | undefined) {
            if (key) {
                return `${imageGetUrl}${key}`;
            } else {
                return "";
            }
        },
    },
})
export default class extends Vue {
    @Prop() private addProjectVisible!: boolean;
    @Prop() private dialogType!: string;
    @Prop() private formData!: any;

    @Ref("ruleForm") readonly ruleForm!: ElForm;

    @Emit("update:addProjectVisible")
    handleClose() {
        return false;
    }

    private form: any = {
        localName: "",
        picInfo: {},
    };
    private rules: any = {
        localName: [{required: true, message: "请输入项目名称", trigger: "blur"}],
    };

    /**
     * 自定义图片上传
     */
    private uploadImg(param: any) {
        const elFile = param.file;
        const fileReader = new FileReader();
        fileReader.readAsDataURL(elFile); //读取图片

        const ftype = elFile.type;
        const fname = elFile.name;
        const uid = elFile.uid;
        const createTime = tools.formatDate(new Date());

        fileReader.addEventListener("load", () => {
            // 读取完成
            const res = fileReader.result;
            //将canvas的base64位图片转换成图片png的file
            const blob = this.dataURLtoBlob(res, ftype);
            //将其转换成file对象
            const file = new File([blob], fname, {
                type: ftype,
                lastModified: Date.now(),
            }); //blob转file

            // try sending
            const reader = new FileReader();
            const fileType = file.name.split(".");
            const imgType = fileType[fileType.length - 1];
            const uploadKey = `${uid}.${imgType}`;
            reader.onloadend = () => {
                // 这个事件在读取结束后，无论成功或者失败都会触发
                if (reader.error) {
                    console.error("读取文件失败：", reader.error);
                } else {
                    // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
                    const xhr = new XMLHttpRequest();
                    xhr.open("POST", `${imageUploadUrl}${uploadKey}`);
                    xhr.send(reader.result);
                    xhr.onreadystatechange = () => {
                        if (xhr.readyState == 4) {
                            if (xhr.status == 200) {
                                this.form.picInfo = {
                                    name: uid,
                                    key: uploadKey,
                                    systemId: "dataPlatform",
                                    type: "image",
                                    createTime: createTime,
                                };
                            }
                        }
                    };
                }
            };
            reader.readAsArrayBuffer(file);
        });
    }

    private dataURLtoBlob(dataURI: any, type: string) {
        const binary = atob(dataURI.split(",")[1]);
        const array = [];
        for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {type: type});
    }

    /**
     * 点击确定（添加/修改项目）
     */
    private handleClick() {
        this.ruleForm.validate(async (valid) => {
            if (valid) {
                if (this.dialogType === "create") {
                    //创建项目
                    const params: any = {
                        id: `Pj${new Date().getTime()}`,
                        localName: this.form.localName,
                    };
                    if (this.form.picInfo?.key) {
                        params.infos = {
                            projPic: [this.form.picInfo],
                        };
                    }
                    const res = await projectCreate({content: [params]});
                    if (res.result === "success") {
                        this.handleClose();
                        this.$emit("update:projectList");
                        this.$message.success("创建成功！");
                    } else {
                        this.$message.success(`创建失败！失败原因：${res.message}`);
                    }
                } else if (this.dialogType === "update" && this.formData?.id) {
                    //修改项目
                    const params: any = {
                        id: this.formData.id,
                        localName: this.form.localName,
                    };
                    if (this.form.picInfo?.key) {
                        params.infos = {
                            projPic: [this.form.picInfo],
                        };
                    }
                    const res = await projectUpdate({content: [params]});
                    if (res.result === "success") {
                        this.$emit("update:projectList");
                        this.handleClose();
                        this.$message.success("修改成功！");
                    } else {
                        this.$message.success(`修改失败！失败原因：${res.message}`);
                    }
                }
            } else {
                return false;
            }
        });
    }

    @Watch("addProjectVisible")
    onVisibleChanged(val: boolean) {
        if (val) {
            this.form.localName = this.formData?.localName ? this.formData.localName : "";
            this.form.picInfo = this.formData?.infos?.projPic?.length ? this.formData.infos.projPic[0] : {};
            if (this.formData?.id) this.form.id = this.formData.id;
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 30px 120px;

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }

    .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }
}
</style>
