<template>
    <div class="flex-container">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <!-- 搜索区域 -->
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :md="4" :sm="8">
                        <a-form-item  label="活动标题：">
                            <a-input  placeholder="活动标题" v-model="queryParam.title"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col :md="3" :sm="6">
                        <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}" label="活动类型">
                        <a-select placeholder="请选择" v-model="queryParam.activityType">
                                <a-select-option key="">请选择</a-select-option>
                                <a-select-option key="个人活动">个人活动</a-select-option>
                                <a-select-option key="团队活动">团队活动</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="3" :sm="6">
                        <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}" label="活动小类">
                            <a-select placeholder="请选择" v-model="queryParam.subclass">
                                <a-select-option key="">请选择</a-select-option>
                                <a-select-option key="部长考核">部长考核</a-select-option>
                                <a-select-option key="前置营销">前置营销</a-select-option>
                                <a-select-option key="线上活动">线上活动</a-select-option>
                                <a-select-option key="线下活动">线下活动</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <span class="table-page-search-submitButtons" style="float: left; overflow: hidden;">
                        <a-col :md="6" :sm="24">
                            <a-button @click="search()" type="primary">查询</a-button>
                             <a-divider type="vertical"/>
                            <a-button @click="add()" type="primary">添加</a-button>
                        </a-col>
                    </span>
                </a-row>
            </a-form>
           </div>

        <!--列表-->
        <s-table  :locale="emptyText" :columns="columns" :data="rowdata" bordered ref="table" size="small" class="flex-filling">
            <template slot="imageUrl" slot-scope="text">
                <img style="width: 20%" :src="apis + text" @click="imgClick(text)">
            </template>
            <template slot="operation" slot-scope="text,record">
                <a  @click="modifyfunction(record)">编辑</a>
                <a-divider type="vertical"/>
                    <a-popconfirm title="是否要删除此行？" @confirm="deleteActivity(record.id)">
                        <a>删除</a>
                    </a-popconfirm>
                <a-divider type="vertical"/>
            </template>
        </s-table>

        <!--编辑----弹框-->
        <a-modal :title="titleName" :visible="modifyvisible"  @ok="createfunctionOk" @cancel="createfunctionCancel" html-type="submit" width="840px">
            <a-form :form="Formtable">

                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动标题">
                    <a-input placeholder="活动标题" v-decorator="[ 'title', {rules: [{ required: true, message: '活动标题不能为空！' ,whitespace:true}]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动详情">
                    <a-input placeholder="活动详情" v-decorator="[ 'desc', {rules: [{ required: true, message: '活动详情不能为空！' ,whitespace:true}]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动积分">
                    <a-input placeholder="活动积分" v-decorator="[ 'integral', {rules: [{ required: false, type:'number', message: '活动积分不能为空！' ,transform:(value)=> {return Number(value)} }]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动类型">
                    <a-radio-group  v-decorator="['activityType', {rules: [{ required: true, message: '活动类型不能为空！'}]} ]">
                        <a-radio value="个人活动">个人活动</a-radio>
                        <a-radio value="团队活动">团队活动</a-radio>
                    </a-radio-group>
                </a-form-item>

                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动小类">
                    <a-select placeholder="请选择" v-decorator="[ 'subclass', {rules: [{ required: true, message: '活动小类不能为空！' ,whitespace:true}]} ]">
                        <a-select-option key="">请选择</a-select-option>
                        <a-select-option key="部长考核">部长考核</a-select-option>
                        <a-select-option key="前置营销">前置营销</a-select-option>
                        <a-select-option key="线上活动">线上活动</a-select-option>
                        <a-select-option key="线下活动">线下活动</a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动封面图片">
                    <a-upload :beforeUpload="uploadPicture" >
                        <a-button> <a-icon type="upload" /> 上传图片 </a-button>
                    </a-upload>
                </a-form-item>

                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="活动范围">
                      <a-select v-model="modifyForm.range">
                        <a-select-option key="全市">全市</a-select-option>
                        <a-select-option v-for="d in subNames" :key="d.value" :value="d.value">{{d.text}}
                        </a-select-option>
                      </a-select>
                </a-form-item>

                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="排序号">
                    <a-input  v-decorator="[ 'sort', {rules: [{ required: true, type:'number', message: '排序号不能为空！' ,whitespace:true,transform:(value)=> {return Number(value)}  }]} ]"></a-input>
                </a-form-item>

            </a-form>
        </a-modal>

        <!----弹框-->
        <a-drawer
                title="活动图片"
                placement="right"
                :closable="false"
                @close="pictureOnClose"
                :visible="visiblepicture"
                width="30%"
        >
            <div >
                <img class="bg-img" :src="imgInfo">
            </div>
        </a-drawer>
    </div>
</template>

<script>
    import STable from '@/components/table';
    import {getList,addActivity,updateActivity,deleteActivity,uploadImg} from "../../../api/school-center/activity/activityAPI"
    import {cloneObject} from '@/utils/util';
    import { initSubstName} from "../../../api/school-center/userManager/newUserAPI";
    import moment from "moment";
    export default {
        name: "activity",
        components: {
            STable,moment
        },
        data: function () {
            return {
                emptyText: {emptyText: '暂无数据'},
                previewVisible: false,
                previewImage: '',
                subNames: [],
                fileList: [
                ],
                apis:'',
                fileid:{},
                brackgroundurl:"manager/ciop/school/schoolManagement/qrcodeUpload",
                // form
                Formtable: this.$form.createForm(this, {name: 'Formtable'}),
                titleName:"",
                modifyForm: {
                    id: '',
                    title: '',
                    desc: '',
                    integral: '',
                    activityType: '',
                    subclass: '',
                    imageUrl: '',
                    range: '',
                    sort: '',
                },
                subNameList: [],
                packageName:[],
                chosePages:[],
                products:[],
                //输入框列表
                queryParam: {
                    title: '',
                    activityType: '',
                    subclass: '',
                    status: '',
                },
                modifyvisible: false,
                visiblepicture: false,
                columns: [
                    {dataIndex: 'title', width: 200, title: '活动标题', align: "center"},
                    {dataIndex: 'desc', width: 200, title: '活动详情', align: "center"},
                    {dataIndex: 'integral', width: 200, title: '活动积分', align: "center"},
                    {dataIndex: 'imageUrl', title: '图片 ', scopedSlots: {customRender: 'imageUrl'},align: 'center'},
                    {dataIndex: 'activityType', width: 200, title: '活动类型', align: "center"},
                    {dataIndex: 'subclass', width: 200, title: '活动小类', align: "center"},
                    {dataIndex: 'sort', width: 200, title: '排序号', align: "center"},
                    {dataIndex: 'creator', width: 200, title: '创建人', align: "center"},
                    {dataIndex: 'createTime', width: 200, title: '创建时间', align: "center",
                      customRender: function (text, record, index) {
                        //text:当前行的值,record: 当前行的数据, index：索引
                        if (text == null) {
                          return "";
                        }
                        return moment(text).format("YYYY-MM-DD HH:mm:ss");
                      },
                    },
                    {
                        dataIndex: 'operation',
                        width: 200,
                        title: '操作',
                        align: "center",
                        scopedSlots: {customRender: 'operation'},
                        fixed: "right"
                    }]
                ,
                rowdata: parameter => {
                    const env = process.env.NODE_ENV; //获取当前环境
                    if(env === 'development'){     //测试环境默认添加前缀
                        this.apis = '/api/';
                    }

                    let params = {
                        pageNo: parameter.pageNo,
                        pageSize: parameter.pageSize
                    }
                    //表示
                    let obj = cloneObject(this.queryParam)
                    return getList(Object.assign(params, obj)).then(res => {
                        let data = {}
                        if (res.state !== 'success') {
                            this.emptyText.emptyText = '查询失败！'
                            this.$message.error("查询失败！", 5);
                            data = {
                                data: [],
                                pageSize: parameter.pageSize,
                                pageNo: 1,
                                totalCount: 0
                            }
                        } else {
                            if (res.data.records.length==0){
                                return data
                            }
                            data = {
                                data: res.data.records,
                                pageSize: parameter.pageSize,
                                pageNo: parameter.pageNo,
                                totalCount: res.data.total
                            }
                        }
                        return data
                    })
                }
            }
        },
        mounted() {
          this.initSubstName();
        },
        methods:{
            // getuuid() {
            //     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            //         var r = Math.random() * 16 | 0,
            //             v = c == 'x' ? r : (r & 0x3 | 0x8);
            //         return v.toString(16);
            //     });
            // },
            // baseuploadUrl(){
            //     const env = process.env.NODE_ENV; //获取当前环境
            //     let apis = "/";
            //     if(env === 'development'){     //测试环境默认添加前缀
            //         apis = '/api/';
            //     }
            //     return apis
            // },
            // uploadUrl(){
            //     return this.baseuploadUrl() + this.brackgroundurl
            // }
            // ,
            // //背景图
            // handleCancel() {
            //     this.previewVisible = false;
            // },
            // handlePreview(file) {
            //     this.previewImage = file.url || file.thumbUrl;
            //     this.previewVisible = true;
            // },
            // handleChange(obj) {
            //     if (this.fileList.length==2){
            //         this.fileList.splice(0,1)
            //     }else{
            //         this.fileList = obj.fileList;
            //     }
            //
            // },
            deleteActivity(id){
                let params = {};
                params.id = id;

                deleteActivity(params).then(res=>{
                    if (res.state=="success"){
                        this.$message.success(res.data ? res.data : '删除成功！', 5);
                        this.search();
                        return null
                    }
                    this.$message.error(res.data ? res.data : '删除失败！', 5);
                })
            },
            search() {
                this.$refs.table.refresh({search: true})
            },
            add(){
                this.titleName="添加"
                this.modifyForm.id = '';
                setTimeout(()=>{
                    this.Formtable.setFieldsValue({
                        id: '',
                        title: '',
                        desc: '',
                        integral: '',
                        activityType: '',
                        subclass: '',
                        imageUrl: '',
                        range: '',
                        sort: '666',
                    })
                },0)
                this.modifyvisible=true;
            },
            modifyfunction(data){
                //初始化
                this.titleName="编辑"
                this.modifyForm.id = data.id

                setTimeout(()=>{
                    this.Formtable.setFieldsValue({
                        title: data.title,
                        desc: data.desc,
                        integral: data.integral,
                        activityType: data.activityType,
                        subclass: data.subclass,
                        imageUrl: data.imgageUrl,
                        range: data.range,
                        sort:data.sort,
                    })
                },0)
                this.modifyForm.range = data.range;

                this.customimg="./img/custom"+data.serviceQrcode
                this.modifyvisible=true;
            },
            //提交表单
            createfunctionOk(){
                this.Formtable.validateFields(['title', 'desc',"integral","activityType", 'subclass', 'sort',"range" ], {force: true}, (err, values)=>{
                    if (!err){
                        this.modifyForm.title=values.title
                        this.modifyForm.desc=values.desc
                        this.modifyForm.integral=values.integral
                        this.modifyForm.activityType=values.activityType
                        this.modifyForm.subclass=values.subclass
                        this.modifyForm.sort=values.sort

                        this.chosePages.forEach(value => {
                            if (value!=undefined){
                                this.modifyForm.chosePages=value+","+this.modifyForm.chosePages
                            }
                        })

                        //插入数据
                        if (this.modifyForm.id==""){
                            for (let key in this.modifyForm) {
                                if (this.modifyForm[key]==undefined){
                                    this.modifyForm[key]=""
                                }
                            }
                            addActivity(this.modifyForm).then(res=>{
                                if (res.state=="success") {
                                    this.$message.success(res.data ? res.data : '添加成功！', 5);
                                    this.search();
                                    this.modifyvisible=false
                                    return null;
                                }
                                this.$message.error(res.data ? res.data : '添加失败！', 5);
                            })
                            return null;
                        }
                        //修改数据
                        updateActivity(this.modifyForm).then(res=>{
                            if (res.state=="success") {
                                this.$message.success(res.data ? res.data : '修改成功！', 5);
                                this.search();
                                this.modifyvisible=false
                                return null;
                            }
                            this.$message.error(res.data ? res.data : '修改失败！', 5);
                        })
                    }
                })
            },
            createfunctionCancel(){
                this.Formtable.setFieldsValue({
                    id: '',
                    title: '',
                    desc: '',
                    integral: '',
                    activityType: '',
                    subclass: '',
                    imageUrl: '',
                    range: '',
                    sort: '',
                })
                this.fileList=[]
                this.modifyForm.id=""
                this.modifyForm.range = ""
                this.modifyForm.chosePages=""
                this.chosePages.splice(0,this.chosePages.length)
                this.modifyvisible=false;
            },
            initSubstName() {
                initSubstName().then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.subName === 'null')
                              return;
                            this.subNames.push({
                              value: r.subName,
                              text: r.subName
                            })
                        })
                    }
                })
            },
            uploadPicture(file) {
                let fileSize = file.size/1024/1024
                console.log(fileSize)
                if(fileSize > this.pictureSize){
                    this.$message.error('上传失败！图片大小不能超过'+this.pictureSize+'M',5);
                    return new Promise(resolve => {
                        console.log(resolve);
                    })
                }else {
                    return new Promise(resolve => {
                        console.log(resolve);
                        const reader = new FileReader();
                        reader.readAsDataURL(file);
                        reader.onload = () => {
                            const img = document.createElement('img');
                            img.src = reader.result;
                            img.onload = () => {
                                const  limitWidth = arguments[2] ? arguments[2] : 640;
                                const  width = img.width > limitWidth ? limitWidth : img.width;
                                const height = img.width > limitWidth ? parseInt((img.height * limitWidth) / img.width) : img.height;
                                const canvas = document.createElement('canvas');
                                const  ctx = canvas.getContext('2d');
                                canvas.width = width
                                canvas.height = height
                                ctx.fillStyle = '#fff'
                                ctx.fillRect(0,0,canvas.width,canvas.height)
                                ctx.drawImage(img,0,0,width,height)
                                const picture = canvas.toDataURL('image/jpeg')
                                console.log(picture.length)
                                return uploadImg({picture}).then(res => {
                                    if(res == 'error'){
                                        this.$message.error('上传失败！',5);
                                    }
                                    if(res.state == 'success'){
                                        this.modifyForm.imageUrl = res.data;

                                        this.$message.success('上传成功',5);
                                    }
                                })
                            };
                        };
                    });
                }
            },
            imgClick(res){
                this.imgInfo=this.apis + res
                this.visiblepicture=true
            },
            pictureOnClose() {
                this.imgInfo=''
                this.visiblepicture = false;
            },
        }
    }
</script>

<style scoped>

</style>
