<template>
    <div class="full-height full-width column" ref="memberListRef">
        <div class="text-dark text-weight-bolder">水印设置</div>
        <div class="borders-light q-pa-lg rounded q-mt-xl row" style="width:600px;">
            <div class="col">
                <div class="text-dark text-weight-bold">行程水印设置</div>
                <div class="text-grey-8 f14 q-mt-md">水印开启后，可以有效保障团队/企业的行程安全</div>
            </div>
            <div>
                <el-button type="info" class="ppt-button text-weight-bolder"
                    @click="showFormHandler">编辑水印</el-button>
                <div class="text-small q-mt-sm text-right"
                    :class="{ 'text-negative': !wmModel || wmModel.status == 0, 'text-secony': wmModel && wmModel.status == 1 }">当前{{
                        (!wmModel || wmModel.status == 0) ? '未启用' : '已启用' }}水印</div>
            </div>
        </div>
    </div>
    <el-dialog v-model="wmFormVisible" style="width:560px;" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
        <template #title>
            <div class="row items-center">
                <div class="text-dark col" style="font-size: 18px;">水印信息设置</div>
                <div>
                    <span class="text-small q-mr-md">启用水印</span>
                    <el-switch v-model="model.Status" class="short-switch" />
                </div>
            </div>
        </template>
        <main>
            <el-form ref="wmFormRef" :model="model" label-position="top" size="large" :rules="rules" :disabled="submitLoading || !model.Status">
                <div class="row">
                    <el-form-item label="水印内容" prop="MakerType" class="col q-mr-lg">
                        <el-radio-group v-model="model.MakerType">
                            <el-radio :label="1">文字水印</el-radio>
                            <el-radio :label="2">图片水印</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="文字水印内容" prop="Content" class="col" v-if="model.MakerType == 1">
                        <el-input v-model="model.Content" placeholder="请填写文字水印内容" type="textarea" show-word-limit
                            resize="none" maxlength="20" />
                    </el-form-item>
                    <el-form-item label="图片水印" prop="content" class="col wm-item" v-else>
                        <el-upload drag action="#" :auto-upload="false" class="avatar-upload" accept=".jpg,.png" :show-file-list="false" :on-change="handleChangeMakerImage">
                            <img :src="newMarkerFile" v-if="newMarkerFile" style="height: 100%;object-fit: cover;"/>
                            <div class="full-width full-height column items-center flex-center" v-else>
                                <IconPlus size="36" class="text-dark"></IconPlus>
                            </div>
                            <div class="after-overlayer">上传</div>
                        </el-upload>
                    </el-form-item>
                </div>
                <div class="row" v-if="model.MakerType==1">
                    <el-form-item label="水印颜色" prop="Color" class="col q-mr-lg">
                        <el-color-picker v-model="model.Color" show-alpha size="large" />
                    </el-form-item>
                    <el-form-item label="水印文字大小" prop="ContentSize" class="col">
                        <el-input-number v-model="model.ContentSize" min="12" max="72" step="2" class="col"/>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="密集程度" prop="Density" class="col q-mr-lg">
                        <el-select v-model="model.Density" placeholder="请选择">
                            <el-option label="密集" :value="1" />
                            <el-option label="中等" :value="2" />
                            <el-option label="宽松" :value="3" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="水印角度" prop="Angle" class="col">
                        <el-input-number v-model="model.Angle" min="-180" max="180" step="1" class="col"/>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="影响范围" prop="Range" class="col q-mr-lg">
                        <el-select v-model="model.Range" placeholder="请选择">
                            <el-option label="全部" :value="0" />
                            <el-option label="仅导出" :value="1" />
                            <el-option label="仅设计页面" :value="2" />
                        </el-select>
                    </el-form-item>
                    <div class="col"></div>
                </div>
            </el-form>
        </main>
        <template #footer>
            <el-button size="large" class="ppt-button" @click="()=>wmFormVisible=false">关闭设置</el-button>
            <el-button size="large" type="primary" class="ppt-button" @click="saveWaterMarker(wmFormRef)">保存设置</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import CryptoJS from 'crypto-js'
import { ApiResult } from "@/configs/axios";
import SettingService from "@/services/SettingService";
import { useUserStore } from "@/store";
import AliyunUpload from "@/utils/upload/aliyun";
import { ElLoading, ElMessage, FormInstance, FormRules } from "element-plus";
import { storeToRefs } from "pinia";
import { reactive, ref } from "vue";

interface RuleForm {
    Content: string
    Color: string
    MakerType: string
    ContentSize: string
    Density: string
    Angle: string
    Range: string
}
const validateColor = (rule: any, value: any, callback: any) => {
    const reg = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
    if (!reg.test(value)) {
        callback(new Error("颜色不正确"))
    } else {
        callback()
    }
}

const {userInfo} = storeToRefs(useUserStore())
const wmFormVisible = ref(false)
const wmModel = ref<any>()
const submitLoading = ref(false)
const model = reactive({
    TId: '',
    MakerType: 1,
    Content: '',
    ContentSize: 12,
    Density: 1,
    Color: '#eeeeee',
    Angle: 20,
    Range: 0,
    Status:true
})
const wmFormRef = ref()
const newMarkerFile = ref<string>('')
const newMarkerSourceFile = ref<any>()

const rules = reactive<FormRules<RuleForm>>({
    Content: [
        { required: true, message: '请添加水印内容', trigger: 'blur' },
        { max: 20, message: '水印内容过长', trigger: 'blur' },
    ],
    Color: [{ required: true, message: '请选择颜色', trigger: 'blur' }],
    ContentSize: [{ required: true, message: '请设置水印大小', trigger: 'blur' }],
    Density: [{ required: true, message: '请设置水印密度', trigger: 'change' }],
    Angle: [{ required: true, message: '请设置水印角度', trigger: 'blur' }],
    Range: [{ required: true, message: '请设置水印显示范围', trigger: 'change' }]
})

const getWaterMaker = async () => {
    const loading = ElLoading.service({ text: '正在加载数据' })

    const response = await SettingService.GetWmAsync()
    if (response.data.resultCode == ApiResult.SUCCESS) {
        wmModel.value = response.data.data
    }

    loading.close()
}
const handleChangeMakerImage=(uploadFile:any, uploadFiles:any)=>{
    const raw = uploadFile.raw
    if(raw.type == 'image/jpeg' || raw.type == 'image/png'){
        if(raw.size<=1024*1024*2){
            var reader = new FileReader();
            reader.readAsDataURL(raw);
            reader.onload = () => { 
                newMarkerFile.value = reader.result?.toString()??'';
                newMarkerSourceFile.value = raw
            } 
            reader.onerror = function(err) {
                ElMessage.error({message:'图片解析失败，请更换图片'})
            }
        } else ElMessage.error({message:'图片过大，图片不能超过2MB'})
    } else ElMessage.error({message:'错误的图片格式，目前支持jpg/png'})
}
const showFormHandler = () => {
    if(wmModel.value && wmModel.value.id!=''){
        const w = wmModel.value
        model.TId=w.id
        model.MakerType= w.wmtype,
        model.Content= w.content,
        model.ContentSize= w.cz,
        model.Density= w.de,
        model.Color= w.color,
        model.Angle= w.ag,
        model.Range= w.ra,
        model.Status= w.status
        if(model.MakerType==2) {
            newMarkerFile.value = w.content
            model.Content= ''
        }
    }else{
        model.TId=''
        model.MakerType= 1,
        model.Content= '',
        model.ContentSize= 12,
        model.Density= 1,
        model.Color= '#eeeeee',
        model.Angle= 20,
        model.Range= 0,
        model.Status= true
    }
    newMarkerSourceFile.value = null
    submitLoading.value=false
    wmFormVisible.value=true
}
const saveWaterMarker = async (formEl: FormInstance | undefined) => {
    if (!formEl || submitLoading.value) return

    submitLoading.value=true
    await formEl.validate(async (valid) => {
        if(valid){
            if(model.MakerType==2 && newMarkerFile.value==''){
                ElMessage.error({message:'请上传水印图片'})
                return
            }else if(model.MakerType==2 && newMarkerFile.value!=''){
                model.Content = newMarkerFile.value
            }
            if(model.MakerType==2 && newMarkerSourceFile.value){
                await uploadWaterMarkerImage()
            }
            
            const parameters = JSON.parse(JSON.stringify(model))
            parameters.Status = parameters.Status?1:0
            const response = await SettingService.SetWmAsync(parameters)
            if(response.data.resultCode == ApiResult.SUCCESS){
                ElMessage.success({message:'水印更新成功'})
                wmFormVisible.value=false
                getWaterMaker()
            }else{
                ElMessage.error({message:'水印更新失败'})
            }
        }
    })

    submitLoading.value=false
}

const uploadWaterMarkerImage = async ()=>{
    if(newMarkerSourceFile.value){
        const url = await AliyunUpload.UploadAsync(newMarkerSourceFile.value,`watermark/${CryptoJS.SHA256(userInfo.value.id)}.${newMarkerSourceFile.value.name.split('.')[1]}`)
        if(url!='') {
            model.Content = `${url}?t=${new Date().getTime().toString()}`
            return
        }
    }
    model.Content
}
getWaterMaker()
</script>

<style>
.el-switch.short-switch .el-switch__core {
    min-width: 35px;
}
.wm-item .avatar-upload{
    width:100%;
    
    position: relative;
    border-radius:8px;
    overflow: hidden;
}
.wm-item .avatar-upload .el-upload-dragger{
    width:100%;
    height: 60px;
    padding: 0px;
    border-radius:8px;
}
.wm-item .after-overlayer{
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0,0,0,.2);
    display: none;
    line-height: 60px;
    font-size: 14px;
    color:#FFF;
    text-align: center;
}
.wm-item:hover .after-overlayer{
    display: block;
}
</style>