<template>
    <div class="flex-container">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <!-- 搜索区域 -->
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :md="6" :sm="12">
                        <a-form-item  label="套餐名称">
                            <a-input  placeholder="套餐名称" v-model="queryParam.name"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="12">
                      <a-form-item  label="标准月租">
                        <a-input  placeholder="标准月租" v-model="queryParam.monthFee"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="12">
                      <a-form-item  label="流量">
                        <a-input  placeholder="流量" v-model="queryParam.flow"></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="12">
                      <a-form-item  label="语音">
                        <a-input  placeholder="语音" v-model="queryParam.voice"></a-input>
                      </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-divider type="vertical"/>
                            <a-button @click="batchDown()" type="primary">批量下架</a-button>
                        </a-col>
                    </span>
                </a-row>
            </a-form>
        </div>

        <!--列表-->
        <s-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :columns="columns" :data="rowdata" bordered ref="table" size="small" class="flex-filling"  :locale="emptyText">
            <template slot="operation" slot-scope="text,record">
                <a @click="modifyfunction(record)">编辑</a>
                <a-divider type="vertical"/>
                <a-popconfirm title="是否删除？" @confirm="delet(record.id)">
                    <a>删除</a>
                </a-popconfirm>
            </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="[ 'packageName', {rules: [{ required: true, message: '套餐名称不能为空！' ,whitespace:true}]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="套餐全称">
                    <a-auto-complete placeholder="套餐全称" v-decorator="[ 'name', {rules: [{ required: true, message: '县分不能为空！' ,whitespace:true}]} ]">
                        <template slot="dataSource">
                            <a-select-option v-for="website in autoCompleteResult" :key="website">{{ website }}</a-select-option>
                        </template>
                    </a-auto-complete>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="卡品类型">
                    <a-radio-group  v-decorator="['isXbCard']" :defaultValue="0" @change="onchangeXB">
                        <a-radio :value="0">小白卡</a-radio>
                        <a-radio :value="1">预制卡</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item v-show="modifyForm.isXbCard===0" :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="配送方式">
                    <a-radio-group v-decorator="['isDelivery']" :defaultValue="1">
                        <a-radio :value="1">省仓配送</a-radio>
                        <a-radio :value="2">本地配送</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="月基本费用">
                    <a-input placeholder="月基本费用" v-decorator="[ 'monthFee', {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="[ 'flow', {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="[ 'voice', {rules: [{ required: true, message: '语音不能为空！' ,whitespace:true}]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="小白卡套餐id">
                    <a-input placeholder="小白卡套餐id" v-decorator="[ 'xbId', {rules: [{ required: true, message: '小白卡套餐id不能为空！' ,whitespace:true}]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="温馨提示">
                    <a-input placeholder="温馨提示" v-decorator="[ 'warmTip']"></a-input>
                    <img v-bind:src="imgUrl" width="50px" height="100px" @click="showDrawer"/>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="简介">
                    <a-input placeholder="简介" v-decorator="[ 'explains', {rules: [{ required: true, message: '简介不能为空！' ,whitespace:true}]}]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="背景图">
                    <a-upload
                            ref="upload"
                            :action=uploadUrl
                            listType="picture-card"
                            :fileList="fileList"
                            :headers="header"
                            @preview="handlePreview"
                            @change="handleChange"
                            :data="fileid"
                            accept=".jpg">
                        <div>
                            <a-icon type="plus" />
                            <div class="ant-upload-text"> <span v-if="fileList.length==0">上传背景图</span>  <span v-if="fileList.length>0">更换背景图</span>  </div>
                        </div>
                    </a-upload>
                    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                        <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                </a-form-item>
                <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="小图">
                    <a-upload
                            ref="xiaoupload"
                            :action=xiaotuuploadUrl
                            listType="picture-card"
                            :fileList="fileListxiaotu"
                            :headers="header"
                            @preview="handlePreviewxiaotu"
                            @change="handleChangexiaotu"
                            :data="fileid"
                            accept=".png">
                        <div>
                            <a-icon type="plus" />
                            <div class="ant-upload-text"> <span v-if="fileListxiaotu.length==0">上传小图</span>  <span v-if="fileListxiaotu.length>0">更换小图</span>  </div>
                        </div>
                    </a-upload>
                    <a-modal :visible="previewVisiblexiaotu" :footer="null" @cancel="handleCancelxiaotu">
                        <img alt="example" style="width: 100%" :src="previewImagexiaotu" />
                    </a-modal>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-drawer
            title="温馨提示"
            placement="right"
            :closable="false"
            :visible="wxtsVisible"
            width="400px"
            @close="onClose">
          <img v-bind:src='imgUrl' width='300px' height='600px'/>
        </a-drawer>
    </div>
</template>

<script>
    import Vue from 'vue'
    import { ACCESS_TOKEN } from "@/store/mutation-types"
    import STable from '@/components/table';
    import {findByList,modify,insert,packageAllList,delet, batchUpdate} from "@/api/school-center/packageManagementAPI"
    import {cloneObject} from '@/utils/util';
    export default {
        name: "package",
        components: {
            STable,
        },
        data: function () {
            return {
              radioValue: 0,
                emptyText: {emptyText: '暂无数据'},
                header:{
                    "Authorization":Vue.ls.get(ACCESS_TOKEN)
                },
                wxtsVisible: false,
                previewVisible: false,
                previewImage: '',
                imgUrl: '/images/wxts.png',
                fileList: [
                ],
                selectedRowKeys: [],
                previewVisiblexiaotu: false,
                previewImagexiaotu: '',
                fileListxiaotu:[],
                fileid:{},
                brackgroundurl:"manager/ciop/packageManagement/package/backgroundUpload",
                xiaotuurl:"manager/ciop/packageManagement/package/xiaotuUpload",
                Formtable: this.$form.createForm(this, {name: 'Formtable'}),
                //输入框列表
                autoCompleteResult:[],
                modifyForm: {
                    id:"",
                    packageName:"",
                    name:"",
                    isXbCard:1,
                    isDelivery:"",
                    monthFee:"",
                    flow:"",
                    voice:"",
                    xbId:"",
                    warmTip:"",
                    explains:"",
                    smallImgBase64: "",
                    backgroundBase64: "",
                },
                queryParam: {
                    name: '',
                    monthFee: '',
                    flow: '',
                    voice:''
                },
                modifyvisible:false,
                titleName:"",
                columns: [
                    {dataIndex: 'packageName', width: 200, title: '套餐名称', align: "center"},
                    {dataIndex: 'monthFee', width: 200, title: '标准月租', align: "center"},
                    {dataIndex: 'flow', width: 200, title: '流量', align: "center"},
                    {dataIndex: 'voice', width: 200, title: '语音', align: "center"},
                    {
                        dataIndex: 'operation',
                        width: 100,
                        title: '操作',
                        align: "center",
                        scopedSlots: {customRender: 'operation'},
                        fixed: "right"
                    }
                ],
                rowdata: parameter => {
                    let params = {
                        pageNo: parameter.pageNo,
                        pageSize: parameter.pageSize
                    }
                    //表示
                    let obj = cloneObject(this.queryParam)
                    return findByList(Object.assign(params,obj)).then(res => {
                        let data = {}
                        if (res.state !== 'success') {
                            this.$message.error("查询失败！", 5);
                            this.emptyText.emptyText = '查询失败！'
                            data = {
                                data: [],
                                pageSize: parameter.pageSize,
                                pageNo: 1,
                                totalCount: 0
                            }
                        } else {
                            data = {
                                data: res.data.records,
                                pageSize: parameter.pageSize,
                                pageNo: parameter.pageNo,
                                totalCount: res.data.total
                            }
                        }
                        return data
                    })
                }
            }
        },
        methods:{
            showDrawer() {
              this.wxtsVisible = true;
            },
            onClose() {
              this.wxtsVisible = false;
            },
            onSelectChange(selectedRowKeys) {
              this.selectedRowKeys = selectedRowKeys;
            },
            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
            },
            xiaotuuploadUrl(){
                return this.baseuploadUrl() + this.xiaotuurl
            },
            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;
                }

            },
            //小图
            handleCancelxiaotu() {
                this.previewVisiblexiaotu = false;
            },
            handlePreviewxiaotu(file) {
                this.previewImagexiaotu = file.url || file.thumbUrl;
                this.previewVisiblexiaotu = true;
            },
            handleChangexiaotu(obj) {
                console.log(obj);
                if (this.fileListxiaotu.length==2){
                    this.fileListxiaotu.splice(0,1)
                }else{
                    this.fileListxiaotu = obj.fileList;
                }

            },
            search() {
                this.$refs.table.refresh({search: true})
            },
            delet(id){
                let parent={
                    id:id
                }
                delet(parent).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);
                })
            },
            add(){
                this.fileid={id:""}
                this.modifyForm.id=""
                this.titleName="添加"
                this.modifyForm.isXbCard = 0
                packageAllList().then(res=>{
                    if (res.state=="success"){
                        this.autoCompleteResult=res.data
                    }
                })
                setTimeout(()=>{this.Formtable.setFieldsValue({isXbCard:0,})},0)
                this.modifyvisible=true
            },
            modifyfunction(data){
              console.log(data)
                this.modifyForm.id=data.id
                this.fileid={
                    id:data.id
                }

                if (!(data.advImg == null || data.advImg=="")) {
                  let url = this.baseuploadUrl()+"app/ciop"+data.advImg.replace("enclosure","ciop")
                    //下载图片浏览
                    this.fileList.push({
                        uid: this.getuuid(),
                        name: '找不到图片',
                        status: 'done',
                        url: url,
                    })
                }

                //下载图片浏览
                if (!(data.logo == null || data.logo == "")) {
                    let xiaotuurl = this.baseuploadUrl() +"app/ciop"+ data.logo.replace("enclosure","ciop")
                    this.fileListxiaotu.push({
                        uid: this.getuuid(),
                        name: '找不到图片',
                        status: 'done',
                        url: xiaotuurl,
                    })
                }
                // 判断配送方式是否为空
                if (data.isDelivery == null) {
                  data.isDelivery = "";
                }
                this.titleName="编辑"
                setTimeout(()=>{
                    this.Formtable.setFieldsValue({
                        packageName:data.packageName,
                        name:data.name,
                        isXbCard:data.isXbCard,
                        isDelivery:data.isDelivery,
                        monthFee:data.monthFee,
                        flow:data.flow,
                        voice:data.voice,
                        xbId:data.xbId,
                        warmTip:data.warmTip,
                        explains:data.explains,
                    })
                },0)
                packageAllList().then(res=>{
                    if (res.state=="success"){
                        this.autoCompleteResult=res.data
                    }
                })
                this.modifyForm.isXbCard = data.isXbCard
                this.modifyvisible=true
            },
            onchangeXB(data){
              this.modifyForm.isXbCard = data.target.value
            },
            //提交表单
            createfunctionOk(){
                this.Formtable.validateFields(['packageName', 'name',"isXbCard","isDelivery","monthFee", 'flow',"voice", 'xbId',"warmTip" ,'explains'], {force: true}, (err, values)=>{
                    if (!err){
                        this.modifyForm.packageName=values.packageName
                        this.modifyForm.name=values.name
                        this.modifyForm.isXbCard=values.isXbCard
                        this.modifyForm.isDelivery=values.isDelivery
                        this.modifyForm.monthFee=values.monthFee
                        this.modifyForm.flow=values.flow
                        this.modifyForm.voice=values.voice
                        this.modifyForm.xbId=values.xbId
                        this.modifyForm.warmTip=values.warmTip
                        this.modifyForm.explains=values.explains
                        console.log(this.fileList);
                        console.log(this.fileListxiaotu);
                        if (this.previewImage != undefined) {
                          this.modifyForm.backgroundBase64 = this.previewImage;
                        }
                        if (this.previewImagexiaotu != undefined) {
                          this.modifyForm.smallImgBase64 = this.previewImagexiaotu;
                        }
                        //插入数据
                        if (this.modifyForm.id==""){
                            insert(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;
                        }
                        //修改数据
                        modify(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.fileList=[]
                this.fileListxiaotu=[]
                this.modifyvisible=false
                this.autoCompleteResult=[]
                this.Formtable.setFieldsValue({
                    packageName:"",
                    name:"",
                    isXbCard:0,
                    isDelivery:"",
                    monthFee:"",
                    flow:"",
                    voice:"",
                    xbId:"",
                    warmTip:"",
                    explains:"",
                })
            },
            batchDown() {
                // 批量下架产品
              const ids = this.selectedRowKeys;
              batchUpdate({ids: ids}).then(res => {
                console.log(res);
                if (res.state=="success") {
                  this.$message.success(res.data ? res.data : '下架成功！', 5);
                }else{
                  this.$message.error(res.data ? res.data : '下架失败！', 5);
                }
              })
            }
        }

        }
</script>

<style scoped>

</style>
