<template>
    <div class="edit-view">
        <el-form
            :model="formData"
            :rules="rules"
            ref="form"
            label-width="108px"
            label-position="right"
            size="small"
            style="max-width: 700px;"
        >
            <el-form-item prop="type" label="发送类型">
                <el-select v-model="formData.type" clearable filterable placeholder="请选择" :disabled="formData.send">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="authorities" label="角色权限" v-if="formData.type == 'PERMISSION'">
                <el-select
                    v-model="formData.authorities"
                    multiple
                    placeholder="请选择"
                    value-key="name"
                    style="width:70%"
                    @change="changeAuth"
                    :disabled="formData.send"
                >
                    <el-option v-for="item in authorities" :key="item.name" :label="item.description" :value="item">
                    </el-option>
                </el-select>
                <el-button style="margin-left: 20px" @click="showUser">查看人员</el-button>
            </el-form-item>
            <el-form-item label="模版" v-if="formData.type == 'UPLOAD'">
                <el-button @click="downloadTemp">手机号模版下载</el-button>
                <el-upload
                    :action="uploadUrl"
                    :before-upload="beforeUpload"
                    :headers="headers"
                    :show-file-list="false"
                    ref="upload"
                    :on-success="onSuccess"
                    class="uploader"
                    :on-error="onfail"
                    :loading="loading"
                    :disabled="loading || formData.send"
                >
                    <el-button slot="trigger" :loading="loading" :disabled="loading || formData.send"
                        >导入手机号</el-button
                    >
                </el-upload>
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
                <!-- <el-input v-model="formData.phone"></el-input> -->
                <el-select
                    v-model="formData.phone"
                    class="suffix"
                    multiple
                    style="width: 100%"
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请输入手机号，按回车分割"
                    clearable
                    popper-class="hideSelect"
                    :disabled="formData.send"
                >
                </el-select>
            </el-form-item>
            <el-form-item prop="content" label="短信内容">
                <el-input type="textarea" :rows="6" v-model="formData.content" :readonly="formData.send"></el-input>
            </el-form-item>
            <el-form-item prop="responseBody" label="返回内容" v-if="formData.responseBody">
                <el-input v-model="formData.responseBody" :readonly="formData.send"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="submit(false)" :loading="saving" type="primary" v-if="!formData.send"
                    >保存</el-button
                >
                <el-button @click="onSave" :loading="saving" type="success" v-if="!formData.send">发送</el-button>
                <el-button @click="sendToo" :loading="saving" type="success" v-if="formData.send">再次发送</el-button>
                <el-button @click="onDelete" :loading="saving" type="danger" v-if="formData.id">删除 </el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
        <el-dialog title="待发送人员" :visible.sync="dialogShow" style="min-height:400px">
            <el-table
                :data="users"
                row-key="id"
                ref="table"
                height="tableHeight"
                header-row-class-name="table-header-row"
                header-cell-class-name="table-header-cell"
                row-class-name="table-row"
                cell-class-name="table-cell"
            >
                <el-table-column prop="nickname" label="昵称" min-width="100"> </el-table-column>
                <el-table-column prop="phone" label="手机号" min-width="100"> </el-table-column>
                <el-table-column prop="work" label="工作单位" min-width="100"> </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import resolveUrl from 'resolve-url';
export default {
    name: 'MessageEdit',
    created() {
        this.uploadUrl = resolveUrl(this.$baseUrl, 'message/upload');
        if (this.$route.query.id) {
            this.get(this.$route.query.id);
        }
        this.$http
            .get('/authority/all')
            .then(res => {
                this.authorities = res;
            })
            .catch(e => {
                console.log(e);
            });
    },
    data() {
        return {
            saving: false,
            formData: {},
            rules: {
                type: [{ required: true, message: '请选择发送类型', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
                content: [{ required: true, message: '请输入短信内容', trigger: 'blur' }]
            },
            typeOptions: [
                { label: '按角色权限选择', value: 'PERMISSION' },
                { label: '手动输入手机号', value: 'MANUAL' },
                { label: '批量上传手机号', value: 'UPLOAD' }
            ],
            authorities: [],
            loading: false,
            users: [],
            dialogShow: false
        };
    },
    computed: {
        headers() {
            return {
                Authorization: 'Bearer ' + sessionStorage.getItem('token')
            };
        }
    },
    methods: {
        sendToo() {
            this.formData.id = '';
            this.formData.responseBody = '';
            this.onSave();
        },
        onSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    return this.$confirm('确认要发送短信吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        this.submit(true);
                    });
                } else {
                    return false;
                }
            });
        },
        submit(send) {
            let data = { ...this.formData, send: send };

            this.saving = true;
            this.$http
                .post('/message/save', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    if (send) {
                        this.$http.get(`/message/send/${res.id}`);
                    }
                    this.$message.success('成功');
                    // this.$router.go(-1);
                    this.$router.replace({
                        query: {
                            id: res.id
                        }
                    });
                    this.formData.id = res.id;
                    this.formData.send = res.send;
                    this.formData.responseBody = res.responseBody;
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        onDelete() {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/message/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 || '删除失败');
                    }
                });
        },
        downloadTemp() {
            this.downloading = true;
            this.$axios
                .get('/message/excelTemp', {
                    responseType: 'blob'
                })
                .then(res => {
                    this.downloading = false;
                    const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
                    const link = document.createElement('a');
                    link.href = downloadUrl;
                    link.setAttribute('download', res.headers['content-disposition'].split('filename=')[1]);
                    document.body.appendChild(link);
                    link.click();
                    link.remove();
                })
                .catch(e => {
                    console.log(e);
                    this.downloading = false;
                    this.$message.error(e.error);
                });
        },
        beforeUpload() {
            return this.$confirm('确认要导入表格吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true;
            });
        },
        upload() {},
        onfail(e) {
            console.log(e);
            this.$message.error('失败:' + e);
            this.loading = false;
        },
        onSuccess(res) {
            console.log(res);
            this.formData.phone = res;
            this.$message.success('上传成功');
            this.loading = false;
        },
        showUser() {
            this.dialogShow = true;
            if (this.formData.send) {
                let data = this.formData.authorities.map(item => {
                    return item.name;
                });
                if (this.formData.authorities.length > 0) {
                    this.$http
                        .post(
                            '/user/byAuthority',
                            { size: 1000, query: { del: false, authorities: data.join(',') } },
                            { body: 'json' }
                        )
                        .then(res => {
                            this.users = res.content;
                        })
                        .catch(e => {
                            console.log(e);
                        });
                }
            }
        },
        changeAuth(res) {
            let data = res.map(item => {
                return item.name;
            });
            // console.log(res);
            if (res.length == 0) {
                this.formData.phone = [];
            }
            if (res.length > 0) {
                this.$http
                    .post(
                        '/user/byAuthority',
                        { size: 1000, query: { del: false, authorities: data.join(',') } },
                        { body: 'json' }
                    )
                    .then(res => {
                        this.users = res.content;
                        let phone = this.users.map(item => {
                            return item.phone;
                        });
                        this.formData.phone = phone;
                    })
                    .catch(e => {
                        console.log(e);
                    });
            }
        },
        get(id) {
            this.$http
                .get('message/get/' + id)
                .then(res => {
                    this.formData = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    }
};
</script>
<style lang="less" scoped>
.uploader {
    display: inline-block;
    margin: 0 10px;
}
</style>
