<template>
    <div class="giftList flex-display">

        <div class="head">
            <div class="text">

                <div class="head-item">
                    <el-select v-model="params.gameId" placeholder="请选择所属游戏" filterable clearable>
                        <el-option
                                v-for="item in giftGameList"
                                :key="item.gameId"
                                :label="item.gameId + '_' +item.gameName"
                                :value="item.gameId"
                        ></el-option>
                    </el-select>
                </div>

                <div class="head-item" placeholder="请选择创建时间">
                    <el-date-picker
                            v-model="createTime"
                            @change="handelCreateTimeChange"
                            type="datetimerange"
                            :value-format="'yyyy-MM-dd HH:mm:ss'"
                            start-placeholder="日期"
                            end-placeholder="日期"
                            :default-time="['00:00:00', '23:59:59']"
                    ></el-date-picker>
                </div>

                <div class="head-item">
                    <el-select v-model="params.state" placeholder="请选择完成状态">
                        <el-option
                                v-for="item in stateList"
                                :key="item.text"
                                :label="item.text"
                                :value="item.value"
                        ></el-option>
                    </el-select>
                </div>

                <div class="head-item">
                    <el-select v-model="params.keywords" placeholder="请选择礼包类型">
                        <el-option
                                v-for="item in keywordsList"
                                :key="item.text"
                                :label="item.text"
                                :value="item.value"
                        ></el-option>
                    </el-select>
                </div>

            </div>

            <div class="action">
                <el-button plain type="primary" icon="el-icon-search" @click="getGiftLists">搜索</el-button>
                <el-button plain type="success" icon="el-icon-circle-plus-outline" @click="handelClickAdd">新增
                </el-button>
            </div>
        </div>

        <div class="list">
            <el-table :data="giftList.slice((curPage-1)*pageSize,curPage*pageSize)" border stripe :fit="false" height="100%" @sort-change="handelSortChange">
                <el-table-column label="礼包编号" prop="id" width="150" show-overflow-tooltip/>
                <el-table-column label="礼包名称" prop="giftName" width="150" show-overflow-tooltip/>
                <el-table-column label="礼包描述" prop="giftContent" width="150" show-overflow-tooltip/>
                <el-table-column label="所属游戏" prop="gameName" width="150" show-overflow-tooltip/>
                <el-table-column label="领取数量" prop="amount" width="150" show-overflow-tooltip sortable/>
                <el-table-column label="剩余数量" prop="restAmount" width="150" show-overflow-tooltip sortable/>
                <el-table-column label="礼包类型" width="150" show-overflow-tooltip >
                    <template slot-scope="scope">
                        <el-tag>{{convertType(scope.row.keywords)}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="关键字" prop="keywords" width="150" show-overflow-tooltip />
                <el-table-column label="创建时间" prop="createTime" width="150" show-overflow-tooltip sortable="custom"/>
                <el-table-column label="是否开启" prop="state" width="150" show-overflow-tooltip :formatter="states"/>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <div class="headrow">
                            <el-button size="mini" @click="handelGift(scope.row.id)">编辑</el-button>
                            <el-button size="mini" type="danger" @click="handelDelete(scope.row.id)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="page">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    layout="total, sizes, prev, pager, next, jumper"
                    :page-size="pageSize"
                    :current-page="curPage"
                    :pager-count="11"
                    :total="total"
            ></el-pagination>
        </div>

        <el-dialog :title="dialog.title" :visible.sync="dialog.visible" center @close="handelCancel">
            <div class="content">

                <el-form label-width="100px" :rules="rules" :model="giftDto" ref="giftForm">
                    <div class="item" v-if="!isUpdate">
                        <el-form-item label="所属游戏:" prop="gameId">
                        <el-select v-model="giftDto.gameId" placeholder="请选择所属游戏" filterable clearable>
                            <el-option
                                    v-for="item in giftGameList"
                                    :key="item.gameId"
                                    :label="item.gameId + '_' +item.gameName"
                                    :value="item.gameId"
                            ></el-option>
                        </el-select>
                        </el-form-item>
                    </div>

                    <el-form-item label="礼包名:" prop="giftName" >
                        <el-input v-model.trim="giftDto.giftName" placeholder="请输入内容"></el-input>
                    </el-form-item>

                    <el-form-item label="礼包描述:" prop="giftContent" v-if="isUpdate">
                        <el-input v-model.trim="giftDto.giftContent" placeholder="请输入内容"></el-input>
                    </el-form-item>

                    <el-form-item label="礼包码:" prop="giftCode" >
                        <el-input
                                type="textarea"
                                :rows="2"
                                placeholder="请输入内容"
                                v-model="giftDto.giftCode">
                        </el-input>
                    </el-form-item>

                    <div class="code" v-if="isUpdate">
                        <el-button type="primary" size="medium" @click="handelCode">编辑礼包码</el-button>
                    </div>

                    <div class="dis">
                        <el-radio-group v-model="giftDto.display" @change="o">
                            <el-radio :label="0" border >页面展示</el-radio>
                            <el-radio :label="1" border>关键字回复</el-radio>
                        </el-radio-group>
                    </div>

                    <el-form-item label="关键字:" prop="keywords" v-show="giftDto.display === 1">
                        <el-input v-model.trim="giftDto.keywords" placeholder="请输入关键字"></el-input>
                    </el-form-item>

                    <div class="dis" v-show="isUpdate">
                    <template>
                        <el-radio v-model="giftDto.state" :label="1">关闭</el-radio>
                        <el-radio v-model="giftDto.state" :label="0">开启</el-radio>
                    </template>
                    </div>

                    <div class="dis" v-show="giftDto.state == 0 && giftDto.display == 1">
                        <el-checkbox-group v-model="checkList" @change="handelChangeCheckBox">
                            <el-checkbox v-for="item in typeList" :label="item.value" border>{{item.label}}</el-checkbox>
                        </el-checkbox-group>
                    </div>

                </el-form>

            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handelCancel">取 消</el-button>
                <el-button type="primary" @click="handelClickConform">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

    import giftListApi from '@/api/giftList'
    import {getLastDay, formatTime} from '@/utils/util'

    export default {
        name: "giftList",
        data(){
            return {
                createTime:'',
                params:{
                },
                giftList:[],
                giftGameList:[],
                total: 0,
                pageSize: 20,
                curPage: 1,
                isUpdate:false,
                stateList:[
                    {value:0,text:'开启'},
                    {value:1,text:'关闭'},
                    {value:null,text:'全部'}
                ],
                keywordsList:[
                    {value:0,text:'页面展示'},
                    {value:1,text:'关键字回复'},
                    {value:null,text:'全部'}
                ],
                // typeOptions:[
                //     {value:0,text:''}
                //     ],
                dialog:{
                    title:'请添加所属游戏礼包',
                    visible:false
                },
                giftDto:{
                    giftName:'',
                    giftCode:'',
                    giftContent:'',
                    keywords:'',

                },
                dialogs:{
                },
                rules:{
                    gameId:{required:true,message:'请选择游戏',trigger: 'blur'},
                    giftName:{required:true,message:'请输入礼包名',trigger: 'blur'},
                    giftCode:{required:true,message:'请输入礼包码',trigger: 'blur'}
                },
                param:{},
                checkList:[],
                typeList:[
                    {label:'订阅号',value:'subscribe'},
                    {label:'服务号',value:'service'}
                ]
            }
        },
        mounted(){
            this.init()
        },
        methods:{
            /**
             * 初始化
             */
            init(){
                /*let lastDay = getLastDay(3);
                this.createTime = lastDay;
                this.params.createStartTime = lastDay ? formatTime(lastDay[0]) : null;
                this.params.createEndTime = lastDay ? formatTime(lastDay[1]) : null;*/
                this.getGameList();
                this.getGiftLists()
            },
            /**
             * 游戏列表
             */
            getGameList(){
                giftListApi.getGameList().then(res=>{
                    console.log(res)
                    this.giftGameList = this.params.gameId ? res.filter(f=> f.gameId == this.params.gameId) : res.filter(f => f.deleted != 1)
                })
            },
            /**
             * 礼包列表
             */
            getGiftLists(){
                giftListApi.getGiftList(this.params).then(res=>{
                    this.giftList = res.rows;
                    this.giftList.map(m => {
                        if(m.keywords != null && m.keywords !=''){
                            m.display = 1;
                        }
                        else {
                            m.display = 0;
                        }
                    });
                    console.log(this.giftList)
                    this.total = this.giftList.length;
                })
            },
            /**
             * 时间
             */
            handelCreateTimeChange(val) {
                this.params.createStartTime = val ? val[0] : null;
                this.params.createEndTime = val ? val[1] : null;
            },
            handelClickAdd(){
                giftListApi.getGameList().then(res=>{
                    this.giftGameList = this.params.gameId ? res.filter(f=>f.gameId == this.params.gameId) : res.filter(f => f.deleted != 1)
                    this.dialog.visible=true
                })
            },
            /**
             * 确定按钮
             */
            handelClickConform(){

                this.$refs['giftForm'].validate((valid =>{
                    if(valid){
                        if(this.giftDto.giftCode != undefined)
                            this.giftDto.giftCode = (this.giftDto.giftCode).split('\n').join(',')

                        if(this.giftDto.display == 0){
                            this.giftDto.keywords = '';
                        }

                        this.giftDto.type = this.checkList.join(',')

                        //this.giftDto.type.filter(f => f != )

                        this.isUpdate ? giftListApi.updateGift(this.giftDto).then(this.refresh)
                            : giftListApi.addGift(this.giftDto).then(this.refresh)
                    }else{
                        console.log('error submit');
                        return false
                    }
                }))
            },
            /**
             * 刷新
             */
            refresh(){
                this.getGiftLists();
                this.handelCancel()
            },
            /**
             * 取消按钮
             */
            handelCancel(){
                this.$refs['giftForm'].resetFields();
                this.dialog.visible=false;
                this.isUpdate=false;
                this.giftDto = {
                        giftName:'',
                        giftCode:''
                    }
                this.checkList=[]
                this.rules.giftCode={required:true,message:'请输入礼包码',trigger: 'blur'}
            },
            /**
             * 编辑
             * @param id
             */
            handelGift(id){
                this.isUpdate=true;
                giftListApi.getGiftById(id).then(res=> {
                    this.giftDto={
                        id:res.id,
                        gameId:res.gameId,
                        giftName:res.giftName,
                        state:res.state,
                        giftContent:res.giftContent,
                        keywords:res.keywords,

                        oldType:res.type,
                        oldKeywords:res.keywords
                    };

                    if(res.type != '' && res.type != null)
                        this.checkList = res.type.split(',');
                    //this.check = this.checkList;
                    console.log(this.checkList);

                    if(res.keywords != null && res.keywords != '' ){
                        this.giftDto.display = 1;
                    }
                    else
                        this.giftDto.display = 0;

                    let resListForm = 1;
                    let ListForm = Object.assign({},this.giftDto,resListForm);//合并对象
                    this.giftDto = ListForm;


                    this.rules.giftCode='';

                    this.param.giftId=res.id;
                    this.param.gameId=res.gameId;
                    this.dialog.visible=true
                }
                );
            },
            handelDelete(id){
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    giftListApi.deleteGift(id).then(res => {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.refresh()
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            /**
             * 后端排序
             * @param order
             */
            handelSortChange({ prop, order }) {
                console.log(prop);

                let orderBy = prop.replace(/([A-Z])/g,"_$1").toLowerCase() + ':';

                if (order == 'descending') {
                    this.params.orderBy = orderBy + 'desc'
                } else if (order == 'ascending') {
                    this.params.orderBy = orderBy + 'asc'
                } else {
                    this.params.orderBy = null
                }



                // console.log(order)
                // if (order == 'descending') {
                //     this.params.orderBy = 1
                // } else if (order == 'ascending') {
                //     this.params.orderBy = 0
                // } else {
                //     this.params.orderBy = null
                // }
                this.getGiftLists()
            },
            handelCode(){
                this.$router.push({
                    name: "giftCodeList",
                    params:this.param,
                })
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.curPage = val;
            },

            states(row,column) {
                if (row.state === 0) {
                return '开启';
                }
                else if(row.state === 1) {
                    return '关闭'
                }
            },
            convertType(keywords){
                if(keywords !== '' && keywords !== null){
                    return "关键字回复"
                }else
                    return "页面展示"
            },
            handelChangeCheckBox(val){

            },
            o(val){

            }

        }
    }
</script >

<style lang="less" scoped>
    .giftList {

        /deep/ .el-dialog {
            width: 400px;
            .el-select {
                width: 100%;
            }
            .content{
                .dis{
                    text-align:center;
                    margin: 20px 0
                }
                .code{
                    text-align:center;

                }
            }
        }
    }

</style>
