<template>
    <div class="edit-view">
        <el-form
            :model="formData"
            :rules="rules"
            ref="form"
            label-width="100px"
            label-position="right"
            size="small"
            style="max-width: 700px"
        >
            <el-form-item prop="year" label="年度">
                <el-select v-model="formData.year" style="width: 300px" @change="getName" :disabled="edit">
                    <el-option v-for="item in years" :key="item" :label="item" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="name" label="名称" v-if="formData.year">
                <el-input v-model="formData.name" :readonly="edit" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="报名起始时间">
                <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    start-placeholder="请选择开始时间"
                    end-placeholder="请选择结束时间"
                    range-separator="至"
                    style="width: 300px"
                    :readonly="edit"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="online" label="展演形式">
                <el-radio-group v-model="formData.online">
                    <el-radio :label="true">线上</el-radio>
                    <el-radio :label="false">线下</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="计划安排">
                <el-button type="primary" size="mini" @click="onAddOtherForm()">添加计划</el-button>
                <div class="add-con" v-for="(item, index) in schedules" :key="index">
                    <div v-if="!item.del">
                        <el-row>
                            <el-col :span="11">
                                <el-form-item prop="content" label="活动内容">
                                    <el-input v-model="item.content"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item prop="date" label="活动时间">
                                    <el-date-picker
                                        v-model="item.date"
                                        type="date"
                                        value-format="yyyy-MM-dd"
                                        placeholder="选择日期"
                                    >
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="20">
                                <el-form-item label="活动地点">
                                    <el-input v-model="item.address"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="3">
                                <el-form-item>
                                    <el-button
                                        class="del"
                                        type="danger"
                                        size="small"
                                        icon="el-icon-delete"
                                        @click="onDeleteOtherForm(item, index)"
                                    ></el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="咨询电话">
                <el-button type="primary" size="mini" @click="onAddPhoneForm()">添加电话</el-button>
                <div class="add-con" v-for="(item, index) in phones" :key="index">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="联系人">
                                <el-input v-model="item.name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="电话">
                                <el-input v-model="item.phone"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3">
                            <el-form-item>
                                <el-button
                                    class="del"
                                    type="danger"
                                    size="small"
                                    icon="el-icon-delete"
                                    @click="onDeletePhoneForm(item, index)"
                                ></el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form-item>
            <el-form-item prop="email" label="活动邮箱">
                <el-input v-model="formData.email" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item prop="annex" label="活动方案">
                <file-upload v-model="formData.annex"></file-upload>
            </el-form-item>
            <el-form-item prop="codeImg" label="活动工作群">
                <single-upload v-model="formData.codeImg"></single-upload>
            </el-form-item>
            <el-form-item>
                <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
                <el-button @click="onDelete" :loading="saving" type="danger" v-if="formData.id && !edit">
                    删除
                </el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { mapState } from 'vuex';
export default {
    name: 'PerformanceEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('performance/backGet/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                    if (res.programmeNum > 0) {
                        this.edit = true;
                    }
                    if (typeof res.performanceEnquiries != 'undefined') {
                        this.phones = res.performanceEnquiries;
                    }
                    this.dateRange = [res.startDate, res.endDate];

                    this.$http
                        .post(
                            '/performanceSchedule/all',
                            { size: 100, query: { performanceId: this.$route.query.id } },
                            { body: 'json' }
                        )
                        .then(res => {
                            this.schedules = res.content;
                        });
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        } else {
            this.$confirm('是否代入上一年信息？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.post('/performance/lastYear').then(res => {
                    if (res != '') {
                        if (res.programmeNum > 0) {
                            this.edit = true;
                        }
                        if (typeof res.performanceEnquiries != 'undefined') {
                            this.phones = res.performanceEnquiries;
                        }
                        this.dateRange = [res.startDate, res.endDate];

                        this.$http
                            .post(
                                '/performanceSchedule/all',
                                { size: 100, query: { performanceId: res.id } },
                                { body: 'json' }
                            )
                            .then(res => {
                                this.schedules = res.content.map(item => {
                                    delete item.id;
                                    return item;
                                });
                            });

                        delete res.id;
                        delete res.del;
                        this.formData = res;
                    } else {
                        this.$message.warning('暂无上一年信息');
                    }
                });
            });
        }
        // this.getAdmin();
        let year = new Date().getFullYear();
        this.years = [year - 1, year, year + 1, year + 2, year + 3];
    },
    data() {
        return {
            saving: false,
            formData: {},
            rules: {},
            statusOptions: [
                { label: '报名中', value: 'APPLY' },
                { label: '已结束', value: 'END' }
            ],
            dateRange: [],
            eventTimeRange: '',
            years: [],
            schedules: [],
            phones: [],
            performanceId: '',
            edit: false
        };
    },
    computed: {
        saveOtherJson() {
            const schedules = [...this.schedules]
                .filter(item => {
                    return !!item.content || !!item.date || !!item.address;
                })
                .map(item => {
                    return {
                        ...item,
                        performanceId: this.performanceId
                    };
                });
            return JSON.stringify(schedules);
        }
    },
    methods: {
        onSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {
            let data = { ...this.formData };
            data.startDate = this.dateRange[0];
            data.endDate = this.dateRange[1];
            data.performanceEnquiries = this.phones;
            this.saving = true;
            this.$http
                .post('/performance/save', data, { body: 'json' })
                .then(res => {
                    this.saving = false;

                    this.performanceId = res.id;
                    this.$nextTick(() => {
                        this.$http.post('/performanceSchedule/batchSave', {
                            schedules: this.saveOtherJson
                        });
                    });
                    this.$message.success('成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        onDelete() {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/performance/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 || '删除失败');
                    }
                });
        },
        onAddOtherForm() {
            this.schedules.push({
                content: '',
                date: '',
                address: ''
            });
        },
        onAddPhoneForm() {
            this.phones.push({
                name: '',
                phone: ''
            });
        },
        onDeleteOtherForm(info, index) {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'warning' })
                .then(() => {
                    const schedules = [...this.schedules];
                    if (info.id) {
                        info.del = true;
                        schedules[index] = info;
                    } else {
                        schedules.splice(index, 1);
                    }
                    this.schedules = schedules;
                    this.$message.success('删除成功');
                })
                .catch(e => {});
        },
        onDeletePhoneForm(info, index) {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'warning' })
                .then(() => {
                    const phones = [...this.phones];
                    phones.splice(index, 1);
                    this.phones = phones;
                    this.$message.success('删除成功');
                })
                .catch(e => {});
        },
        getName(value) {
            this.formData.name = value + '“宁艺之星”社会艺术水平考级展演(览)';
        }
    }
};
</script>
<style lang="less" scoped>
.add-con {
    background-color: #f7f7f7;
    width: 100%;
    margin: 7px 0;
    padding-top: 14px;
}
.del {
    float: right;
}
/deep/.el-input.is-disabled .el-input__inner {
    background-color: #ffffff;
    color: #606266;
}
</style>
