<template>
    <div class="app-container">
        <!-- 查询和其他操作 -->
        <div class="filter-container" ref="container">
            <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 150px;"
                placeholder="客户或预约手机" />
            <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 170px;"
                placeholder="请输入订单编号" />
            <el-date-picker v-model="listQuery.timeArray" type="datetimerange" class="filter-item" style="width:320px"
                range-separator="至" start-placeholder="下单开始日期" end-placeholder="下单结束日期" :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss" />
            <el-select v-model="listQuery.orderStatusArray" multiple style="width: 150px" class="filter-item"
                placeholder="请选择订单状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
            </el-select> 

            <el-select v-model="listQuery.cityId" clearable style="width: 120px" class="filter-item" placeholder="请选择城市"
                multiple>
                <el-option v-for="item in city" :key="item.id" :label="item.cityName" :value="item.id" />
            </el-select>

            <el-select v-model="listQuery.orderChannel" style="width: 160px" class="filter-item" placeholder="请选择渠道"
                clearable multiple>
                <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id" />
            </el-select> 
        
            <el-button v-permission="['GET /admin/orderStorage/orderList']" class="filter-item" type="primary"
                icon="el-icon-search" @click="handleFilter">查找</el-button>
        </div>

        <el-tabs v-model="listQuery.tab" @tab-click="handleClick">
            <el-tab-pane label="所有订单" name="0" />
            <!-- <el-tab-pane label="已付款-未处理" name="5" /> -->
            <el-tab-pane label="已付款" name="1" />
            <el-tab-pane label="待付款" name="2" />
            <el-tab-pane label="已取消" name="3" />
            <el-tab-pane label="已退款" name="4" />
        </el-tabs>

        <!-- 查询结果 -->
        <div :style="{ height: tableHeight }">
            <el-table v-loading="listLoading" :data="list" ref="table" :height="tableMaxHeight"
                element-loading-text="正在查询中。。。" border fit highlight-current-row>

                <el-table-column align="center" label="订单编号"  :key="Math.random()" width="150" prop="orderSn">
                    <template slot-scope="scope">
                        {{ scope.row.orderSn }}<i class="el-icon-copy-document"
                            style="margin-left:5px;color:#46a6ff;cursor: pointer;"
                            @click="fnCopy(scope.row.orderSn, scope.row.orderChannel)"></i>
                    </template>
                </el-table-column>
                
                <el-table-column align="center" label="订单状态" width="130" prop="statusTxt"/>  
                <el-table-column align="center" width="150" label="订购商品" prop="goodsName"/>  

                <el-table-column align="center" label="预约人信息" prop="consignee" width="320px">
                    <template slot-scope="scope">
                        <div style="text-align: left;"> 
                            <span style="font-weight: 600;">联系人：</span> {{ scope.row.consignee }}<br />
                            <span style="font-weight: 600;">联系电话：</span> {{ scope.row.mobile }}<br />
                            <span style="font-weight: 600;">预约城市：</span> {{ scope.row.city }}<br />
                            <span style="font-weight: 600;">预约地址:</span> {{ scope.row.address }}<br /> 
                            <span style="font-weight: 600;">预约备注:</span> {{ scope.row.message }}<br /> 
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" label="预约手机" prop="mobile">
                    <template slot-scope="scope">
                        {{ scope.row.mobile }}<i class="el-icon-copy-document"
                            style="margin-left:5px;color:#46a6ff;cursor: pointer;" @click="fnCopy(scope.row.mobile)"></i>
                    </template>
                </el-table-column> -->
                <el-table-column align="center" label="下单时间" min-width="90" prop="createTime" />
                <!-- <el-table-column align="center" label="城市" width="80" prop="city"/>  -->
                <el-table-column align="center" label="订单加盟商" width="80" prop="fraName">
                    <template slot-scope="scope">
                        {{ scope.row.fraName }}<br />{{ scope.row.fraTel }}
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" label="服务地址" width="255" prop="address">
                    <template slot-scope="scope">
                        {{ scope.row.address }}<i class="el-icon-copy-document"
                            style="margin-left:5px;color:#46a6ff;cursor: pointer;" @click="fnCopy(scope.row.address)"></i>
                    </template>
                </el-table-column> -->
                <!-- <el-table-column align="center" label="客户备注" prop="message" />  -->
                <el-table-column align="center" label="订单渠道" min-width="90" prop="orderChannel">
                    <template slot-scope="scope">
                        <el-tag type="success">
                            {{ scope.row.orderChannel | channelsFilter }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column align="center" width="70" label="支付金额" prop="actualPrice" />
                <el-table-column align="center" width="70" label="券抵扣金额" prop="couponPrice" />
                <el-table-column align="center" width="70" label="已退款金额" prop="refundAmount" />

                <!-- <el-table-column align="center" label="支付时间" min-width="100" prop="payTime" /> -->

                <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" width="200">
                    <template slot-scope="scope">
                        <el-button v-permission="['GET /admin/order/detail']" type="text" size="mini" icon="el-icon-view"
                            @click="handleDetail(scope.row)">详情</el-button>
                        <el-button v-permission="['GET /admin/orderbook/detail']" type="text" style="color:green"
                            icon="el-icon-fork-spoon" v-if="scope.row.orderStatus >= 201" size="mini"
                            @click="handleBook(scope.row)">服务详情</el-button>
                        <el-button v-permission="['POST /admin/order/updateOrderAddress']" type="text" icon="el-icon-edit"
                            size="mini" @click="updateOrderAddress(scope.row)">修改地址</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />


        <!-- 修改地址 -->
        <el-dialog :visible.sync="updateAddressVisible" title="修改地址" width="660px" center>
            <el-form ref="updateAddressForm" :model="updateAddressForm" :rules="updateAddressFormRules" status-icon
                label-position="left" label-width="200px" style=" padding:10px 30px">
                <el-row :gutter="60">
                    <el-form-item label="预约人" prop="consignee">
                        <el-input v-model="updateAddressForm.consignee" clearable placeholder="请输入预约联系人" />
                    </el-form-item>
                </el-row>
                <el-row :gutter="60">
                    <el-form-item label="预约电话" prop="mobile">
                        <el-input v-model="updateAddressForm.mobile" clearable placeholder="请输入预约联系人的电话" />
                    </el-form-item>
                </el-row>
                <el-row :gutter="60">
                    <el-form-item label="省市区" prop="area">
                        <el-cascader style="width:100%" :options="areaList" v-model="updateAddressForm.area" ref="cascader1"
                            @change="handleUpdateAreaChange" clearable></el-cascader>
                    </el-form-item>
                </el-row>
                <el-row :gutter="60">
                    <el-form-item label="服务地址" prop="addressDetail">
                        <el-input v-model="updateAddressForm.addressDetail" clearable />
                    </el-form-item>
                </el-row>

                <el-row :gutter="60">

                    <el-form-item label="是否取消已预约未服务工单" prop="cancelBookOrderDetail">
                        <!-- <el-select v-model="updateAddressForm.cancelBookOrderDetail" style="width:100%" placeholder="请选择支付渠道">
  
                  <el-option label="是" value="1" />
                  <el-option label="否" value="0" />
                </el-select> -->
                        <el-radio-group v-model="updateAddressForm.cancelBookOrderDetail">
                            <el-radio label="1">是</el-radio>
                            <el-radio label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>



                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="updateAddressVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmUpdateAddress">确定</el-button>
            </div>
        </el-dialog>


 
        <addressSelectRef ref="addressSelectRef" />

        <!-- 订单详情对话框 -->
        <orderInfoRef ref="orderInfoRef" />

    </div>
</template>
  
<script>
import axios from "axios";
// import areaJson from "../../areaJson";
import { regionData, regionDataPlus } from "element-china-area-data";
import {
    updateOrderAddress, getAllFras, getOrderVerifyInfo
} from "@/api/order";
import {
    orderList
} from "@/api/orderStorage";
import { allChannel } from "@/api/channel";
import { send, getSmsTemplate } from "@/api/sms";
import { allRange } from "@/api/serviceTimeRange";
import {
    statusMap,
    statusModifyMap,
    bookStatusMap,
    ObjectToArray,
    cancelReasonList,
    changeReasonMap
} from "@/api/enumUtils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import { getUserCity } from "@/api/city";
import checkPermission from "@/utils/permission"; // 权限判断函数
import { getSmsLog } from "@/api/sms";
import { getToken } from "@/utils/auth"; 
import addressSelectRef from '@/views/order/components/addressSelectRef'
import orderInfoRef from '@/views/order/components/orderInfoRef.vue'

let vm;

const orderTypeMap = {
    0: "默认下单",
    1: "代客下单",
    2: "赠送单",
    3: "理赔单",
};

export default {
    name: "Order",
    components: { Pagination,  addressSelectRef, orderInfoRef },
    filters: {
        aftersaleStatusFilter(status) {
            if (status == 1) return "-退款申请中";
            if (status == 2) return "-退款审核通过";
            if (status == 3) return "-退款成功";
            if (status == 4) return "-退款拒绝";
            if (status == 5) return "-退款取消";
            return "";
        },
        orderStatusFilter(status) {
            return statusMap[status];
        },
        channelsFilter(value) {
            const rs = vm.channels.filter((item) => {
                return item.id === value;
            });
            if (rs != null && rs.length > 0) {
                return rs[0].name;
            }
        },
        orderTypeFilter(value) {
            if (value == 0) return "默认";
            if (value == 1) return "代客下单";
            if ((value = 2)) return "赠送单";
            if (value == 3) return "理赔单";
            return "";
        },
        bookStatusFilter(status) {
            return bookStatusMap[status];
        },
    },
    data() {
        var payChannelValid = (rule, value, callback) => {
            if (
                this.orderInputForm.orderType == 1 &&
                (value == null || value == "")
            ) {
                callback(new Error("请输入服务时长"));
            } else {
                callback();
            }
        };

        return {
            tableHeight: "600px",//表控件高度
            activeIndex: '',
            payChannelMap: { "WX": '微信', 'ZFB': '支付宝', 'DOUYIN': '抖音' },
            showbaogangRefund: false,
            bgData: {
                orderNo: "",
                serviceContractNo: "",
                reason: "",
                operName: "",
            },
            fras: [],//加盟商列表
            city: [],
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                name: undefined,
                mobile: undefined,
                tab: "0",
                timeArray: ['', ''], 
                orderStatusArray: [], 
            },
            pickerOptions: {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            },
            areaList: [],
            channels: [],
            statusMap: statusMap,
            statusModifyMap: statusModifyMap,
            bookStatusMap: bookStatusMap,
            bookStatusMapValue: ObjectToArray(bookStatusMap),
            orderTypeMap,
            orderTypeMapInput: {
                1: "代客下单",
                2: "赠送单",
                3: "理赔单",
            },
            orderDialogVisible: false,
            orderDetail: {
                order: {},
                user: {},
                orderGoods: [],
                refundList: [],
                commission: {},
                fraInfo: {}
            },
            editVisible: false,
            shopList: [],
            supplierList: [],
            itemList: [],
            timeListAppoint: [],
            servantList: [],
            updateAddressVisible: false,
            updateAddressForm: {
                area: '',
                addressDetail: '',
                cancelBookOrderDetail: '',
                mobile: '',
                consignee: ''
            },
            updateOrderInfo: {},
            updateAddressFormRules: {
                consignee: [
                    { required: true, message: "请输入客户名称", trigger: "blur" },
                ],
                mobile: [
                    { required: true, message: "请输入客户电话", trigger: "blur" },
                ],
                area: [{ required: true, message: "请选择省市区", trigger: "change" }],
                addressDetail: [
                    { required: true, message: "请输入客户地址", trigger: "blur" },
                ],
                goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],

                cancelBookOrderDetail: [
                    {
                        required: true,
                        message: "是否取消已预约未服务工单",
                        trigger: "blur",
                    },
                ]
            }

        };
    },
    computed: {
        tableMaxHeight() {
            console.info(window.innerWidth)
            this.tableHeight = window.innerHeight - (window.innerWidth > 1800 ? 280 : 330) + "px";
            return this.tableHeight;
        },
    },
    beforeCreate() {
        vm = this;
    },
    created() {
        allChannel().then((res) => {
            this.channels = res.data.data;
        });
        this.getCity();
        let orderSn = this.$route.query.orderSn;
        if (orderSn) {
            this.listQuery.orderSn = orderSn;
        }
        allRange().then((res) => {
            this.timerange = res.data.data;
        });
        this.getList();
        this.getAllFras();
    },
    methods: {
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        getAllFras() {
            getAllFras().then(res => {
                this.fras = res.data.data
            })
        },
        getCity() {
            getUserCity().then((res) => {
                this.city = res.data.data;
                //去除非业务城市
                this.areaList = [];
                regionData.forEach(p => {
                    if (this.city.filter(city => { return city.cityName == p.label }).length > 0)
                        this.areaList.push(p);
                    else {
                        let province = { label: p.label, value: p.value, children: [] };
                        p.children.forEach(c => {
                            if (this.city.filter(city => { return city.cityName == c.label }).length > 0)
                                province.children.push(c);
                        })
                        if (province.children.length > 0)
                            this.areaList.push(province);
                    }

                })
            });
        }, 
        getList() {
            this.listLoading = true;
            if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
                this.listQuery.start = this.listQuery.timeArray[0];
                this.listQuery.end = this.listQuery.timeArray[1];
            } else {
                this.listQuery.start = null;
                this.listQuery.end = null;
            }

            orderList(this.listQuery)
                .then((response) => {
                    this.list = response.data.data.list;
                    this.total = response.data.data.total;
                    this.listLoading = false;
                    this.$refs.table.doLayout();
                })
                .catch(() => {
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
        },
        handleClick() {
            this.getList();
        },
        /*************************************预约单相关操作 **************************************/
        getServantList(id) {
            getAssignmentPerson(id).then((res) => {
                this.servantList = res.data.data;
            });
        },
        handleExpandChange(row, expandRows) {
            console.log("handleExpandChange");
            //console.log(expandRows);
            if (!row.isLoadBookDetail) {
                orderBookDetail(row.id).then((res) => {
                    res.data.data.forEach((item) => {
                        row.bookDetailList.push(item);
                    });
                });
                row.isLoadBookDetail = true;
            }
        },
        getTimeList(type) {
            let timeList = [];
            this.timerange.forEach(e => {
                let str = e.startTime + "-" + e.endTime;
                if (e.duration == type && timeList.includes(str) == false) {
                    timeList.push(str)
                }
            })
            return timeList;
        },
        getAppointTime() {
            if (
                this.reassignForm.bookDate == "" ||
                this.reassignForm.bookDate == null
            ) {
                this.$message.warning("请先选择日期");
                return false;
            } else if (this.reassignForm.servantId == "") {
                this.$message.warning("请先选择服务者");
                return false;
            } else {
                let list = [];
                this.timeList.forEach((item) => {
                    let obj = {
                        startTime: item.split("-")[0],
                        endTime: item.split("-")[1],
                    };
                    list.push(obj);
                });
                let params = {
                    workerId: this.reassignForm.servantId,
                    reservationDate: this.reassignForm.bookDate,
                    timesList: list,
                };
                getAssignmentPersonTime(params)
                    .then((res) => {
                        console.log(res);
                        let reslist = res.data.data.timesList;
                        this.timeListAppoint = reslist.map((item) => {
                            return item.startTime + "-" + item.endTime;
                        });
                    })
                    .catch((response) => { });
            }
        },
        servantChange(value) {
            console.log(value);
            this.timeListAppoint = [];
            this.reassignForm.bookTime = "";
        },
        handleDetail(row) {
            this.$refs.orderInfoRef.getDetail(row.id);
        },
        handleBook(row) {
            console.info(row)
            //工单情况
            this.$router.push({
                path: "/order/storage/storageBookList",
                query: {
                    orderSn: row.orderSn,
                },
            });
        },

        handleUpdateAreaChange(value) {
            console.log(value);
            console.log(this.updateAddressForm.area == "");
            let node = this.$refs["cascader1"].getCheckedNodes();
            console.log(node);
            if (node.length > 0) {
                console.log(node[0].path, node[0].pathLabels);
                this.updateAddressForm.areaCode = node[0].path[2];
                this.updateAddressForm.province = node[0].pathLabels[0];
                this.updateAddressForm.city = node[0].pathLabels[1];
                this.updateAddressForm.county = node[0].pathLabels[2];
                if (
                    node[0].pathLabels[2] == "市辖区" &&
                    node[0].pathLabels[0] != "北京市" &&
                    node[0].pathLabels[0] != "上海市" &&
                    node[0].pathLabels[0] != "重庆市" &&
                    node[0].pathLabels[0] != "天津市"
                ) {
                    this.$notify.error({
                        title: "请选择具体区域",
                    });
                    this.updateAddressForm.area = "";
                    return false;
                }

            }
        },
        updateOrderAddress(row) {
            let location = [];
            if (row.position && row.position.length > 6)
                location = row.position.split(',');

            this.$refs.addressSelectRef.init(row.id, row.mobile, row.consignee, row.address, location);
        },
        confirmUpdateAddress() {
            this.$refs["updateAddressForm"].validate((valid) => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: "提交中...",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.5)",
                    });
                    updateOrderAddress({
                        addressDto: {
                            addressDetail: this.updateAddressForm.addressDetail,
                            areaCode: this.updateAddressForm.areaCode,
                            city: this.updateAddressForm.city,
                            county: this.updateAddressForm.county,
                            province: this.updateAddressForm.province,
                            name: this.updateAddressForm.consignee,
                            tel: this.updateAddressForm.mobile
                        },
                        orderId: this.updateOrderInfo.id,
                        cancelBookOrderDetail: this.updateAddressForm.cancelBookOrderDetail,
                    })
                        .then((response) => {
                            loading.close();
                            this.updateAddressVisible = false;
                            this.$notify.success({
                                title: "成功",
                                message: "修改成功",
                            });
                            this.getList();
                        })
                        .catch((response) => {
                            loading.close();
                            this.$notify.error({
                                title: "修改失败",
                                message: response.data.errmsg,
                            });
                        });
                    // });
                }
            });
        },
    },
};
</script> 
<style> .pagination-container {
     margin-top: 0px;
     padding: 5px 16px !important;
 }


 .detail-container {
     width: 80%;
     padding: 20px 20px 20px 20px;
     margin: 20px auto;
 }

 .operate-container {
     background: #f2f6fc;
     height: 80px;
     margin: -20px -20px 0;
     line-height: 80px;
 }

 .operate-button-container {
     float: right;
     margin-right: 20px;
 }

 .table-layout {
     margin-top: 20px;
     border-left: 1px solid #dcdfe6;
     border-top: 1px solid #dcdfe6;
 }

 .table-cell {
     height: 60px;
     line-height: 20px;
     border-right: 1px solid #dcdfe6;
     border-bottom: 1px solid #dcdfe6;
     padding: 10px;
     font-size: 14px;
     color: #606266;
     text-align: center;
     white-space: pre-wrap;
     /* overflow: hidden; */
 }

 .table-cell-title {
     border-right: 1px solid #dcdfe6;
     border-bottom: 1px solid #dcdfe6;
     padding: 10px;
     background: #f2f6fc;
     text-align: center;
     font-size: 14px;
     color: #303133;
 }

 .el-table th.gutter {
     display: table-cell !important;
 }

 .el-button+.el-button {
     margin-left: 0px;
 }

 .el-table colgroup.gutter {
     display: table-cell !important;
 }

 .el-table .warning-row {
     background: oldlace;
 }

 .el-table .success-row {
     background: #f0f9eb;
 }

 .color-danger {
     color: #f56c6c;
     font-size: 18px;
 }

 .color-rebuy {
     color: #09afff;
     font-size: 18px;
 }

 .el-dialog .el-cascader {
     width: 400px;
 }

 .fixed-width .el-button--mini {
     width: auto;
     min-width: 60px;
 }

 .el-step.is-center .el-step__description {
     padding-left: 18%;
     padding-right: 18%;
 }

 .el-table th.gutter {
     display: table-cell !important;
 }
</style>
  