<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="168px"
            @submit.native.prevent
        >
            <el-form-item label="站点" prop="stationId">
                <el-select
                    v-model="queryParams.stationId"
                    placeholder="请选择站点"
                    clearable
                    filterable
                    style="width: 140px"
                >
                    <el-option
                        v-for="(station, index) in stationList"
                        :key="index"
                        :label="station.stationName"
                        :value="station.id"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="订单编号" prop="orderCode">
                <el-input
                    v-model="queryParams.orderCode"
                    placeholder="请输入订单编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="手机号码" prop="mobileNumber">
                <el-input
                    v-model="queryParams.mobileNumber"
                    placeholder="请输入手机号码"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <div v-if="buttonBoolean">
                <el-form-item label="交易流水号" prop="transactionCode">
                    <el-input
                        v-model="queryParams.transactionCode"
                        placeholder="请输入交易流水号"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>

                <el-form-item label="订单状态" prop="orderStatus">
                    <el-select
                        v-model="queryParams.orderStatus"
                        placeholder="请选择订单状态"
                        clearable
                        style="width: 140px"
                    >
                        <el-option
                            v-for="item1 in dict.type.order_status"
                            :key="item1.value"
                            :label="item1.label"
                            :value="item1.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="创建时间">
                    <el-date-picker
                        v-model="createTimeRange"
                        style="width: 240px"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :clearable="false"
                    ></el-date-picker>
                </el-form-item>
            </div>
            <el-button
                @click="showOrHide()"
                style="
                    border-color: white;
                    background-color: white;
                    font-size: x-small;
                    color: #50bfff;
                    padding: 1px 2px;
                    margin-left: 40%;
                    margin-top: 0px;
                    margin-bottom: 15px;
                "
                :icon="icon"
                >{{ showOrHideText }}
            </el-button>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-col>
            <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['order:order:export']"
                >导出</el-button
            >
            <div>
                {{ dateDescription }}期间，总用电量{{
                    sumUsedElectricity
                }}度，总消费金额{{ sumOrderAmount }}元
            </div>
            <el-popover placement="top-start" width="400" trigger="click">
                <el-checkbox
                    :indeterminate="isIndeterminate"
                    v-model="checkAll"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                >
                <div style="margin: 15px 0"></div>
                <el-checkbox-group
                    style="display: grid"
                    v-model="checkedCities"
                    @change="handleCheckedCitiesChange"
                >
                    <el-checkbox
                        v-for="city in cities"
                        :label="city"
                        :key="city.id"
                        >{{ city }}</el-checkbox
                    >
                </el-checkbox-group>
            </el-popover>
        </el-row>
        <el-skeleton style="width: 100%" :loading="loading" animated :count="3">
            <template slot="template">
                <el-skeleton-item
                    variant="text"
                    style="width: 100%; height: 100%"
                />
                <div style="padding: 14px">
                    <el-skeleton-item variant="h3" style="width: 50%" />
                    <div
                        style="
                            display: flex;
                            align-items: center;
                            justify-items: space-between;
                            margin-top: 16px;
                            height: 16px;
                        "
                    >
                        <el-skeleton-item
                            variant="text"
                            style="margin-right: 16px"
                        />
                        <el-skeleton-item variant="text" style="width: 30%" />
                    </div>
                </div>
            </template>
            <template>
                <template v-if="orderList.length !== 0">
                    <div
                        class="cardview-box"
                        v-for="(item, orderIndex) in orderList"
                        :key="orderIndex"
                        @change="handleSelectionChange"
                    >
                        <div class="cardview-static">
                            <div>
                                <router-link
                                    :to="
                                        '/order/index/orderDetail/' +
                                        item.orderCode
                                    "
                                    class="link-type"
                                    >订单编号：{{ item.orderCode }}</router-link
                                >

                                <el-tag
                                    :type="color(item.orderStatus)"
                                    style="margin-left: 10px"
                                    >{{ item.orderStatusDescribe }}</el-tag
                                >
                            </div>
                            <div>
                                开始时间：{{ item.chargeStartTime || "一" }}
                            </div>
                        </div>
                        <div style="padding: 10px">
                            <el-descriptions
                                :title="`${item.nickName || '---'}（${
                                    item.mobileNumber || '---'
                                }）`"
                                :column="4"
                            >
                                <el-descriptions-item label="交易流水号">{{
                                    item.transactionCode || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="站点">{{
                                    item.stationName || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="充电桩枪口号">{{
                                    item.pileConnectorCode || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="卡号">{{
                                    item.logicCard || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="微信商户订单号">{{
                                    item.outTradeNo || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="启动方式">{{
                                    startMode(item.startMode)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="支付方式">{{
                                    payMode(item.payMode)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="支付金额">{{
                                    item.payAmount || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="支付状态">{{
                                    payStatus(item.payStatus)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="充电度数">{{
                                    item.chargingDegree || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="起始SOC">{{
                                    item.startSoc || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="终止SOC">{{
                                    item.endSoc || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="结束充电时间">{{
                                    item.chargeEndTime || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="总消费金额">{{
                                    item.orderAmount || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="虚拟金额">{{
                                    item.virtualAmount || "一"
                                }}</el-descriptions-item>
                                <el-descriptions-item label="结算金额">{{
                                    item.settleAmount || "一"
                                }}</el-descriptions-item>
                            </el-descriptions>
                            <div
                                style="
                                    flex: 1;
                                    text-align: center;
                                    margin: auto;
                                "
                            ></div>
                        </div>
                    </div>

                    <pagination
                        v-show="total > 0"
                        :total="total"
                        :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getList"
                    />
                </template>
                <el-empty description="暂无数据" v-else></el-empty>
            </template>
        </el-skeleton>
    </div>
</template>

<script>
import {
    listOrder,
    getOrder,
    delOrder,
    addOrder,
    updateOrder,
    totalData,
} from "@/api/order/order";
import Template from "@/views/billing/template";
import { listStation } from "@/api/pile/station";
import { getDay } from "@/utils/common";
export default {
    name: "Order",
    components: { Template },

    dicts: ["order_status", "start_mode", "pay_mode", "pay_status"],
    data() {
        return {
            skeletonLoading: true, // 骨架屏
            showOrHideText: "显示更多查询条件",
            buttonBoolean: false,
            //图标，可根据自己的需求匹配
            icon: "el-icon-caret-bottom",
            checkAll: false,
            checkedCities: [],
            cities: ["订单状态描述", "启动方式", "起始SOC", "终止SOC"],
            isIndeterminate: true,
            dateDescription: "",
            sumOrderAmount: "",
            sumUsedElectricity: "",
            // 遮罩
            loading: true,
            // 选中数组
            ids: [],
            // 子表选中数据
            checkedOrderDetail: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 订单表格数据
            orderList: [],
            // 订单详情表格数据
            orderDetailList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderCode: null,
                transactionCode: null,
                mobileNumber: null,
                orderStatus: null,
                stationId: null,
                startTime: null,
                endTime: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            // 站点列表
            stationList: [],
            // 订单创建时间范围
            createTimeRange: [],
        };
    },
    mounted() {
        this.setLoading();
    },
    created() {
        this.dataLoading();
    },
    methods: {
        setLoading() {
            this.skeletonLoading = true;
            setTimeout(() => (this.skeletonLoading = false), 2000);
        },
        color(e) {
            let arr = [
                "",
                "success",
                "info",
                "warning",
                "danger",
                "warning",
                "success",
                "success",
            ];
            return e ? arr[e] : arr[0];
        },
        showOrHide() {
            if (this.buttonBoolean) {
                this.icon = "el-icon-caret-bottom";
                this.showOrHideText = "显示更多查询条件";
                this.buttonBoolean = !this.buttonBoolean;
            } else {
                this.icon = "el-icon-caret-top";
                this.showOrHideText = "收起";
                this.buttonBoolean = !this.buttonBoolean;
            }
        },
        startMode(mode) {
            let arr = this.dict.type.start_mode.find(
                (item) => item.value == mode
            );
            if (arr == null) {
                return "一";
            } else {
                return arr.label;
            }
        },
        payMode(mode) {
            let arr = this.dict.type.pay_mode.find(
                (item) => item.value == mode
            );
            if (arr == null) {
                return "一";
            } else {
                return arr.label;
            }
        },
        payStatus(status) {
            let arr = this.dict.type.pay_status.find(
                (item) => item.value == status
            );
            if (arr == null) {
                return "一";
            } else {
                return arr.label;
            }
        },
        handleCheckAllChange(val) {
            this.checkedCities = val ? cityOptions : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            console.log(value);
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.cities.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.cities.length;
        },
        getTagType(row) {
            let arr = this.dict.type.order_status.find(
                (item) => item.value === row.orderStatus
            );
            return arr.raw.listClass;
        },
        async dataLoading() {
            console.log("加载订单列表页数据...");
            // 设置默认日期
            await this.defaultDate();
            // 查询订单列表
            this.getList();
            // 查询站点列表
            this.getStationList();
            // 获取订单总金额
            this.getOrderTotalData();
        },
        /** 查询订单列表 */
        getList() {
            this.loading = true;
            listOrder(this.queryParams).then((response) => {
                this.orderList = response.rows;
                console.log("order里面的参数", this.orderList);
                this.total = response.total;
                this.loading = false;
            });
        },
        // 获取订单总金额数据
        getOrderTotalData() {
            totalData(this.queryParams).then((response) => {
                console.log("getOrderTotalData", response);
                this.dateDescription = response.data.dateDescription;
                this.sumOrderAmount = response.data.sumOrderAmount;
                this.sumUsedElectricity = response.data.sumUsedElectricity;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                orderCode: null,
                orderStatus: "0",
                memberId: null,
                nickName: null,
                mobileNumber: null,
                stationId: null,
                connectorCode: null,
                startMode: null,
                payMode: null,
                payStatus: null,
                payAmount: null,
                payTime: null,
                orderAmount: null,
                startSoc: null,
                endSoc: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                delFlag: null,
            };
            this.orderDetailList = [];
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            // 获取订单列表
            this.getList();
            // 获取订单总金额
            this.getOrderTotalData();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加订单";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getOrder(id).then((response) => {
                this.form = response.data;
                this.orderDetailList = response.data.orderDetailList;
                this.open = true;
                this.title = "修改订单";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.form.orderDetailList = this.orderDetailList;
                    if (this.form.id != null) {
                        updateOrder(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addOrder(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm('是否确认删除订单编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delOrder(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },
        /** 订单详情序号 */
        rowOrderDetailIndex({ row, rowIndex }) {
            row.index = rowIndex + 1;
        },
        /** 订单详情添加按钮操作 */
        handleAddOrderDetail() {
            let obj = {};
            obj.totalUsedElectricity = "";
            obj.totalOrderAmount = "";
            obj.totalElectricityAmount = "";
            obj.totalServiceAnount = "";
            obj.sharpUsedElectricity = "";
            obj.sharpElectricityPrice = "";
            obj.sharpServicePrice = "";
            obj.peakUsedElectricity = "";
            obj.peakElectricityPrice = "";
            obj.peakServicePrice = "";
            obj.flatUsedElectricity = "";
            obj.flatElectricityPrice = "";
            obj.flatServicePrice = "";
            obj.valleyUsedElectricity = "";
            obj.valleyElectricityPrice = "";
            obj.valleyServicePrice = "";
            this.orderDetailList.push(obj);
        },
        /** 订单详情删除按钮操作 */
        handleDeleteOrderDetail() {
            if (this.checkedOrderDetail.length === 0) {
                this.$modal.msgError("请先选择要删除的订单详情数据");
            } else {
                const orderDetailList = this.orderDetailList;
                const checkedOrderDetail = this.checkedOrderDetail;
                this.orderDetailList = orderDetailList.filter(function (item) {
                    return checkedOrderDetail.indexOf(item.index) === -1;
                });
            }
        },
        /** 复选框选中数据 */
        handleOrderDetailSelectionChange(selection) {
            this.checkedOrderDetail = selection.map((item) => item.index);
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "order/order/export",
                {
                    ...this.queryParams,
                },
                `order_${new Date().getTime()}.xlsx`
            );
        },
        /** 查询充电站信息列表 */
        getStationList() {
            const queryStationParams = {
                pageNum: 1,
                pageSize: 999,
            };
            listStation(queryStationParams).then((response) => {
                // console.log("订单列表页-查询站点列表", response)
                this.stationList = response.rows;
            });
        },

        //设置默认日期
        defaultDate() {
            //字符串拼接，开始时间，结束时间
            let beg = getDay(-7) + " 00:00:00"; //当月第一天
            let end = getDay(0) + " 23:59:59"; //当天
            this.createTimeRange = [beg, end]; //将值设置给插件绑定的数据
            // return this.createTimeRange;
        },
    },
    watch: {
        createTimeRange(newValue, oldValue) {
            // console.log("createTimeRange发生变化", newValue, oldValue);
            if (newValue != null && newValue.length > 0) {
                this.queryParams.startTime = newValue[0];
                this.queryParams.endTime = newValue[1];
            }
        },
    },
    computed: {
        tagType(row) {
            console.log("tagType row", row);
            return "info";
        },
    },
};
</script>
<style lang="scss" scoped>
::v-deep
    .el-descriptions--medium:not(.is-bordered)
    .el-descriptions-item__cell {
    padding-bottom: 4px;
}
::v-deep .el-descriptions__header {
    margin-bottom: 10px;
}
.cardview-box {
    width: 100%;
    margin-bottom: 12px;
    font-size: 16px;
    color: #4a4a4a;
    border: 1px solid #f0f0f0;
}
.cardview-static {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-content: center;
    padding: 0 10px;
    height: 46px;
    line-height: 46px;
    background-color: #f0f0f0;
}
.flex {
    display: flex;
    justify-content: space-between;
    align-content: center;
    margin-bottom: 10px;
}
</style>
