<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.card" style="width: 8rem;"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="8">
                        <a-form-item label="销售状态">
                            <a-select v-model="queryParam.state" @change="getSchoolNames" style="width: 8rem;">
                                <a-select-option key="">--全部--</a-select-option>
                                <a-select-option key="1">未出售</a-select-option>
                                <a-select-option key="2">已出售</a-select-option>
                                <a-select-option key="3">出售中</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="12" v-show="false">
                        <a-form-item label="上架状态">
                            <a-select v-model="queryParam.shelfState" style="width: 15rem;">
                                <a-select-option key="">--全部--</a-select-option>
                                <a-select-option key="1">已上架</a-select-option>
                                <a-select-option key="2">已下架</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="modifyfunction()" type="primary">添加</a-button>
                             <a-divider type="vertical"/>
                             <a-button @click="excelInto()" type="primary">兑换券数据导入</a-button>
                             <a-divider type="vertical"/>
                             <a-button @click="excelOut()" type="primary">兑换券数据导出</a-button>
                        </a-col>
                    </span>
                </a-row>
            </a-form>
        </div>
        <a-modal
                title="批量导入"
                :visible="kpiModifyvisible"
                @ok="createfunctionOk0"
                @cancel="createfunctionCancel0"
                html-type="submit"
                width="400px"
        >
            <a-row :gutter="24">
                <a-col :md="24" :sm="12">
                    <p style="text-align:center">{{ importTile }}</p>
                </a-col>
            </a-row>
            <import-btn :url="importUrl" :responseFun="doPush">
                <a-tooltip placement="topLeft" title="导入文件" arrowPointAtCenter>
                    <a-row :gutter="24">
                        <a-col :md="24" :sm="12">
                            <p>
                                选择文件：
                                <a-button type="primary">选择文件</a-button>
                            </p>
                        </a-col>
                    </a-row>
                </a-tooltip>
            </import-btn>
            <a-row :gutter="24">
                <a-col :md="24" :sm="12">
                    <p v-show="YRYMmoBan">
                        模板下载：
                        <a-button type="primary" @click="downloadMoBan">兑换券信息模板</a-button>
                    </p>
                </a-col>
            </a-row>
            <a-row :gutter="24" :v-show="KDmoBan">
                <a-col :md="24" :sm="12">
                    <p>说明：</p>
                    <p>1.批量导入请严格按照模版进行导入;</p>
                </a-col>
            </a-row>
        </a-modal>
        <!--列表-->
        <s-table :columns="columns" :data="rowdata" bordered ref="table" size="small" class="flex-filling"
                 :locale="emptyText">
            <!--拦截器-->
            <template slot="updateDate" slot-scope="text">
                {{ text | dayjs}}
            </template>
            <!--拦截器-->
            <template slot="validityPeriod" slot-scope="text">
                {{ text | dayjs}}
            </template>
            <!--<template slot="shelfState" slot-scope="text">
                <p v-if="text==1">已上架</p>
                <p v-if="text==2">已下架</p>
                <p v-else=""></p>
            </template>-->
            <template slot="state" slot-scope="text">
                <p v-if="text==1">未售出</p>
                <p v-if="text==2">已售出</p>
                <p v-if="text==3">售出中</p>
                <p v-else=""></p>
            </template>
            <template slot="operation" slot-scope="text,record">
                <span>
                    <a-popconfirm title="确定删除吗" v-if="record.state == 1" @confirm="remove(record,1)">
                        <a>删除</a>
                    </a-popconfirm>
                    <a-popconfirm title="确定恢复删除吗" v-if="record.delFlag == 1" @confirm="remove(record,0)">
                        <a>恢复删除</a>
                    </a-popconfirm>
                </span>
            </template>
        </s-table>
        <!----弹框-->
        <a-modal :title="add ?'添加正则配置': '编辑正则配置'" :visible="modifyvisible" @ok="createfunctionOk"
                 @cancel="createfunctionCancel" html-type="submit" width="1024px">
            <a-form :form="Formtable">
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="兑换券账号：">
                    <a-input placeholder="兑换券账号"
                             v-decorator="[ 'cardNumber', {rules: [{ required: true, message: '兑换券账号不能为空！' }]} ]"/>
                </a-form-item>
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="密码：">
                    <a-input placeholder="密码"
                             v-decorator="[ 'password', {rules: [{ required: true, message: '密码不能为空！' }]}  ]"/>
                </a-form-item>
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="有效截止日期：">
                    <a-date-picker @change="onChange" placeholder="有效截止日期"
                                   v-decorator="[ 'validityPeriod', {rules: [{ required: true, message: '有效截止日期不能为空！' }]} ]"
                                   style="width: 20rem;"/>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
    import STable from '@/components/table';
    import ImportBtn from "../../../components/sysmanage/ImportBtn";
    import {
        yxtCouponList, yxtCouponDelete, yxtCouponInsert, yxtCouponUpdate,
        getSchoolNames, initSubstName, uploadExcel, downloadMoBan
    } from "@/api/school-center/exchangeCouponAPI"
    import {cloneObject, exportFile} from '@/utils/util';
    import Vue from 'vue';
    import {DatetimePicker} from 'vant';
    import moment from "moment";
    import ConstantActivity from "@/constant/ConstantActivity";

    Vue.use(DatetimePicker);

    export default {
        name: "exchangeCoupon",
        components: {
            STable, ImportBtn
        },
        data() {
            return {
                emptyText: {emptyText: '暂无数据'},
                Formtable: this.$form.createForm(this),
                modifyvisible: false,
                kpiModifyvisible: false,
                title: ConstantActivity.title,
                add: true,
                isdisabled: true,
                queryParam: {
                    card: '',
                    state: '',
                    shelfState: '',
                },
                subNames: [],
                schoolNames: [],
                modelData: {
                    id: '',
                    cardNumber: '',
                    password: '',
                    validityPeriod: '',
                    updateDate: '',
                    state: '',
                    shelfState: '',
                },
                columns: [
                    {dataIndex: 'cardNumber', width: 40, title: '兑换券账号'},
                    {dataIndex: 'password', width: 20, title: '密码'},
                    {dataIndex: 'state', width: 20, title: '出售状态 ', scopedSlots: {customRender: 'state'}},
                    /*{dataIndex: 'shelfState', width: 20, title: '上架状态 ', scopedSlots: {customRender: 'shelfState'}},*/
                    {
                        dataIndex: 'validityPeriod',
                        width: 40,
                        title: '有效截止日期',
                        scopedSlots: {customRender: 'validityPeriod'}
                    },
                    {dataIndex: 'updateDate', width: 40, title: '上传时间', scopedSlots: {customRender: 'updateDate'}},
                    {
                        dataIndex: 'operation',
                        width: 30,
                        title: '操作',
                        scopedSlots: {customRender: 'operation'},
                        fixed: "right"
                    }
                ],
                rowdata: parameter => {
                    let params = {
                        pageNo: parameter.pageNo,
                        pageSize: parameter.pageSize
                    }
                    let obj = cloneObject(this.queryParam)
                    //表示
                    return yxtCouponList(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
                    })
                },
                importTile: "",
                importUrl: "",
                YRYMmoBan: true,
            }
        },
        methods: {
            moment,
            onChange(date, dateString) {
                console.log(dateString);
                this.modelData.validityPeriod = dateString;
            },
            excelOut() {
                let params = {
                    pageNo: 1,
                    pageSize: 10
                }
                let obj = cloneObject(this.queryParam)
                let nowdate = moment().format("YYYY-MM-DD");
                //导出
                exportFile(
                    uploadExcel(Object.assign(params, obj)),
                    "兑换券信息" + nowdate + ".xlsx",
                );

            },
            excelInto() {
                this.importTile = "批量导入兑换券信息";
                this.YRYMmoBan = true;
                this.importUrl = "manager/ciop/yxtCoupon/importDate";
                this.kpiModifyvisible = true
            },
            downloadMoBan: function () {
                exportFile(downloadMoBan(), "兑换券信息模板模板.xlsx");
            },
            doPush(res) {
                console.log(res);
                if (!res || !res.response) {
                    this.$message.error("上传文件出错！", 10);
                    return false;
                }
                const response = res.response;
                if (response.state !== "success") {
                    this.$message.error(response.msg ? response.msg : "上传文件出错！", 10);
                    return false;
                }
                this.$message.success("上传成功！" + response.data, 5);
            },
            createfunctionOk0() {
                this.kpiModifyvisible = false;
                this.clearmodel0();
            },
            createfunctionCancel0() {
                this.kpiModifyvisible = false;
                this.clearmodel0();
            },
            clearmodel0() {
                this.importTile = "";
                this.YRYMmoBan = false;
                this.importUrl = "";
            },
            search() {
                this.$refs.table.refresh({search: true})
            },
            remove(date, delFlag) {
                if(delFlag == 1){
                    if(date.state == 2){//
                        this.$message.error("已售出的兑换券不能删除！");
                        return;
                    }else if(date.state == 2){//售出中
                        this.$message.error("售出中的兑换券不能删除！");
                        return;
                    }
                }
                yxtCouponDelete({'id': date.id, 'isdel': delFlag}).then((res) => {
                    if (res.state == "success") {
                        this.$notification.success({message: res.data, description: '', duration: 4})
                    } else {
                        this.$message.error(res.msg);
                        return;
                    }
                    this.$refs.table.refresh({search: true})
                })
            },
            modifyfunction(data) {
                if (data != undefined) {
                    this.add = false;
                    this.isdisabled = true;

                    this.modelData.id = data.id
                    setTimeout(() => {
                        this.Formtable.setFieldsValue({
                            "cardNumber": data.cardNumber,
                            "password": data.password,
                            "validityPeriod": data.validityPeriod,
                            "updateDate": data.updateDate,
                            "state": data.state,
                            "shelfState": data.shelfState,
                            "delFlag": data.delFlag,
                        })
                    }, 0)
                } else {
                    this.isdisabled = false;
                }
                this.modifyvisible = true;
            },
            createfunctionOk() {
                let that = this;
                that.Formtable.validateFields(['cardNumber', 'password', 'validityPeriod'], {force: true}, (err, values) => {
                    if (err) {
                        return;
                    }
                    that.modelData.cardNumber = values.cardNumber
                    that.modelData.password = values.password
                    that.modelData.validityPeriod = values.validityPeriod
                    if (this.add) {
                        let obj = that.modelData;
                        delete obj.id
                        let yxtCoupon = JSON.stringify(obj);
                        yxtCouponInsert({yxtCoupon}).then((res) => {
                            this.modifyvisible = false;
                            this.clearmodel()
                            if (res.state == "success") {
                                this.$notification.success({message: res.data, description: '', duration: 4})
                            } else {
                                this.$message.error(res.msg);
                                return;
                            }
                            this.search()
                        })
                    } else {
                        let obj = that.modelData;
                        let yxtCoupon = JSON.stringify(obj);
                        yxtCouponUpdate({yxtCoupon}).then((res) => {
                            this.modifyvisible = false;
                            this.clearmodel()
                            if (res.state == "success") {
                                this.$notification.success({message: res.data, description: '', duration: 4})
                            }
                            this.search()
                        })
                    }
                })
            },
            createfunctionCancel() {
                this.modifyvisible = false;
                this.clearmodel()
                this.add = true;
            },
            //清除弹窗信息
            clearmodel() {
                this.add = true
                this.modelData.id = ''
                this.modelData.month = ''
                this.Formtable.setFieldsValue({
                    "cardNumber": '',
                    "password": '',
                    "validityPeriod": '',
                })
            }
        },
        mounted() {

        }
    }
</script>

<style scoped>

</style>