<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 >订单状态 {{ dict['003'] && dict['003'].filter(({value}) => value === order.orderState)[0].label}}</span> -->
                            <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">
                            <span  style="color: rgb(64, 158, 255);cursor: pointer" @click="toServerProject"
                                >{{ order.goodsName }}></span
                            >
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="3">
                            <span >预约的服务人员</span>
                        </el-col>
                        <el-col :span="2">
                            <span class="span-color-size">{{ order.serverName }}</span>
                        </el-col>
                        <el-col :span="3">
                            <span class="span-color-size">{{ order.serverPhone }}</span>
                        </el-col>
                        <el-col :span="2">
                            <el-tag type="info" effect="dark" size="medium">{{ this.serverUser.serverLevel }}</el-tag>
                        </el-col>
                        <el-col :span="2">
                            <el-tag type="info" effect="dark" size="medium">{{ this.serverUser.serverAge }}年工龄</el-tag>
                        </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="24" style="margin-bottom: 20px">
                            <span>上门时间</span>
                            <span class="span-color-size">
                                {{ order.appointmentStartTime }}
                            </span>
                            <span v-if="this.qrCodeUrl">
                                <el-button
                                    size="mini"
                                    type="primary"
                                    class="gatePass"
                                    @click="getAccessPasscode()"
                                    >门岗通行证
                                </el-button>
                            </span>
                            <span v-if="!this.qrCodeUrl && order.orderState === '001'">
                                <el-button
                                    size="mini"
                                    type="primary"
                                    class="gatePass"
                                    @click="getOrSaveAccessPasscode()"
                                    >门岗通行证
                                </el-button>
                            </span>
                        </el-col>

                        <el-col :span="12">
                            <span>顾客信息</span>
                              <span  class="span-color-size">
                                {{ member.name }}
                                {{ member.phone }}</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.goodsCounts }}{{order.otherUnit}}</span>
                        </el-col>

                        <el-col :span="12">
                            <span>服务单价 </span
                            ><span class="span-color">{{ order.price }} </span
                            ><span>元/{{order.otherUnit}}</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.maintenanceAmount > 0">
                <el-row style="margin-bottom: 10px">
                    <span class="span-detailed-info"><b>收取维修/配件费</b></span>
                </el-row>
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <span
                                >收取金额 ￥{{ order.maintenanceAmount }}</span
                            >
                        </el-col>
                        <el-col :span="12">
                            <span>费用说明 </span
                            ><span style="word-break: break-all">{{
                                order.maintenanceRemark
                            }}</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
                                >服务数量
                                {{
                                    parseInt(order.addCount) +
                                    parseInt(order.goodsCounts)
                                }}{{order.otherUnit}}</span
                            >
                        </el-col>

                        <el-col :span="12">
                            <span>订单实付 ￥{{ order.totalAmount }}</span>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>

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

            <!-- <el-col
                :span="24"
                v-if="
                    order.maintenanceAmount != null &&
                    order.maintenanceAmount != '' &&
                    order.maintenanceAmount != undefined
                "
            >
                <el-card>
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <span>收取维修/配件费 </span>
                        </el-col>

                        <el-col :span="12" style="margin-bottom: 20px">
                            <span
                                >收取金额 {{ order.maintenanceAmount }}元</span
                            >
                        </el-col>
                        <el-col :span="12">
                            <span>费用说明 {{ order.maintenanceRemark }}</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"
                            :show-close="false"
                            ref="refDia"
                            >
                            <div ref="reference" 
                            :style="'background-image:url('+urlBg+');background-repeat:no-repeat;background-size:100% 100%;height:595px;width:380px;background-color: rgba(0, 0, 0, 0)'"
                            >
                                <el-row class="qrCodeDialog" style="margin-top:-20px;">
                                    <div style="font-size:25px;color:#fff;padding-bottom:5px;margin-top:30px;">
                                        门岗通行证
                                    </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:279px;left:180px;">
                                    <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="toImage()"> 下载图片</el-button>
                                </el-row>
                            </div>
                </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 { saveAccessPasscode, getByOrderIdAndOrderVerificationCode } from "../../../api/merchant/accessPasscode";
import { mapGetters } from "vuex";
import html2canvas from "html2canvas";
import ClipboardJS from "clipboard";

export default {
    name: "index",
    data() {
        return {
            refundOpen: false,
            order: {},
            activeNames: ["1"],
            imgSrc: "",
            goodsList: [],
            member: {},
            serverUser: {},
            recordOpen: false,
            orderRecord: [],
            refStatusOptions: [],
            refund: {},
            clipboard: null,
            qrCodeOpen: false,
            qrCodeUrl: null,
            qrCodeUrls: [],
            logoImage:require('../../../assets/logo/logo.png'),
            urlBg : require('../../../assets/images/card-bg.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.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 = "支付成功";
                    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/service");
        },
        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;
                }
            });
        },
        toImage () {
            html2canvas( this.$refs.reference, {
                width:380,
                height:596,
                backgroundColor: null,
                useCORS: true // 解决文件跨域问题
            }).then(canvas => {
                console.log(this.$refs.reference)
                const url = canvas.toDataURL('image/png') // 生成的图片
                if (window.navigator.msSaveOrOpenBlob) {
                        const bstr = atob(url.split(',')[1])
                        let n = bstr.length
                        const u8arr = new Uint8Array(n)
                        while (n--) {
                        u8arr[n] = bstr.charCodeAt(n)
                        }
                        const blob = new Blob([u8arr])
                        window.navigator.msSaveOrOpenBlob(blob, '门岗通行证' + '.' + 'png')
                    } else {
                        // 这里就按照chrome等新版浏览器来处理
                        const a = document.createElement('a')
                        a.href = url
                        a.setAttribute('download', '门岗通行证')
                        a.click()
                    }
            })   
        },
           // 获取或保存门岗通行证信息
        getOrSaveAccessPasscode() {
            this.$refs.refDia.$refs.dialog.style.backgroundColor="rgb(0, 0, 0,0)"
            this.$refs.refDia.$refs.dialog.style.WebkitBoxShadow="0 0px 0px rgb(0 0 0 / 30%)"
            this.$refs.refDia.$refs.dialog.style.boxShadow="0px"
            let accessPasscodeParam = {
                "orderId": this.order.orderId,
                "orderIndex": this.order.orderIndex,
                "merchantId": this.order.merchantId,
                "orderVerificationCode": null
            }
            // 调用门岗通行证获取或保存接口
            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() {
            this.$refs.refDia.$refs.dialog.style.backgroundColor="rgb(0, 0, 0,0)"
            this.$refs.refDia.$refs.dialog.style.WebkitBoxShadow="0 0px 0px rgb(0 0 0 / 30%)"
            this.$refs.refDia.$refs.dialog.style.boxShadow="0px"
            let accessPasscodeQueryParam = {
                "orderId": this.order.orderId,
                "orderVerificationCode": null
            }
            getByOrderIdAndOrderVerificationCode(accessPasscodeQueryParam).then((res) => {
                if (res.code == "200") {
                    if (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-weight: bold;
    color: #F59A23;
}
.span-color-size {

    font-weight: bold;
    color: #f59a23;
    line-height: 14px;
}
.span-detailed-info{
    color:black;
}
.gatePass {
    margin-left: 290px;
}
.qrCodeDialog {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
