<template>
    <div style="width: 1200px; margin: 0 auto; word-spacing: 2em">
        <el-row :gutter="20">
            <el-col :span="24">
                <el-card style="margin-top: 10px">
                    <el-row :gutter="10">
                        <el-col :span="8">
                            <span>订单状态 </span
                            ><span
                                style="
                                    letter-spacing: normal;
                                    color: #333333;
                                    line-height: normal;
                                    font-weight: 700;
                                "
                                >{{ order.refStatus }}</span
                            >
                        </el-col>
                        <el-col :span="16" style="cursor: pointer">
                            <span style="color: rgb(64, 158, 255);" @click="seeOrderStatus()">订单跟踪></span>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="24">
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="3">服务主题</el-col>
                        <el-col :span="21" style="margin-bottom: 20px; cursor: pointer">
                            <span  style="color: rgb(64, 158, 255);" @click="toServerProject"
                                >{{ order.goodsName }}></span
                            >
                        </el-col>

                        <!-- <el-col :span="2">
                            <span>{{ order.serverName }}</span>
                        </el-col>
                        <el-col :span="3">
                            <span>{{ order.serverPhone }}</span>
                        </el-col>
                        <el-col :span="3">
                            <span>{{ this.serverUser.serverLevel }}</span>
                        </el-col>
                        <el-col :span="3">
                            <span>{{ this.serverUser.serverAge }}年工龄</span>
                        </el-col>
                        <el-col :span="3">
                            <span>好评率 </span><span class="span-color" >{{ this.serverUser.rate }}</span>
                        </el-col> -->
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="24">
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <span>顾客信息</span>
                            <span class="span-color-size">
                                {{
                                    member.name
                                        ? member.name.length > 1
                                            ? member.name.replace(
                                                  member.name.substring(1, 2),
                                                  "*"
                                              )
                                            : member.name + "*"
                                        : ""
                                }}
                                {{ member.phone }}
                            </span>
                            <!-- <span>
                                {{
                                    member.phone
                                        ? member.phone.replace(
                                              member.phone.substring(3, 7),
                                              "****"
                                          )
                                        : ""
                                }}
                            </span> -->
                        </el-col>
                        <el-col :span="12">
                            <span class="span-color-size"
                                ><i class="el-icon-location-information" />{{
                                    member.address
                                }}{{ member.detailed }}</span
                            >
                        </el-col>
                        <el-col :span="24" style="margin-top: 20px">
                            <span>备注 </span
                            ><span class="span-color-size">
                                {{ order.memo }}</span
                            >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="24">
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <span>订单编号</span><span class="span-detailed-info"> {{ order.orderIndex }} </span>
                            <el-button
                                size="mini"
                                class="orderIndex"
                                :data-clipboard-text="order.orderIndex"
                                >复制</el-button
                            >
                        </el-col>

                        <el-col :span="12" style="margin-bottom: 20px">
                            <span>下单时间</span><span  class="span-detailed-info"> {{ order.createTime }}</span>
                        </el-col>

                        <el-col :span="12">
                            <span>服务类别 </span
                            ><span class="span-detailed-info">
                                {{
                                    order.parentName == null
                                        ? ""
                                        : order.parentName + "—"
                                }}{{ order.categoryName }}</span
                            >
                        </el-col>
                        <el-col :span="12" style="margin-bottom: 20px">
                            <span>规格描述</span><span class="span-detailed-info"> {{ order.specificationDesc }}</span>
                        </el-col>

                        <el-col :span="12">
                            <span>次数 </span
                            ><span class="span-color"
                                >{{ order.groupTimes }}
                            </span>
                        </el-col>
                        <el-col :span="12">
                            <span>订单金额 </span
                            ><span class="span-color"
                                >￥{{ order.orderAmount }}</span
                            >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="24" v-if="order.beanAmount">
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="24">
                            <span>优金豆</span
                            ><span style="color: #d9001b">
                                -￥{{ order.beanAmount / 100 }}</span
                            >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="24" v-if="order.couponAmount">
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="24">
                            <span>优惠券</span
                            ><span style="color: #d9001b">
                                -￥{{ order.couponAmount }}</span
                            >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col>
                <el-card
                    :span="24"
                    style="background-color: rgb(127, 127, 127); color: white"
                >
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <span>订单实付 ￥{{ order.totalAmount }}</span>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="24" v-if="orderVerificationRecordList.length > 0">
                <el-row style="margin-bottom: 10px">
                    <b>核销记录</b>
                </el-row>
                <el-card
                    v-for="item in orderVerificationRecordList"
                    :key="item.orderVerificationRecordId"
                >
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <span
                                >核销时间
                                {{
                                    item.createTime
                                        | dateFormat("yyyy-MM-DD HH:mm")
                                }}
                            </span>
                        </el-col>

                        <el-col :span="12" style="margin-bottom: 20px">
                            <span
                                >上门时间
                                {{
                                    item.appointmentTime
                                        | dateFormat("yyyy-MM-DD HH:mm")
                                }}</span
                            >
                        </el-col>

                        <el-col :span="12">
                            <span>核销码 {{ item.orderVerificationCode }}</span>
                        </el-col>
                        <el-col :span="12" style="margin-bottom: 20px">
                            <span>备注 {{ item.remark }}</span>
                            <span v-if="item.qrCodeUrl">
                                <el-button
                                    size="mini"
                                    type="primary"
                                    class="gatePass"
                                    @click="
                                        getAccessPasscode(
                                            item.orderVerificationCode
                                        )
                                    "
                                    >门岗通行证
                                </el-button>
                            </span>
                            <span v-else>
                                <el-button
                                    size="mini"
                                    type="primary"
                                    class="gatePass"
                                    @click="
                                        getOrSaveAccessPasscode(
                                            item.orderVerificationCode
                                        )
                                    "
                                    >门岗通行证
                                </el-button>
                            </span>
                        </el-col>

                        <el-col :span="12" style="margin-bottom: 20px">
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

            <el-col :span="24" v-if="refundOpen">
                <el-row style="margin-bottom: 10px">
                    <b>退款信息 </b>
                </el-row>
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="12" style="margin-bottom: 10px">
                            <span
                                >退款金额
                                {{
                                    refund === undefined ? "" : refund.payMoney
                                }}
                                元</span
                            >
                        </el-col>
                    </el-row>
                    <el-row :gutter="10" style="margin-bottom: 10px">
                        <el-col :span="24">
                            <span
                                >退款原因
                                {{
                                    refund === undefined
                                        ? ""
                                        : refund.refundReason
                                }}</span
                            >
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="24">
                            <span
                                >审核结果
                                {{
                                    refund === undefined
                                        ? ""
                                        : refund.refundResult
                                }}</span
                            >
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>

        <!--订单跟踪-->
        <el-dialog title="订单跟踪" :visible.sync="recordOpen" width="600px">
            <ul>
                <li :key="item.id" v-for="item in orderRecord">
                    <el-row>
                        <el-col :span="12">
                            {{ item.operateInfo }}
                            <!-- {{ checkCode(item) }} -->
                        </el-col>

                        <el-col :span="12">
                            {{ item.createTime }}
                        </el-col>
                    </el-row>

                    <el-divider></el-divider>
                </li>
            </ul>
        </el-dialog>
        <!--门岗通行证二维码-->
        <el-dialog  title="" 
        :visible.sync="qrCodeOpen" 
        width="410px"
        :modal-append-to-body="true" 
        :append-to-body="true"
        ref="refDia"
        >
        <el-row class="qrCodeDialog" style="margin-top:-20px;">
            <div style="font-size:25px;color:#fff;padding-bottom:5px;">
                门岗通行证
            </div>
        </el-row>
        <el-row class="qrCodeDialog">
            <div style="font-size:16px;color:#fff;padding-bottom:30px;">
                优鲜信家政/维修服务平台
            </div>
        </el-row>
        <el-row class="qrCodeDialog">
            <!-- <el-image
                style="width: 300px; height: 300px;"
                :src="this.qrCodeUrl"
                :preview-src-list="this.qrCodeUrls">
            </el-image> -->
            <img :src=" 'data:image/png;base64,' + this.qrCodeUrl ">
        </el-row>
        <el-row class="qrCodeDialog">
            <div style="font-size:15px;color:rgb(0, 0, 0);padding-bottom:5px;">
                进小区时请服务人员主动向门岗<span style="font-family:newHelvetica;">出</span>示此二维
            </div>
        </el-row>
        <el-row class="qrCodeDialog">
            <div style="font-size:15px;color:rgb(0, 0, 0);padding-bottom:5px;">
                码，请门岗保<span style="font-family:newHelvetica;">安</span>微信扫码确认服务人员身份。
            </div>
        </el-row>
        <el-row class="qrCodeDialog">
            <div style="font-size:16px;color:#ff511b;padding-bottom:100px;font-weight: bold;">
                此码只可使用一次，请勿给他人使用。
            </div>
        </el-row>
        <el-row class="qrCodeDialog"  style="position: absolute;top:253px;left:174px;">
            <div>
                <el-image :src="logoImage" style="border-radius:10px;width:60px;height:60px;"></el-image>
            </div>
        </el-row>
        <el-row class="qrCodeDialog" style="position: absolute;top:660px;left:152px;">
            <el-button size="mini" type="primary" class="el-icon-download"  @click="handleDownQrCodeImg()"> 下载图片</el-button>
        </el-row>
</el-dialog>

    </div>
</template>

<script>
import { getOrder, getAddress } from "@/api/system/order";
import { getUser } from "../../../api/system/ServiceUserService";
import { listCode } from "../../../api/system/dict/code";
import { listRecord } from "../../../api/system/orderRecord";
import { listRefund } from "../../../api/system/orderRefund";
import { listRecordVOByOrderId } from "../../../api/merchant/orderVerificationRecord";
import {
    saveAccessPasscode,
    getByOrderIdAndOrderVerificationCode,
} from "../../../api/merchant/accessPasscode";
import { mapGetters } from "vuex";
import ClipboardJS from "clipboard";

export default {
    name: "index",
    data() {
        return {
            refundOpen: false,
            order: {},
            activeNames: ["1"],
            imgSrc: "",
            goodsList: [],
            member: {},
            serverUser: {},
            recordOpen: false,
            qrCodeOpen: false,
            qrCodeUrl: null,
            qrCodeUrls: [],
            orderRecord: [],
            refStatusOptions: [],
            refund: {},
            clipboard: null,
            orderVerificationRecordOpen: false,
            orderVerificationRecordList: [],
            logoImage:require('../../../assets/logo/logo.png'),
        };
    },
    computed: {
        ...mapGetters(["dict"]),
    },

    mounted() {
        getOrder(this.$route.query.id).then((response) => {
            this.order = response.data;
            this.queryAdress();
            this.getServicceUser();
            this.getRefStatus();
            this.getRefund();
            this.getOrderVerificationRecordList();
        });

        this.clipboard = new ClipboardJS(".orderIndex");
        this.clipboard.on("success", (e) => {
            this.$message.success("复制成功");
            e.clearSelection();
        });
    },
    destroyed() {
        // 销毁Clipboard实例，避免在其它页面或组件中实例化Clipboard后造成再次监听，产生重复回调
        this.clipboard.destroy();
    },

    methods: {
        checkCode({ preState, nowState }) {
            let result = nowState;
            switch (nowState) {
                case "000":
                    result = "提交订单";
                    break;
                case "001":
                    result = preState === "001" ? "已核销一次服务" : "支付成功";
                    break;
                case "002":
                    result = preState === "001" ? "开始服务" : "追加服务";
                    break;
                case "003":
                    result = "完成服务";
                    break;
                case "004":
                    result =
                        preState === "005" ? "顾客取消平台退款" : "确认完成";
                    break;
                case "005":
                    result = "顾客申请平台退款";
                    break;
                case "006":
                    result = preState === "005" ? "平台已退款" : "商家已退款";
                    break;
                case "007":
                    result = "平台拒绝退款";
                    break;
                case "099":
                    result = "未支付取消订单";
                    break;
            }
            return result;
        },
        toServerProject() {
            this.$router.push("/merchant/groupService");
        },
        queryAdress() {
            getAddress(this.order.orderId).then((res) => {
                this.member = res.data;
            });
        },
        getServicceUser() {
            if (!this.order.serverId) {
                return;
            }
            getUser(this.order.serverId).then((res) => {
                this.serverUser = res.data;
                this.serverUser.rate =
                    parseFloat(this.serverUser.rate || 0) + "%";
                let params = {
                    codeValue: "服务等级",
                };
                listCode(params).then((res) => {
                    for (let i in res.rows) {
                        if (
                            this.serverUser.serverLevel == res.rows[i].decodeId
                        ) {
                            this.serverUser.serverLevel =
                                res.rows[i].decodeValue;
                        }
                    }
                });
            });
        },
        seeOrderStatus() {
            listRecord(this.order).then((res) => {
                this.orderRecord = res.rows;
                this.recordOpen = true;
            });
        },
        /** 获取订单退款子状态和信息*/
        getRefStatus() {
            let param = {
                codeValue: "退款状态",
            };
            listCode(param).then((res) => {
                this.refStatusOptions = res.rows;
            });
        },
        getRefund() {
            listRefund({ ...this.order, createTime: null }).then((res) => {
                this.refund = res.rows[0];
                if (this.refund) {
                    this.refundOpen = true;
                }
            });
        },
        // 查询订单核销记录列表
        getOrderVerificationRecordList() {
            const orderVerificationRecord = {
                orderId: this.order.orderId,
            };
            listRecordVOByOrderId(orderVerificationRecord).then((res) => {
                this.orderVerificationRecordList = res.rows;
                this.orderVerificationRecordOpen = true;
            });
        },
        // 调用门岗通行证获取或保存接口
        getOrSaveAccessPasscode(orderVerificationCode) {
            let urlBg = require('../../../assets/images/card-bg.png');
            this.$refs.refDia.$refs.dialog.style.backgroundImage="url("+urlBg+")";
            this.$refs.refDia.$refs.dialog.style.backgroundSize="cover"
            this.$refs.refDia.$refs.dialog.style.backgroundRepeat="no-repeat"
            this.$refs.refDia.$refs.dialog.style.backgroundColor="rgb(0, 0, 0,0)"
            let accessPasscodeParam = {
                orderId: this.order.orderId,
                orderIndex: this.order.orderIndex,
                merchantId: this.order.merchantId,
                orderVerificationCode: orderVerificationCode,
            };
            saveAccessPasscode(accessPasscodeParam)
                .then((res) => {
                    if (res.code == "200" && res.data) {
                        this.qrCodeOpen = true;
                        this.qrCodeUrl = res.data.qrCodeUrl;
                        this.qrCodeUrls.push(res.data.qrCodeUrl);
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 根据订单ID和核销码查询门岗二维码信息
        getAccessPasscode(orderVerificationCode) {
            debugger
            let urlBg = require('../../../assets/images/card-bg.png');
            this.$refs.refDia.$refs.dialog.style.backgroundImage="url("+urlBg+")";
            this.$refs.refDia.$refs.dialog.style.backgroundSize="cover"
            this.$refs.refDia.$refs.dialog.style.backgroundRepeat="no-repeat"
            this.$refs.refDia.$refs.dialog.style.backgroundColor="rgb(0, 0, 0,0)"
            let accessPasscodeQueryParam = {
                orderId: this.order.orderId,
                orderVerificationCode: orderVerificationCode,
            };
            getByOrderIdAndOrderVerificationCode(accessPasscodeQueryParam)
                .then((res) => {
                    if (res.code == "200" && res.data) {
                        this.qrCodeOpen = true;
                        this.qrCodeUrl = res.data.qrCodeUrl;
                        this.qrCodeUrls.push(res.data.qrCodeUrl);
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 下载门岗通行证二维码图片
        handleDownQrCodeImg() {
            // 文件名
            let downloadName = '门岗通行证二维码.png';
            // base64
            let imgData = 'data:image/png;base64,' + this.qrCodeUrl;
            // 调用下载方法
            this.downloadFile(downloadName, imgData);
        },
        //下载
        downloadFile(fileName, content) {
            let aLink = document.createElement("a");
            let blob = this.base64ToBlob(content); //new Blob([content]);

            let evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
            aLink.download = fileName;
            aLink.href = URL.createObjectURL(blob);

            // aLink.dispatchEvent(evt);
            //aLink.click()
            aLink.dispatchEvent(
                new MouseEvent("click", {
                    bubbles: true,
                    cancelable: true,
                    view: window,
                })
            ); //兼容火狐
        },
        //base64转blob
        base64ToBlob(code) {
            let parts = code.split(";base64,");
            let contentType = parts[0].split(":")[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;

            let uInt8Array = new Uint8Array(rawLength);

            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], { type: contentType });
        },
    },
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
  background-color: #f4f4f4;
  color:#737373;
  font-size:14px;

}

li {
  list-style-type: none;
}
ul {
  padding-inline-start: 0px;
}
.span-color{
    font-size:16px;
    font-weight: bold;
    color: #F59A23;
}
.span-color-size {
    font-size:16px;
    font-weight: bold;
    color: #f59a23;
    line-height: 14px;
}
.span-detailed-info{
    color:black;
}
.gatePass {
    margin-left: 300px;
}

.qrCodeDialog {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
