<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-button >新店</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>
            <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    start-placeholder="请选择开始时间"
                    end-placeholder="请选择结束时间"
                    range-separator="至"
                    :default-time="['00:00:00', '23:59:59']"
                    class="filter-item"
                    :picker-options="pickerOptions"
                    @change="getData"
            >
            </el-date-picker>

        </div>
        <el-table :data="tableData" row-key="mid" 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="mid" label="ID" width="100">
            </el-table-column>
            <el-table-column prop="logo" label="Logo"
            >
                <template slot-scope="{row}">
                    <el-image style="width: 30px; height: 30px"
                              :src="row.logo" fit="cover"
                              :preview-src-list="[row.logo]"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="名称"
            >
            </el-table-column>
            <el-table-column prop="phone" label="电话"
            >
            </el-table-column>
            <el-table-column prop="introduction" label="简介"
            >
            </el-table-column>
            <el-table-column prop="address" label="地址"
            >
            </el-table-column>
            <!--<el-table-column prop="firstOrder" label="首单优惠"
            >
            </el-table-column>
            <el-table-column prop="newUser" label="新用户优惠"
            >
            </el-table-column>-->
            <el-table-column prop="category" label="类别"
            >
                <template slot-scope="{ row }">
                    <span v-for="item in row.category">{{ item.name }}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column prop="tag" label="标签"
                        >
                        </el-table-column>-->
            <el-table-column prop="status" label="状态" :formatter="statusFormatter"
            >
            </el-table-column>
            <!--            <el-table-column prop="startTime" label="营业时间"
                        >
                        </el-table-column>
                        <el-table-column prop="endTime" label="结束时间"
                        >
                        </el-table-column>-->
            <!--            <el-table-column prop="qualification" label="营业资质"
                        >
                            <template slot-scope="{row}">
                                <el-image style="width: 30px; height: 30px"
                                          :src="row.qual" fit="cover"
                                          :preview-src-list="[row.qualifications]"></el-image>
                            </template>
                        </el-table-column>-->
            <el-table-column prop="merchantNature.name" 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="showDrawer(row)" type="success" size="mini" plain>详情</el-button>
                    <el-button @click="" type="primary" size="mini" plain v-if="row.isPass">报表</el-button>
                    <el-button @click="" type="primary" size="mini" plain v-if="row.isPass">评价</el-button>
                    <el-button
                            v-if="row.status === 'PENDING'"
                            :loading="row.loading"
                            @click="audit(row, true)"
                            type="warning"
                            size="mini"
                            plain
                    >通过
                    </el-button
                    >
                    <el-button
                            v-if="row.status === 'PENDING'"
                            @click="audit(row, false)"
                            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-drawer
                size="45%"
                :show-close="false"
                :visible.sync="drawer"
                :with-header="false">
            <div class="info-content">
                <div class="info-item">
                    Logo：
                    <el-image style="width: 30px; height: 30px"
                              :src="formData.logo" fit="cover"
                              :preview-src-list="[formData.logo]"/>
                </div>
                <div class="info-item">名称：{{formData.name}}</div>
                <div class="info-item">显示名称：{{formData.showName}}</div>
                <div class="info-item">横幅：
                    <el-image style="width: 60px; height: 30px"
                              :src="formData.banner" fit="cover"
                              :preview-src-list="[formData.banner]"/>
                </div>
                <div class="info-item">电话：{{formData.phone}}</div>
                <div class="info-item">简介：{{formData.introduction}}</div>
                <div class="info-item">图片： {{formData.img}}
                    <!--<el-image style="width: 60px; height: 30px"
                              :src="picList(formData.img)" fit="cover"
                              :preview-src-list="picList(formData.img)"/>-->
                </div>
                <div class="info-item">地址：{{formData.address}}</div>
                <div class="info-item">成立时间：{{formData.establishTime}}</div>
                <div class="info-item">营业资质：
                    <el-image style="width: 30px; height: 30px"
                              :src="formData.qualification" fit="fit"
                              :preview-src-list="[formData.qualification]"/>
                </div>
                <!--<div class="info-item">营业性质：{{formData.merchantNature.name}}</div>-->
                <div class="info-item">公告：{{formData.proclamation}}</div>
                <div class="info-item">经营品类：{{formData.category}}
                </div>
                <div class="info-item">营业：{{formData.week}}</div>
                <div class="info-item">营业时间：{{formData.startTime}} - {{formData.endTime}}</div>
                <hr/>
                <div class="info-item">法人姓名：{{verified.realName}}</div>
                <div class="info-item">法人身份证：{{verified.idNo}}</div>
                <div class="info-item">身份证照片：
                    <el-image style="width: 30px; height: 30px"
                              :src="picList(verified.idNoImg)[0]" fit="fit"
                              :preview-src-list="picList(verified.idNoImg)?picList(verified.idNoImg):[]"/>
                </div>
                <div class="info-item">手持身份证：
                    <el-image style="width: 30px; height: 30px"
                              :src="verified.handheldIdNo" fit="fit"
                              :preview-src-list="[verified.handheldIdNo]"/>
                </div>
                <!--                <div class="info-item">申请状态：{{formData.status}}</div>-->
                <el-button @click="moveRow"
                           type="danger" v-if="formData.mid && !formData.blacklist">移入黑名单
                </el-button>
                <el-button @click="editRow(formData)" type="primary" size="mini" plain>编辑</el-button>
                <el-button @click="deleteRow(formData)" type="danger" size="mini" plain>删除</el-button>
            </div>
        </el-drawer>

    </div>
</template>
<script>
    import {mapState} from "vuex";
    import pageableTable from "@/mixins/pageableTable";
    import addDays from "date-fns/addDays";
    import addMonths from "date-fns/addMonths";
    import format from "date-fns/format";
    import startOfDay from "date-fns/startOfDay";
    import endOfDay from "date-fns/endOfDay";

    export default {
        name: 'MerchantList',
        mixins: [pageableTable],
        created() {
            this.getData();
        },
        data() {
            return {
                multipleMode: false,
                search: "",
                url: "/merchant/backAll",
                downloading: false,
                statusOptions: [{"label": "待处理", "value": "PENDING"}, {
                    "label": "成功", "value": "PASS"
                }, {"label": "失败", "value": "DENY"}],
                status: '',
                drawer: false,
                formData: {
                    // category: []
                },
                showSetLogistics: false,
                dateRange: [],
                verified: {},

                pickerOptions: {
                    shortcuts: [
                        {
                            text: '今天',
                            onClick(picker) {
                                picker.$emit('pick', [
                                    format(startOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss'),
                                    format(endOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss')
                                ]);
                            }
                        },
                        {
                            text: '近一周',
                            onClick(picker) {
                                const date = addDays(new Date(), -7);
                                picker.$emit('pick', [
                                    format(startOfDay(date), 'yyyy-MM-dd HH:mm:ss'),
                                    format(endOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss')
                                ]);
                            }
                        },
                        {
                            text: '近一月',
                            onClick(picker) {
                                const date = addMonths(new Date(), -1);
                                picker.$emit('pick', [
                                    format(startOfDay(date), 'yyyy-MM-dd HH:mm:ss'),
                                    format(endOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss')
                                ]);
                            }
                        },
                        {
                            text: '近三月',
                            onClick(picker) {
                                const date = addMonths(new Date(), -3);
                                picker.$emit('pick', [
                                    format(startOfDay(date), 'yyyy-MM-dd HH:mm:ss'),
                                    format(endOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss')
                                ]);
                            }
                        },

                    ]
                }

            }
        },
        computed: {
            selection() {
                return this.$refs.table.selection.map(i => i.mid);
            }
        },
        methods: {
            picList(row) {
                if (row) {
                    return row.split(",");
                } else {
                    return "";
                }
            },
            beforeOnCreate() {
                if (this.$route.query.dateRange) {
                    this.dateRange = decodeURIComponent(this.$route.query.dateRange).split(',');
                } else {
                    this.dateRange = [
                        format(startOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss'),
                        format(endOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss')
                    ];
                }
            },

            showDrawer(row) {
                this.drawer = true;
                this.$http
                    .get('merchant/getDTO/' + row.mid)
                    .then(res => {
                        this.formData = res;
                    })
                    .catch(e => {
                        console.log(e);
                        this.$message.error(e.error);
                    });
                this.$http
                    .get('/verified/my', {
                        userId: row.userId
                    })
                    .then(res => {
                        this.verified = res;
                    })
                    .catch(e => {
                        console.log(e);
                        this.$message.error(e.error);
                    });
            },

            statusFormatter(row, column, cellValue, index) {
                let selectedOption = this.statusOptions.find(i => i.value === cellValue);
                if (selectedOption) {
                    return selectedOption.label;
                }
                return '';
            },
            beforeGetData() {

                let data = {
                    sort: 'createdAt,desc',
                    query: {}
                };
                if (this.search) {
                    data.search = this.search;
                }
                if (this.dateRange && this.dateRange.length > 0) {
                    data.query.establishTime = this.dateRange[0] + ',' + this.dateRange[1];
                }
                if (this.status) {
                    data.query.status = this.status;
                }
                return data;
                /*                if (this.search) {
                                    return {search: this.search};
                                }*/
            },
            toggleMultipleMode(multipleMode) {
                this.multipleMode = multipleMode;
                if (!multipleMode) {
                    this.$refs.table.clearSelection();
                }
            },
            addRow() {
                this.$router.push({
                    path: "/merchantEdit",
                    query: {
                        ...this.$route.query
                    }
                });
            },
            editRow(row) {
                this.$router.push({
                    path: "/merchantEdit",
                    query: {
                        id: row.mid
                    }
                });
            },
            download() {
                this.downloading = true;
                this.$axios
                    .get("/merchant/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(`/merchant/del/${row.mid}`)
                }).then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                }).catch(action => {
                    if (action === 'cancel') {
                        this.$message.info('删除取消');
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            },
            audit(row, pass) {
                this.$prompt('请输入推广语(最多15字)', '提示', {
                    inputType: 'textarea'
                })
                    .then(res => {
                        // console.log(res);
                        if (res.value) {
                            this.$alert('确定通过？', '提示', {
                                showCancelButton: true
                            })
                                .then(() => {
                                    return this.$http
                                        .get('/merchant/audit', {
                                            id: row.mid,
                                            pass: pass,
                                            promo: res.value
                                        })
                                })
                                .then(res => {
                                    this.$message.success('成功');
                                    this.$router.go(-1);
                                })
                                .catch(() => {
                                    this.$message.error(res.error || '失败');
                                });
                        }
                    })
                    .catch(() => {
                    });


                /*this.$set(row, 'loading', true);
                this.$http
                    .get('/merchant/audit', {
                        id: row.mid,
                        pass: pass
                    })
                    .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);
                    });*/
            },
            moveRow() {
                this.$prompt('请输入理由', '提示', {
                    inputType: 'textarea'
                })
                    .then(res => {
                        // console.log(res);
                        if (res.value) {
                            this.$alert('确定拉入黑名单？', '提示', {
                                showCancelButton: true
                            })
                                .then(() => {
                                    return this.$http.post('/blackList/move', {
                                        userId: this.formData.userId,
                                        reason: res.value
                                    });
                                })
                                .then(res => {
                                    this.$message.success('拉入黑名单成功');
                                    this.$router.go(-1);
                                })
                                .catch(() => {
                                    this.$message.error(res.error || '拉入黑名单失败');
                                });
                        }
                    })
                    .catch(() => {
                    });
            },
        }
    }
</script>
<style lang="less" scoped>
    .info-content {
        padding: 0px 20px 0;
        /*border-bottom: 1px solid #f2f4f5;*/
        margin-bottom: 20px;

        .info-item {
            font-size: 14px;
            color: rgba(77, 77, 77, 1);
            display: flex;
            margin-bottom: 20px;
            font-weight: 500;

            .el-col {
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .el-button--text {
                margin: 0 !important;
                padding: 0 !important;
                border: none !important;
                font-size: 14px !important;
            }

            label {
                width: 84px;
                display: inline-block;
                text-align: right;
                font-weight: 400;
            }

            .remark {
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
                width: calc(100% - 85px);
            }
        }
    }
</style>
