<template>
    <div
        class="page"
        :class="{ 'page--iphoneX': iphoneX, page_red: theme === 1 }"
    >
        <div class="page__content">
            <div class="row" v-if="orderStatus !== '3'">
                <div class="row__title row__title--must">退款类型</div>
                <div class="row__button">
                    <div
                        class="row__btn"
                        :class="{ 'row__btn--active': refundType === '1' }"
                        @click="setRefundType('1')"
                    >
                        退货且退款
                    </div>
                    <div
                        class="row__btn"
                        :class="{ 'row__btn--active': refundType === '2' }"
                        @click="setRefundType('2')"
                    >
                        仅退款
                    </div>
                </div>
            </div>
            <div class="row" v-if="orderStatus !== '3' && refundType === '2'">
                <div class="row__title row__title--must">是否收到商品</div>
                <picker
                    mode="selector"
                    :range="isReceiveList"
                    range-key="name"
                    :value="isReceiveIndex"
                    @change="isReceiveHandle"
                >
                    <div class="row__select">
                        <div class="row__text">
                            {{ isReceiveText || "请选择是否收到商品" }}
                        </div>
                        <img
                            class="row__arrows"
                            src="/static/icon/arrows_bottom.png"
                            alt=""
                        />
                    </div>
                </picker>
            </div>
            <div class="row" v-if="refundType || orderStatus === '3'">
                <div class="row__title row__title--must">退货退款原因</div>
                <picker
                    mode="selector"
                    :range="causeList"
                    range-key="value"
                    :value.sync="causeIndex"
                    @change="causeHandle"
                >
                    <div class="row__select">
                        <div class="row__text">
                            {{ cause || "请选择退货退款原因" }}
                        </div>
                        <img
                            class="row__arrows"
                            src="/static/icon/arrows_bottom.png"
                            alt=""
                        />
                    </div>
                </picker>
                <div class="row__explain">{{ causeText || "" }}</div>
            </div>
            <div class="row">
                <div class="row__title">退款金额</div>
                <input class="row__input" type="digit" v-model="refundPrice" />
                <div class="row__explain">
                    {{ refundPriceText || "最多可退款¥" + (price || "0.00") }}
                </div>
            </div>
            <div class="title">该笔交易退款将原路返回</div>
            <div class="row">
                <div class="row__title">退款说明</div>
                <div class="row__content">
                    <textarea
                        class="row__textarea"
                        v-model="remark"
                        maxlength="-1"
                        placeholder="请填写退款说明"
                    ></textarea>
                </div>
            </div>
            <div class="bottom">
                <div class="bottom__title">上传照片</div>
                <ul class="upload">
                    <li
                        class="upload__item"
                        v-for="(item, index) in imageList"
                        :key="index"
                    >
                        <img class="upload__img" :src="item" alt="" />
                        <img
                            class="upload__close"
                            src="/static/icon/close.png"
                            @click="removeImage(item)"
                            alt=""
                        />
                    </li>
                    <li
                        v-if="imageList.length < 8"
                        class="upload__item upload__add"
                        @click="upload"
                    >
                        <img
                            class="upload__camera"
                            src="/static/icon/camera.png"
                            alt=""
                        />
                        <div class="upload__text">添加图片</div>
                    </li>
                </ul>
                <div class="bottom__text">上传凭证，最多8张</div>
            </div>
        </div>
        <div class="submit" :class="{ 'submit--iphoneX': iphoneX }">
            <div class="submit__btn" @click="submit">提交</div>
        </div>
    </div>
</template>

<script>
export default {
    name: "",

    // 数据
    data() {
        return {
            orderId: "",
            orderItemId: "",
            orderStatus: "",
            applyId: "",
            type: "",
            refundType: "",
            causeIndex: "",
            cause: "",
            causeText: "",
            causeList: [],
            isReceiveIndex: "",
            isReceive: "",
            isReceiveText: "",
            isReceiveList: [],
            causeConfig: {},
            price: "",
            refundPrice: "",
            imageList: [],
            remark: "",
        };
    },

    onShow() {
        const self = this;

        self.orderId = self.$mp.query.orderId;
        self.orderItemId = self.$mp.query.orderItemId;
        self.orderStatus = self.$mp.query.orderStatus;
        self.applyId = self.$mp.query.applyId;
        self.type = self.$mp.query.type;
        self.price = self.$mp.query.price
            ? Number(self.$mp.query.price / 100).toFixed(2)
            : "";
        self.refundPrice = self.price;
        self.getCauseConfig();

        if (self.type === "update") {
            self.fn.setTitle("修改申请");
        }
    },

    // 函数
    methods: {
        // 获取原因配置
        getCauseConfig() {
            const self = this;

            self.api.get("/AfterSale/GetAfterSaleConfig").then((res) => {
                self.causeConfig = JSON.parse(res.data);

                self.causeList = self.causeConfig.refund;
                self.isReceiveList = self.causeConfig.isReceive;

                if (self.applyId && self.type === "update") {
                    self.getInfo();
                }
            });
        },

        // 获取详情
        getInfo() {
            const self = this;

            self.api
                .get("/AfterSale/GetDetailByOrderItemId", {
                    orderItemId: self.orderItemId,
                })
                .then((res) => {
                    let data = res.data;

                    self.refundType = data.type === 1 ? "2" : "1";
                    self.setRefundType(self.refundType);

                    self.causeList.forEach((item, index) => {
                        if (item.value === data.applyReason) {
                            self.cause = item.value;
                            self.causeText = item.text;
                            self.causeIndex = index;
                        }
                    });

                    self.isReceiveList.forEach((item, index) => {
                        if (item.value === data.received.toString()) {
                            self.isReceive = item.value;
                            self.isReceiveText = item.name;
                            self.isReceiveIndex = index;
                        }
                    });

                    self.refundPrice = Number(data.refundAmount / 100).toFixed(
                        2
                    );
                    self.imageList = data.images;
                    self.remark = data.applyRemark;
                });
        },

        // 设置退款类型
        setRefundType(type) {
            const self = this;

            self.refundType = type;

            if (type === "1") {
                self.causeList = self.causeConfig.salesReturn;
            } else {
                self.causeList = self.causeConfig.refund;
            }

            self.isReceive = "";
            self.isReceiveText = "";
            self.cause = "";
            self.causeText = "";
        },

        // 是否收到商品处理
        isReceiveHandle(e) {
            const self = this;
            let index = e.detail.value;

            self.isReceive = self.causeConfig.isReceive[index].value;
            self.isReceiveText = self.causeConfig.isReceive[index].name;
        },

        // 退款原因处理
        causeHandle(e) {
            const self = this;
            let index = e.detail.value;

            self.cause = self.causeList[index].value;
            self.causeText = self.causeList[index].text;
        },

        // 上传图片
        upload() {
            const self = this;
            let list = ["拍照", "我的相册"];
            self.fn.showActionSheet(list).then((index) => {
                uni.chooseImage({
                    count: 8,
                    sizeType: ["original", "compressed"],
                    sourceType: index === 0 ? ["camera"] : ["album"],
                    success(res) {
                        const filePaths = res.tempFilePaths;

                        filePaths.forEach((item) => {
                            uni.uploadFile({
                                header: {
                                    appId: self.config.appId,
                                    companyId: self.$store.state.user.companyId,
                                    userId: self.$store.state.user.userId,
                                    Authorization: "Bearer " + self.token,
                                },
                                url: self.config.apiBaseUrl + "/Upload/Image",
                                filePath: item,
                                name: "file",
                                formData: {},
                                success: function (res) {
                                    let data = JSON.parse(res.data);

                                    uni.hideLoading();

                                    if (self.imageList.length < 8) {
                                        self.imageList.push(data.data);
                                    }
                                },
                            }).onProgressUpdate((res) => {
                                if (res.progress < 100) {
                                    uni.showLoading({
                                        title: "上传中 " + res.progress,
                                        mask: true,
                                    });
                                }
                            });
                        });
                    },
                });
            });
        },

        // 删除图片
        removeImage(val) {
            const self = this;

            self.imageList.forEach((item, index) => {
                if (item === val) {
                    self.imageList.splice(index, 1);
                }
            });
        },

        // 提交申请
        submit() {
            const self = this;

            if (self.orderStatus !== "3" && !self.refundType) {
                self.fn.showToast("请选择退款类型");
            } else if (
                self.orderStatus !== "3" &&
                self.refundType === "2" &&
                !self.isReceive
            ) {
                self.fn.showToast("请选择是否收到商品");
            } else if (!self.cause) {
                self.fn.showToast("请选择原因");
            } else if (!self.refundPrice) {
                self.fn.showToast("请填写退款金额");
            } else if (self.refundPriceText) {
                self.fn.showToast("退款金额不正确");
            } else {
                if(this.refundType==='1' && this.orderStatus!='20'){
                    return self.fn.showToast("退货必须上传图片");
                }

                if (self.applyId && self.type === "update") {
                    // 修改申请
                    self.api
                        .post("/AfterSale/UpdateApply", {
                            id: Number(self.applyId),
                            orderId: self.orderId,
                            orderItemId: self.orderItemId,
                            type: self.refundType === "1" ? 1 : 0,
                            receivedGoods: Number(self.isReceive),
                            reason: self.cause,
                            refundAmount: parseInt(self.refundPrice * 100),
                            remark: self.remark,
                            images: self.imageList,
                        })
                        .then((res) => {
                            self.fn.getMsgTpls(
                                    res.data,
                                self.refundType === "1" ? 4 : 5,
                                () => {
                                    self.router.back();
                                }
                            );
                        });
                } else {
                    // 提交申请
                    self.take(function () {
                        self.api
                            .post("/AfterSale/Apply", {
                                id: self.applyId ? Number(self.applyId) : 0,
                                orderId: self.orderId,
                                orderItemId: self.orderItemId,
                                type: self.refundType === "1" ? 1 : 0,
                                receivedGoods: Number(self.isReceive),
                                reason: self.cause,
                                refundAmount: parseInt(self.refundPrice * 100),
                                remark: self.remark,
                                images: self.imageList,
                            })
                            .then((res) => {
                                self.fn.getMsgTpls(
                                    res.data,
                                    self.refundType === "1" ? 4 : 5,
                                    () => {
                                        self.router.back();
                                    }
                                );
                            });
                    });
                }
            }
        },

        // 订阅
        take(callback) {
            const self = this;
            let type = self.refundType === "1" ? 4 : 5;

            self.api
                .get("/Subscription/GetMsgTpls", {
                    type: type,
                })
                .then((res) => {
                    uni.requestSubscribeMessage({
                        tmplIds: res.data,
                        complete: () => {
                            callback();
                        },
                        fail: (err) => {
                            console.log(err);
                        },
                    });
                });
        },
    },

    // 数据计算
    computed: {
        // 判断主题  1:红色  2：绿色
        theme() {
            return this.$store.state.common.theme;
        },
        user() {
            return this.$store.state.user || "";
        },
        token() {
            return this.$store.state.user.token;
        },
        refundPriceText() {
            const self = this;
            let text = "";
            let reg = /^\d+(?:.\d{1,2})?$/;

            if (Number(self.refundPrice) > Number(self.price)) {
                text = "退款额度不能超过退款商品总价¥" + self.price;
            }

            if (!reg.test(self.refundPrice || self.refundPrice < 0)) {
                text =
                    "退款金额为≥0且≤" + self.price + "的数字，最多保留两位小数";
            }

            return text;
        },
    },

    // 数据监听
    watch: {},
};
</script>

<style lang="scss" scoped>
.page {
    padding-bottom: px(200);

    &__content {
        padding: px(50) 0;
        border-top: solid px(25) #f8f8f8;
        background-color: #fff;
    }

    &--iphoneX {
        padding-bottom: px(230);
    }
}

.row {
    padding: px(40);

    &__title {
        display: flex;
        align-items: center;
        font-size: px(36);
        color: #333;

        &--must:after {
            content: "*";
        }
    }

    &__button {
        display: flex;
        align-items: center;
        margin-top: px(30);
    }

    &__btn {
        display: flex;
        justify-content: center;
        align-items: center;
        height: px(75);
        padding: 0 px(40);
        margin-right: px(15);
        font-size: px(36);
        color: #666;
        border: solid px(3) #999;

        &--active {
            color: #27a34f;
            border-color: #27a34f;
        }
    }

    &__select {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: px(85);
        padding: 0 px(40);
        margin-top: px(20);
        border-radius: px(10);
        background-color: #f5f5f5;
    }

    &__text {
        font-size: px(36);
        color: #333;
    }

    &__arrows {
        width: px(40);
        height: px(40);
    }

    &__explain {
        margin-top: px(20);
        font-size: px(36);
        color: #999;
    }

    &__input {
        height: px(85);
        padding: 0 px(40);
        margin-top: px(20);
        border-radius: px(10);
        background-color: #f5f5f5;
    }

    &__content {
        width: 100%;
        height: px(230);
    }

    &__textarea {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding: px(40);
        margin-top: px(20);
        font-size: px(36);
        color: #333;
        border-radius: px(10);
        background-color: #f5f5f5;
    }
}

.title {
    display: flex;
    align-items: center;
    height: px(100);
    padding: 0 px(40);
    font-size: px(36);
    color: #999;
    background-color: #f8f8f8;
}

.bottom {
    padding: px(50) px(40);

    &__title {
        font-size: px(36);
        color: #333;
    }

    &__text {
        font-size: px(36);
        color: #999;
    }
}

.upload {
    display: flex;
    flex-wrap: wrap;
    margin-top: px(20);

    &__item {
        position: relative;
        width: px(180);
        height: px(180);
        margin: 0 0 px(25) px(25);

        &:nth-child(5n + 1) {
            margin-left: 0;
        }
    }

    &__img {
        width: 100%;
        height: 100%;
    }

    &__close {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 1;
        width: px(50);
        height: px(50);
        transform: translate(50%, -50%);
    }

    &__add {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: #f5f5f5;
    }

    &__camera {
        width: px(60);
        height: px(60);
    }

    &__text {
        margin-top: px(20);
        font-size: px(36);
        color: #999;
    }
}

.submit {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 995;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: px(170);
    background-color: #fff;

    &--iphoneX {
        padding-bottom: px(30);
    }

    &__btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: px(970);
        height: px(110);
        font-size: px(42);
        color: #fff;
        border-radius: px(55);
        background-color: #27a34f;
    }
}
.page_red {
    .row__btn--active {
        color: #27a34f;
        border-color: #27a34f;
    }
    .submit__btn {
        background-color: #27a34f;
    }
}
</style>