<template>
    <div class="edit-view">
        <page-title>
            <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
            <!-- <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id"> 删除 </el-button> -->
            <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
        </page-title>
        <div class="edit-view__content-wrapper">
            <div class="edit-view__content-section">
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="form"
                    label-width="110px"
                    label-position="right"
                    size="small"
                    style="max-width: 750px"
                >
                    <el-form-item prop="name" label="拍卖名称">
                        <el-input v-model="formData.name" style="width: 500px" :disabled="!canEdit"></el-input>
                    </el-form-item>
                    <el-form-item prop="pic" label="图片">
                        <object-upload
                            v-model="formData.pic[0]"
                            compress
                            width="3000"
                            height="3000"
                            :disabled="!canEdit"
                        ></object-upload>
                        <div class="tip">支持JPG、PNG、GIF、MP4，推荐长宽比1:1</div>
                    </el-form-item>
                    <el-form-item prop="model3d" label="3D模型">
                        <model-upload
                            :limit="1"
                            v-model="formData.model3d"
                            :customUrl="customUrl"
                            accept="application/zip"
                            format="json"
                            single
                        ></model-upload>
                        <div class="tip">请将FBX文件与贴图打包成zip压缩包上传</div>
                    </el-form-item>
                    <el-form-item label="相机距离" v-if="formData.model3d">
                        <el-input-number v-model="scale" :min="0.1" :step="0.1"></el-input-number>
                    </el-form-item>
                    <el-form-item label="Y轴偏移" v-if="formData.model3d">
                        <el-input-number v-model="yOffset"></el-input-number>
                    </el-form-item>
                    <div class="inline-wrapper">
                        <el-form-item prop="sellerId" label="起拍者">
                            <minter-select
                                v-model="formData.sellerId"
                                @detail="onMinterDetail"
                                :disabled="!canEdit"
                            ></minter-select>
                        </el-form-item>
                        <el-form-item prop="category" label="分类">
                            <el-select v-model="formData.category" :disabled="!canEdit">
                                <el-option
                                    v-for="item in cateogories"
                                    :label="item"
                                    :value="item"
                                    :key="item"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>

                    <el-form-item prop="detail" label="详情" style="width: calc(100vw - 450px)">
                        <rich-text v-model="formData.detail"></rich-text>
                    </el-form-item>
                    <el-form-item prop="auctionType" label="拍卖类型">
                        <el-select
                            v-model="formData.auctionType"
                            clearable
                            filterable
                            placeholder="请选择"
                            :disabled="!canEdit"
                        >
                            <el-option
                                v-for="item in auctionTypeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <div class="inline-wrapper">
                        <el-form-item prop="startingPrice" label="起拍价">
                            <el-input-number
                                type="number"
                                v-model="formData.startingPrice"
                                :disabled="!canEdit"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item prop="increment" label="加价幅度">
                            <el-input-number
                                type="number"
                                v-model="formData.increment"
                                :disabled="!canEdit"
                            ></el-input-number>
                        </el-form-item>
                    </div>
                    <div class="inline-wrapper">
                        <el-form-item prop="deposit" label="保证金">
                            <el-input-number
                                type="number"
                                v-model="formData.deposit"
                                :disabled="!canEdit"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item prop="fixedPrice" label="一口价">
                            <el-input-number
                                type="number"
                                v-model="formData.fixedPrice"
                                :disabled="!canEdit"
                            ></el-input-number>
                        </el-form-item>
                    </div>
                    <div class="inline-wrapper">
                        <el-form-item prop="royalties" label="版税(%)">
                            <el-input-number v-model="formData.royalties" :min="0" :max="99" :disabled="!canEdit">
                            </el-input-number>
                        </el-form-item>
                        <el-form-item prop="serviceCharge" label="手续费(%)">
                            <el-input-number v-model="formData.serviceCharge" :min="0" :max="99" :disabled="!canEdit">
                            </el-input-number>
                        </el-form-item>
                    </div>
                    <el-form-item prop="startTime" label="开始时间">
                        <el-date-picker
                            v-model="formData.startTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item prop="endTime" label="截止时间">
                        <el-date-picker
                            v-model="formData.endTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                        >
                        </el-date-picker>
                    </el-form-item>

                    <!-- <el-form-item prop="purchasePrice" label="出价">
                        <el-input-number type="number" v-model="formData.purchasePrice"></el-input-number>
                    </el-form-item> -->
                    <!-- <el-form-item prop="purchaserId" label="买家id">
                        <el-input-number type="number" v-model="formData.purchaserId"></el-input-number>
                    </el-form-item>
                    <el-form-item prop="purchaser" label="买家">
                        <el-input v-model="formData.purchaser"></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item prop="status" label="状态">
                        <el-select v-model="formData.status" clearable filterable placeholder="请选择">
                            <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                    <!-- <el-form-item prop="source" label="状态">
                        <el-select v-model="formData.source" clearable filterable placeholder="请选择">
                            <el-option
                                v-for="item in sourceOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item class="form-submit">
                        <el-button @click="onSave" :loading="saving" type="primary"> 保存 </el-button>
                        <!-- <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
                            删除
                        </el-button> -->
                        <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import resolveUrl from 'resolve-url';
import ModelUpload from '../components/ModelUpload.vue';
import { format, parse, isBefore } from 'date-fns';
export default {
    name: 'AuctionActivityEdit',
    components: { ModelUpload },
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('auctionActivity/get/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                    this.canEdit = res.source !== 'TRANSFER';
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    },
    data() {
        return {
            saving: false,
            formData: {
                pic: [],
                source: 'OFFICIAL'
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    }
                ],
                pic: [
                    {
                        validator: (rule, value, callback) => {
                            if (value) {
                                if (!(value instanceof Array)) {
                                    callback(new Error('请上传内容'));
                                    return;
                                } else {
                                    for (let f of value) {
                                        if (!f.url) {
                                            callback(new Error('请上传内容'));
                                            return;
                                        }
                                    }
                                }
                                callback();
                            } else {
                                callback(new Error('请上传内容'));
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                seller: [
                    {
                        required: true,
                        message: '请输入铸造者',
                        trigger: 'blur'
                    }
                ],
                sellerId: [
                    {
                        required: true,
                        message: '请输入铸造者ID',
                        trigger: 'blur'
                    }
                ],
                detail: [
                    {
                        required: true,
                        message: '请输入详情',
                        trigger: 'blur'
                    }
                ],
                increment: [{ required: true, message: '请输入加价幅度' }],
                royalties: [{ required: true, message: '请填写版税' }],
                serviceCharge: [{ required: true, message: '请填手续费' }],
                auctionType: [{ required: true, message: '请选择拍卖类型' }],
                startTime: [
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请填写发布时间'));
                                // } else if (isBefore(parse(value, 'yyyy-MM-dd HH:mm:ss', new Date()), new Date())) {
                                //     callback(new Error('发布时间不能小于当前时间'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                endTime: [
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请填写结束时间'));
                            } else if (isBefore(parse(value, 'yyyy-MM-dd HH:mm:ss', new Date()), new Date())) {
                                callback(new Error('结束时间不能小于当前时间'));
                            } else if (this.formData.startTime) {
                                if (
                                    isBefore(
                                        parse(value, 'yyyy-MM-dd HH:mm:ss', new Date()),
                                        parse(this.formData.startTime, 'yyyy-MM-dd HH:mm:ss', new Date())
                                    )
                                ) {
                                    callback(new Error('结束时间不能小于发布时间'));
                                } else {
                                    callback();
                                }
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            auctionTypeOptions: [
                { label: '虚拟藏品', value: 'NFT' },
                { label: '实物', value: 'ENTITY' }
            ],
            statusOptions: [
                { label: '未开始', value: 'NOTSTARTED' },
                { label: '进行中', value: 'ONGOING' },
                { label: '成交', value: 'PURCHASED' },
                { label: '一口价成交', value: 'FIXED_PRICE_PURCHASED' },
                { label: '流拍', value: 'PASS' },
                { label: '完成', value: 'FINISH' }
            ],
            sourceOptions: [
                { label: '官方拍卖', value: 'OFFICIAL' },
                { label: '转让拍卖', value: 'TRANSFER' }
            ],
            cateogories: ['勋章', '收藏品', '数字艺术', '门票', '游戏', '音乐', '使用', '其他'],
            customUrl: resolveUrl(this.$baseUrl, 'upload/3dModel'),
            canEdit: true
        };
    },
    // computed: {
    //     canEdit() {
    //         // return !!!this.$route.query.id;
    //         return this.formData.source === 'TRANSFER';
    //     }
    // },
    methods: {
        onSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    console.log('1');
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {
            let data = { ...this.formData };
            if (data.model3d) {
                data.model3d.url = data.model3d.url + '?scale=' + this.scale + '&yOffset=' + this.yOffset;
            }

            this.saving = true;

            this.$http
                .post('/auctionActivity/save', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        onDelete() {
            this.$confirm('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/auctionActivity/del/${this.formData.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        console.log(e);
                        this.$message.error((e || {}).error || '删除失败');
                    }
                });
        },
        onMinterDetail(e) {
            console.log(e);
            this.$set(this.formData, 'minter', e.nickname);
            this.$set(this.formData, 'minterAvatar', e.avatar);

            this.$set(this.formData, 'sellerId', e.id);
            this.$set(this.formData, 'seller', e.nickname);
            this.$set(this.formData, 'sellerAvatar', e.avatar);
        }
    }
};
</script>
<style lang="less" scoped>
.tip {
    font-size: 12px;
    color: @text3;
    margin-top: 5px;
}
.inline-wrapper {
    .el-form-item {
        display: inline-block;
    }
}
</style>
