<template>
    <div class="list-view">
        <div class="filters-container">
            <el-input placeholder="输入关键字" v-model="search" clearable
                      class="filter-item"></el-input>
            <el-button @click="getData" type="primary" icon="el-icon-search"
                       class="filter-item">搜索
            </el-button>
            <el-button @click="addRow" type="primary" icon="el-icon-plus"
                       class="filter-item">添加
            </el-button>
            <!--            <el-button @click="download" type="primary" icon="el-icon-download"
                                   :loading="downloading" class="filter-item">导出EXCEL
                        </el-button>-->
            <el-select v-model="status" class="filter-item" placeholder="筛选状态" clearable filterable
                       @change="getData">
                <el-option
                        v-for="item in statusOptions"
                        :label="item.label"
                        :value="item.value"
                        :key="item.value"
                />
            </el-select>
        </div>
        <el-table :data="tableData" row-key="id" ref="table"
                  header-row-class-name="table-header-row"
                  header-cell-class-name="table-header-cell"
                  row-class-name="table-row" cell-class-name="table-cell"
                  :height="tableHeight">
            <el-table-column v-if="multipleMode" align="center" type="selection"
                             width="50">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="100">
                <template slot="header" slot-scope="{column}">
                    <sortable-header :column="column" :current-sort="sort"
                                     @changeSort="changeSort">
                    </sortable-header>
                </template>
            </el-table-column>
            <!--            <el-table-column prop="orderId" label="订单ID"
                        >
                        </el-table-column>-->
            <el-table-column prop="orderId" label="订单号"
            >
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column prop="reason" label="理由" :formatter="reasonFormatter"
            >
            </el-table-column>
            <el-table-column prop="status" label="状态"
                             :formatter="statusFormatter"
            >
                <template slot="header" slot-scope="{column}">
                    <sortable-header :column="column" :current-sort="sort" @changeSort="changeSort">
                    </sortable-header>
                </template>
            </el-table-column>
            <el-table-column prop="applyTime" label="申请时间"
                             :formatter="datetimeFormatter"
            >
                <template slot="header" slot-scope="{column}">
                    <sortable-header :column="column" :current-sort="sort" @changeSort="changeSort">
                    </sortable-header>
                </template>
            </el-table-column>
            <el-table-column prop="auditTime" label="审核时间"
                             :formatter="datetimeFormatter"
            >
                <template slot="header" slot-scope="{column}">
                    <sortable-header :column="column" :current-sort="sort" @changeSort="changeSort">
                    </sortable-header>
                </template>
            </el-table-column>
            <el-table-column prop="refundTime" label="退款时间"
                             :formatter="datetimeFormatter"
            >
                <template slot="header" slot-scope="{column}">
                    <sortable-header :column="column" :current-sort="sort" @changeSort="changeSort">
                    </sortable-header>
                </template>
            </el-table-column>
            <el-table-column prop="refundId" label="退款单号"
            >
            </el-table-column>
            <el-table-column prop="merchantLiability" label="商家承担"
            >
            </el-table-column>
            <el-table-column prop="riderLiability" label="骑手承担"
            >
            </el-table-column>
            <el-table-column prop="platformLiability" label="平台承担"
            >
            </el-table-column>
            <!--            <el-table-column
                                label="操作"
                                align="center"
                                fixed="right"
                                min-width="150">
                            <template slot-scope="{row}">
                                <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
                                <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</el-button>
                            </template>
                        </el-table-column>-->
            <el-table-column label="操作" align="center" fixed="right" min-width="250">
                <template slot-scope="{ row }">
                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
                    <el-button
                            v-if="row.status === 'PENDING_PAYMENT'"
                            :loading="row.loading"
                            @click="payment(row)"
                            type="primary"
                            size="mini"
                            plain
                    >打款
                    </el-button>
                    <el-button
                            v-if="row.status === 'PENDING' && row.report"
                            :loading="row.loading"
                            @click="audit(row)"
                            type="primary"
                            size="mini"
                            plain
                    >通过
                    </el-button>

                    <el-button
                            v-if="row.status === 'PENDING' && row.report"
                            @click="denyAudit(row)"
                            type="danger"
                            size="mini"
                            plain
                    >拒绝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
            <!--<div class="multiple-mode-wrapper">
                <el-button v-if="!multipleMode"
                           @click="toggleMultipleMode(true)">批量编辑
                </el-button>
                <el-button-group v-else>
                    <el-button @click="operation1">批量操作1</el-button>
                    <el-button @click="operation2">批量操作2</el-button>
                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
                </el-button-group>
            </div>-->
            <el-pagination background @size-change="onSizeChange"
                           @current-change="onCurrentChange" :current-page="page"
                           :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="totalElements">
            </el-pagination>
        </div>

        <el-dialog
                title="退款"
                center
                :visible.sync="dislogForm"
                width="400px"
        >
            <el-form>
                <el-form-item label="商家责任">
                    <el-input-number type="number" v-model="merchantLiability"
                                     :min='0' :step="0.01" :max="1"></el-input-number>
                </el-form-item>
                <el-form-item label="骑手责任">
                    <el-input-number type="number" v-model="riderLiability"
                                     :min='0' :step="0.01" :max="1"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="remark" type="textarea"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="platformAudit(true)">确定</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>
    </div>
</template>
<script>
    import {mapState} from "vuex";
    import pageableTable from "@/mixins/pageableTable";

    export default {
        name: 'OrderRefundApplyList',
        mixins: [pageableTable],
        created() {
            this.getData();
        },
        data() {
            return {
                multipleMode: false,
                search: "",
                url: "/orderRefundApply/all",
                downloading: false,
                statusOptions: [
                    {"label": "待处理", "value": "PENDING"},
                    /*{"label": "退款中", "value": "REFUNDING"},*/
                    {"label": "成功", "value": "SUCCESS"},
                    {"label": "待打款", "value": "PENDING_PAYMENT"},
                    {"label": "失败", "value": "DENY"},
                    {"label": "取消退款", "value": "CANCEL"}],
                reasonOptions: [
                    {"label": "用户支付超时", "value": "PAYMENT_TIMEOUT"},
                    {"label": "商家接单超时", "value": "ORDER_TIMEOUT"},
                    {"label": "商家拒单", "value": "MERCHANT_REJECTION"},
                    {"label": "配送时间太长", "value": "DELIVERY_TIME_IS_TOO_LONG"},
                    {"label": "地址填写错误", "value": "ADDRESS_IS_INCORRECT"},
                    {"label": "商家无法送达，联系我取消", "value": "MERCHANT_CANNOT_DELIVER"},
                    {"label": "商家缺货/打烊，联系我取消", "value": "MERCHANT_OUT_OF_STOCK"},
                    {"label": "忘记使用红包", "value": "FORGOT_TO_USE_THE_RED_ENVELOPE"},
                    {"label": "忘点主食", "value": "FORGET_ABOUT_STAPLE_FOOD"},
                    {"label": "骑手联系我取消", "value": "RIDER_CONTACT_ME_TO_CANCEL"},
                    {"label": "点多了/点错了/漏点了", "value": "MORE_POINTS"},
                    {"label": "临时有事不想要了", "value": "DO_NOT_WANT_SOMETHING_TEMPORARILY"},
                    {"label": "用户投诉", "value": "USER_COMPLAINTS"},
                    {"label": "其他原因", "value": "OTHER"}],
                status: '',
                dislogForm: false,
                merchantLiability: 0,
                riderLiability: 0,
                remark: '',
                value: [],
            }
        },
        computed: {
            selection() {
                return this.$refs.table.selection.map(i => i.id);
            }
        },
        methods: {
            reasonFormatter(row, column, cellValue, index) {
                let selectedOption = this.reasonOptions.find(i => i.value === cellValue);
                if (selectedOption) {
                    return selectedOption.label;
                }
                return '';
            },
            statusFormatter(row, column, cellValue, index) {
                let selectedOption = this.statusOptions.find(i => i.value === cellValue);
                if (selectedOption) {
                    return selectedOption.label;
                }
                return '';
            },
            beforeGetData() {
                /*if (this.search) {
                    return {search: this.search};
                }*/
                return {
                    search: this.search,
                    query: {
                        status: this.status,
                    },
                    sort: "applyTime,desc"
                };
            },
            toggleMultipleMode(multipleMode) {
                this.multipleMode = multipleMode;
                if (!multipleMode) {
                    this.$refs.table.clearSelection();
                }
            },
            addRow() {
                this.$router.push({
                    path: "/orderRefundApplyEdit",
                    query: {
                        ...this.$route.query
                    }
                });
            },
            editRow(row) {
                this.$router.push({
                    path: "/orderRefundApplyEdit",
                    query: {
                        id: row.id
                    }
                });
            },
            download() {
                this.downloading = true;
                this.$axios
                    .get("/orderRefundApply/excel", {
                        responseType: "blob",
                        params: {size: 10000}
                    })
                    .then(res => {
                        console.log(res);
                        this.downloading = false;
                        const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
                        const link = document.createElement("a");
                        link.href = downloadUrl;
                        link.setAttribute(
                            "download",
                            res.headers["content-disposition"].split("filename=")[1]
                        );
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                    })
                    .catch(e => {
                        console.log(e);
                        this.downloading = false;
                        this.$message.error(e.error);
                    });
            },
            operation1() {
                this.$notify({
                    title: '提示',
                    message: this.selection
                });
            },
            operation2() {
                this.$message('操作2');
            },
            deleteRow(row) {
                this.$alert('删除将无法恢复，确认要删除么？', '警告', {type: 'error'}).then(() => {
                    return this.$http.post(`/orderRefundApply/del/${row.id}`)
                }).then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                }).catch(action => {
                    if (action === 'cancel') {
                        this.$message.info('删除取消');
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            },
            denyAudit(row){
                this.$http
                    .get('/orderRefundApply/platformAudit', {
                        id: row.id,
                        agree: false,
                    })
                    .then(res => {
                        this.$set(row, 'loading', false);
                        this.$message.success('OK');
                        this.getData();
                    })
                    .catch(e => {
                        console.log(e);
                        this.$set(row, 'loading', false);
                        this.$message.error(e.error);
                    });
            },
            platformAudit() {
                this.$set(this.value, 'loading', true);
                this.$http
                    .get('/orderRefundApply/platformAudit', {
                        id: this.value.id,
                        agree: true,
                        merchantLiability: this.merchantLiability,
                        riderLiability: this.riderLiability,
                        remark: this.remark

                    })
                    .then(res => {
                        this.$set(this.value, 'loading', false);
                        this.$message.success('OK');
                        this.dislogForm = false;
                        this.getData();
                    })
                    .catch(e => {
                        console.log(e);
                        this.$set(this.value, 'loading', false);
                        this.$message.error(e.error);
                    });
            },
            payment(row) {
                this.$alert('确认后将无法恢复，确认要已打款？', '提示', {type: 'warning'}).then(() => {
                    return this.$http.get(`/orderRefundApply/payment`, {
                        id: row.id
                    })
                }).then(() => {
                    this.$message.success('确认成功');
                    this.getData();
                }).catch(action => {
                    if (action === 'cancel') {
                        this.$message.info('确认取消');
                    } else {
                        this.$message.error('确认失败');
                    }
                })
            },
            audit(row) {
                this.dislogForm = true;
                this.value = row;
            }
        }
    }
</script>
<style lang="less" scoped>
</style>
