<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-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  @click="auditfunction(record)">审核</a>
            </template>
        </s-table>

        <!--编辑----弹框-->
        <a-modal :title="titleName" :visible="modifyvisible" @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="活动封面图片">
                    <van-image :src="this.modifyForm.imageUrl"></van-image>
                </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-modal
            title="审核"
            :visible="setAbnormal"
            @ok="setAbnormalOk"
            @cancel="setAbnormalCancel"
            html-type="submit"
            width="512px"
        >
          <a-row :gutter="24" style="text-align: right">
            <a-col :md="12" :sm="12">
              <a-radio-group v-model="setAbnormalStr.status">
                <a-radio :value="1">
                  通过
                </a-radio>
                <a-radio :value="2">
                  不通过
                </a-radio>
              </a-radio-group>
              <a-input type="hidden" placeholder="获取id" v-model="setAbnormalStr.activityId"></a-input>

            </a-col>
          </a-row>
        </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, auditActivity,uploadImg} from "../../../api/school-center/activity/activityAPI"
    import {cloneObject} from '@/utils/util';
    import { initSubstName} from "../../../api/school-center/userManager/newUserAPI";
    export default {
        name: "activity",
        components: {
            STable,
        },
        data: function () {
            return {
                emptyText: {emptyText: '暂无数据'},
                previewVisible: false,
                previewImage: '',
                subNames: [],
                setAbnormal: false,
                setAbnormalStr: {},
                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: '',
                },
                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"},
                    {
                        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,
                        status: '0'  // 未审核状态
                    }
                    //表示
                    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:{
            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;
            },
            auditfunction(data) {
              this.setAbnormalStr.activityId = data.id;
              this.setAbnormal = true;
            },
            setAbnormalCancel() {
              this.setAbnormalStr.activityId = '';
              this.setAbnormalStr.status = '';
              this.setAbnormal = false;
            },
            setAbnormalOk() {
              auditActivity(this.setAbnormalStr).then(res => {
                if (res.state == 'success') {
                  this.$message.success('审核成功！',5);
                }else{
                  this.$message.error(res.msg, 10);
                }
              });
              this.setAbnormal = false;
            },
            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.imageUrl,
                  range: data.range,
                  sort:data.sort,
                })
              },0)
              this.modifyForm.range = data.range;
              this.modifyForm.imageUrl = data.imageUrl;
              this.customimg="./img/custom"+data.serviceQrcode
              this.modifyvisible=true;

            },
            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>
