<template>
    <div class="container">
        <!--    添加或修改对话框-->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
        >
            <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="80px">
                <el-form-item label="应用ID" prop="sourceId">
                    <el-input
                        v-model="form.sourceId"
                        :disabled="title !== '添加应用'"
                        placeholder="请输入应用ID"
                    />
                </el-form-item>
                <el-form-item label="应用名称" prop="sourceName">
                    <el-input
                        v-model="form.sourceName"
                        placeholder="请输入应用名称"
                    />
                </el-form-item>
                <el-form-item label="授权时间">
                    <el-col :span="11">
                        <el-date-picker v-model="form.startTime" placeholder="选择开始日期" style="width: 100%;"
                                        type="date"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                        ></el-date-picker>
                    </el-col>
                    <el-col :span="2" class="line">-</el-col>
                    <el-col :span="11">
                        <el-date-picker v-model="form.endTime" placeholder="选择结束日期" style="width: 100%;"
                                        type="date"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                        ></el-date-picker>
                    </el-col>
                </el-form-item>
                <div style="display: flex">
                    <el-form-item label="授权状态" style="flex: 1">
                        <el-switch
                            v-model="form.status"
                            :active-value="1"
                            :inactive-value="0"
                        >
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="水印开启状态" label-width="120" style="flex: 1">
                        <el-switch
                            v-model="form.watermarkStatus"
                            :active-value="1"
                            :inactive-value="0"
                        >
                        </el-switch>
                    </el-form-item>
                </div>
                <el-form-item label="水印模板配置" label-width="100px" prop="watermarkTemplate">
                    <el-tooltip effect="light" placement="top">
                        <div slot="content">
                            请填写占位符文字配置,例如:<br/>
                            仅供XXXX医院检验系统使用0078<br/>
                            动态配置可以使用占位符,例如:<br/>
                            仅供XXXX医院{sourceName}使用{userCode},目前提供的占位符属性有:<br/>
                            sourceId: 应用ID<br/>
                            sourceName: 应用名称<br/>
                            key: 授权码<br/>
                            startTime: 授权开始时间 <br/>
                            endTime: 授权结束时间 <br/>
                            userCode: 调阅的患者ID<br/>
                            documentCode: 文档编码<br/>
                            fromId: 文档的来源应用ID<br/>
                        </div>
                        <el-input
                            v-model="form.watermarkTemplate"
                            placeholder="请输入水印模板配置"
                            type="textarea"
                        />
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="颜色">
                    <el-color-picker v-model="form.color" show-alpha/>
                </el-form-item>
                <el-form-item label="水平文字间隔" label-width="100px">
                    <el-slider v-model="form.horizontalInterval" :min="1"/>
                </el-form-item>
                <el-form-item label="垂直文字间隔" label-width="100px">
                    <el-slider v-model="form.verticalInterval" :min="1"/>
                </el-form-item>
                <el-form-item label="文字大小" label-width="100px">
                    <el-slider v-model="form.size" :min="1"/>
                </el-form-item>
                <el-form-item label="斜率" label-width="100px">
                    <el-slider v-model="form.rate" :min="1"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reviewWatermark">预 览</el-button>
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

        <div style="margin-bottom: 8px">
            <el-button :loading="loading" icon="el-icon-search" type="success" @click="getList">刷新</el-button>
            <el-button icon="el-icon-circle-plus-outline" type="primary" @click="add">新增</el-button>
            <el-button :disabled="single" icon="el-icon-edit" type="primary" @click="update">修改</el-button>
            <el-button :disabled="multiple" icon="el-icon-delete" type="danger" @click="deleteApp">删除</el-button>
        </div>
        <el-table ref="multipleTable"
                  v-loading="loading" :data="list"
                  border stripe tooltip-effect="light"
                  @row-click="handleRowClick"
                  @selection-change="handleSelectionChange"
        >
            <el-table-column align="center" type="selection" width="55"/>
            <el-table-column label="应用ID" prop="sourceId" show-overflow-tooltip/>
            <el-table-column label="应用名称" prop="sourceName" show-overflow-tooltip/>
            <el-table-column label="授权key" prop="key" show-overflow-tooltip/>
            <el-table-column label="授权开始时间" prop="startTime" show-overflow-tooltip/>
            <el-table-column label="授权结束时间" prop="endTime" show-overflow-tooltip/>
            <el-table-column align="center" label="启用状态" prop="status" width="100">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status"
                               :active-value="1"
                               :inactive-value="0"
                               :loading="scope.row.loading"
                               active-color="#13ce66"
                               @change="validChange(scope.row)"
                    />
                </template>
            </el-table-column>
        </el-table>

    </div>
</template>

<script>

import { addApp, getAppList, updateApp, removeApp } from '@/api/document/app'
import WindowUtil from '@/utils/document/WindowUtil'
import * as QueryString from 'querystring'

export default {
    name: 'Authorization',
    data() {
        return {
            //弹出层标题
            title: '',
            //打开和关闭弹出层
            open: false,
            loading: false,
            list: [],
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            //表单参数
            form: {},
            rules: {
                sourceId: [{ required: true, message: '应用ID不能为空', trigger: 'blur' }],
                sourceName: [{ required: true, message: '应用名称不能为空', trigger: 'blur' }]
            },
            submitLoading: false
        }
    },
    created() {
        this.getList()
    },
    methods: {
        // 水印预览
        reviewWatermark() {
            let sourceUrl = `${process.env.VUE_APP_REQUEST}/view/watermark/review?`
            let obj = {}
            if (this.form.color) {
                let color = this.colorParse(this.form.color)
                obj.color = color.color
                obj.fillOpacity = color.fillOpacity
            }
            obj.horizontalInterval = this.form.horizontalInterval
            obj.verticalInterval = this.form.verticalInterval
            obj.rate = this.form.rate
            obj.size = this.form.size
            if (this.form.watermarkTemplate) {
                obj.text = this.form.watermarkTemplate
            }
            let s = QueryString.stringify(obj)
            WindowUtil.openWindow(840, window.screen.height - 150, sourceUrl + s, '水印预览')
        },
        // 解析颜色
        colorParse(color) {
            let start = color.indexOf('(')
            let end = color.indexOf(')')
            let s = color.substring(start + 1, end)
            let arr = s.split(',')
            return {
                color: `${arr[0].trim()},${arr[1].trim()},${arr[2].trim()}`,
                fillOpacity: arr[3].trim()
            }
        },
        // 颜色格式化
        colorStringify(color, fillOpacity) {
            return `rgba(${color.split(',').join(', ')}, ${fillOpacity})`
        },
        //表单取消
        cancel() {
            this.open = false
        },
        //表单重置
        reset() {
            this.form = {
                status: 1,
                watermarkStatus: 1,
                color: 'rgba(140, 140, 140, 0.4)',
                horizontalInterval: 30,
                verticalInterval: 40,
                size: 20,
                rate: 20
            }
        },
        //表单提交
        submitForm() {
            console.log(this.form)
            let color = this.colorParse(this.form.color)
            console.log(color)
            console.log(this.colorStringify(color.color, color.fillOpacity))
            this.$refs.form.validate(valid => {
                if (valid) {
                    let obj = {}
                    if (this.form.color) {
                        let color = this.colorParse(this.form.color)
                        obj.color = color.color
                        obj.fillOpacity = color.fillOpacity
                    }
                    obj.horizontalInterval = this.form.horizontalInterval
                    obj.verticalInterval = this.form.verticalInterval
                    obj.rate = this.form.rate
                    obj.size = this.form.size
                    this.submitLoading = true
                    if (this.title === '添加应用') {
                        addApp({
                            ...this.form,
                            watermarkConfig: JSON.stringify(obj)
                        }).then(res => {
                            if (res.code === 200) {
                                this.$message.success('添加成功')
                                this.open = false
                                this.getList()
                            }
                        }).finally(_=>{
                            this.submitLoading = false
                        })
                    } else {
                        updateApp({
                            ...this.form,
                            watermarkConfig: JSON.stringify(obj)
                        }).then(res => {
                            if (res.code === 200) {
                                this.$message.success('修改成功')
                                this.open = false
                                this.getList()
                            }
                        }).finally(_=>{
                            this.submitLoading = false
                        })
                    }
                }
            })
        },
        //新增app
        add() {
            this.reset()
            this.open = true
            this.title = '添加应用'
        },
        //修改app
        update() {
            let id = this.ids[0]
            const data = this.list.find(item => item.sourceId === id)
            console.log(data)
            if (data) {
                const watermarkConfig = JSON.parse(data.watermarkConfig)
                this.form = {
                    ...data,
                    color: this.colorStringify(watermarkConfig.color, watermarkConfig.fillOpacity),
                    horizontalInterval: watermarkConfig.horizontalInterval,
                    verticalInterval: watermarkConfig.verticalInterval,
                    rate: watermarkConfig.rate,
                    size: watermarkConfig.size
                }
                this.open = true
                this.title = '修改应用'
            }
        },
        //删除app
        deleteApp() {
            this.$confirm(
                `是否删除应用 ${this.ids.join(',')} ?`,
                '应用删除',
                {
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            removeApp(this.ids.join(',')).then(res => {
                                if (res.code === 200) {
                                    this.$message.success('删除成功')
                                    done()
                                    this.getList()
                                }
                            }).finally(_ => {
                                instance.confirmButtonLoading = false
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
            removeApp(this.ids.join(','))
        },
        getList() {
            this.loading = true
            getAppList().then(res => {
                if (res.code === 200) {
                    this.list = res.data
                    this.ids = []
                }
            }).finally(_ => {
                this.loading = false
            })
        },
        handleRowClick(row, column, event) {
            this.$refs.multipleTable.toggleRowSelection(row)
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.sourceId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        validChange(row) {
            row.loading = true
            updateApp({
                sourceId: row.sourceId,
                status: row.status
            }).then(res => {
                if (res.code === 200) {
                    this.$message.success('修改成功')
                } else {
                    this.$message.error('修改失败')
                    if (row.status === 1) {
                        row.status = 0
                    } else {
                        row.status = 1
                    }
                }
            }).finally(_ => {
                row.loading = false
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.line {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
