<template>
    <div class="app-container">
        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 160px;"
                placeholder="请输入用户手机" />
            <el-input v-model="listQuery.detailId" clearable class="filter-item" style="width: 160px;"
                placeholder="请输入服务单编号" />
            <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 160px;"
                placeholder="请输入支付订单编号" />

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

            <el-select v-model="listQuery.orderStatusArray" clearable multiple class="filter-item" placeholder="请选择服务单状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
            </el-select>
            <el-date-picker v-model="listQuery.timeArray" type="datetimerange" class="filter-item" range-separator="至"
                style="width: 340px" start-placeholder="预约开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss" />

            <el-select v-model="listQuery.fraId" style="width: 200px" class="filter-item" placeholder="请选择加盟商" clearable
                filterable>
                <el-option v-for="item in fras" :key="item.id" :label="item.fraName" :value="item.id" />
            </el-select>
            <el-button v-permission="['GET /admin/orderbook/list']" class="filter-item" type="primary" icon="el-icon-search"
                @click="handleFilter">查找</el-button>
        </div>


        <el-tabs v-model="listQuery.tab" @tab-click="handleFilter">
            <el-tab-pane label="全部" name="1" />
            <el-tab-pane label="未预约" name="7" />
            <el-tab-pane label="匹配中" name="3" />
            <el-tab-pane label="待履约" name="2" />
            <el-tab-pane label="已完成" name="4" />
            <el-tab-pane label="取消" name="5" />
            <el-tab-pane label="挂单" name="6" />
        </el-tabs>

        <!-- 查询结果 -->

        <div :style="{ height: tableHeight }">
            <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
                :height="tableMaxHeight" :row-class-name="tableRowClassName">
                <el-table-column align="center" :key="Math.random()" label="服务单编号" width="95" prop="id" />
                <el-table-column align="center" label="支付订单编号" width="135" prop="orderSn" />
                <el-table-column align="center" label="服务单状态" width="105">
                    <template slot-scope="scope">
                        <el-tag :type="getTagType(scope.row)"> {{ statusMap[scope.row.status] }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" 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.serviceCity }}<br />
                            <span style="font-weight: 600;">预约地址:</span> {{ scope.row.address }}<br />
                            <span style="font-weight: 600;">上门时段:</span> {{ scope.row.bookTime }}<br />
                            <span style="font-weight: 600;">联系电话：</span> {{ scope.row.mobile }}<br />
                            <span style="font-weight: 600;">联系人：</span> {{ scope.row.consignee }}<br />
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" label="预约联系方式" prop="mobile" />
                <el-table-column align="center" label="预约时间" prop="bookTime" />
                <el-table-column align="center" label="城市" prop="serviceCity" />
                <el-table-column align="center" label="预约地址" prop="address" /> -->
                <el-table-column align="center" label="加盟商" width="185" prop="fraName">
                    <template slot-scope="scope">
                        <div style="text-align: left;">
                            <span style="font-weight: 600;">加盟商：</span> {{ scope.row.fraName }}<br />
                            <span style="font-weight: 600;">加盟商电话：</span> {{ scope.row.fraTel }}<br />
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" label="加盟商电话" width="145" prop="fraTel" /> -->
                <el-table-column align="center" label="服务人员" prop="servantName" width="200px">
                    <template slot-scope="scope">
                        <div style="text-align: left;">
                            <span style="font-weight: 600;">服务人员：</span> {{ scope.row.servantName }}<br />
                            <span style="font-weight: 600;">联系方式：</span> {{ scope.row.servantName }}<br />
                            <span style="font-weight: 600;">类型：</span> {{ scope.row.servantName ? (scope.row.servantType == 0
                                ? '全职' : '兼职') : '' }}<br />
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" label="服务人员手机" prop="servantMobile" /> -->
                <el-table-column align="center" label="更新时间" prop="updateTime" />
                <el-table-column align="center" label="更新人" prop="updateUserName" />

                <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" width="250">
                    <template slot-scope="scope1">
                        <el-button v-permission="['POST /admin/orderbookdetail/changeWorker']" type="primary" plain size="mini"
                            @click="handleReassign(scope1.row)"
                            v-if="scope1.row.status == 1 || scope1.row.status == 0 || scope1.row.status == 7">{{
                                scope1.row.status ==
                                0 ? "预约" : "修改预约" }}</el-button>
                        <el-button v-permission="['GET /admin/orderbook/cancelBook']" type="danger" plain size="mini"
                            @click="handleCancel(scope1.row)"
                            v-if="scope1.row.status == 1 || scope1.row.status == 7">取消预约</el-button>
                        <el-button v-permission="['GET /admin/orderbook/finish']" type="success" plain size="mini"
                            @click="handleFinish(scope1.row)"
                            v-if="(scope1.row.status == 1 || scope1.row.status == 2) && scope1.row.servantMobile != ''">完成工单</el-button>

                        <el-button v-permission="['GET /admin/orderbookdetail/tranBookToFra']" type="info" plain size="mini"
                            @click="handleTranBook(scope1.row)"
                            v-if="scope1.row.status == 0 || scope1.row.status == 7">调单</el-button>

                        <el-button type="primary" plain size="mini" @click="handleLog(scope1.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="reassignDialogVisible" title="改派">
            <el-form ref="reassignForm" :model="reassignForm" status-icon label-position="left" label-width="100px"
                style="width: 400px; margin-left:50px;" :rules="rules">
                <el-form-item label="日期" prop="bookDate">
                    <el-date-picker v-model="reassignForm.bookDate" type="date" placeholder="选择日期"
                        value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="服务者" prop="servantId">
                    <el-select v-model="reassignForm.servantId" placeholder="请选择" @change="servantChange">
                        <el-option v-for="item in servantList" :key="item.code" :label="item.workerName"
                            :value="item.workerId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间段" prop="bookTime">
                    <el-select v-model="reassignForm.bookTime" placeholder="请选择" @focus="getAppointTime">
                        <el-option v-for="(item, index) in timeListAppoint" :key="index" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reassignDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmReassign">确定</el-button>
            </div>
        </el-dialog>

        <!-- 取消预约对话框 -->
        <el-dialog :visible.sync="cancelAppointVisible" title="取消预约" width="600px">
            <el-form ref="cancelAppointForm" :model="cancelAppointForm" status-icon label-position="left"
                label-width="100px" style="width: 400px; margin-left:50px;" :rules="cancelAppointrules">

                <el-form-item label="取消原因" prop="changeReason">
                    <el-select v-model="cancelAppointForm.changeReason" placeholder="请选择">
                        <el-option v-for="item in cancelReasonList" :key="item.id" :label="item.reason" :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAppointVisible = false">取消</el-button>
                <el-button type="primary" @click="cancelBook">确定</el-button>
            </div>
        </el-dialog>

        <!-- 调单给加盟商 -->
        <el-dialog :visible.sync="tranBookFormVisible" title="服务单调单" width="600px">
            <el-form ref="tranBookForm" :model="tranBookForm" status-icon label-position="left" label-width="100px"
                style="width: 400px; margin-left:50px;" :rules="cancelAppointrules">

                <el-form-item label="加盟商" prop="fraId">
                    <el-select v-model="tranBookForm.fraId" placeholder="请选择加盟商" filterable style="width:300px">
                        <el-option v-for="item in fras" :key="item.id" :label="item.fraName" :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="tranBookFormVisible = false">取消</el-button>
                <el-button type="primary" @click="saveTranBook">确定</el-button>
            </div>
        </el-dialog>
        <!-- 操作日志 -->
        <el-dialog :visible.sync="logDiaVisible" title="操作日志" center width="700px">
            <el-table :data="logList" style="width: 100%" border>
                <el-table-column prop="changeType" label="操作类型" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.changeType == 1">改派</span>
                        <span v-if="scope.row.changeType == 2">取消</span>
                    </template>
                </el-table-column>
                <el-table-column prop="changeReason" label="修改原因" />
                <el-table-column prop="newBookTime" label="新预约时间" />
                <el-table-column prop="oldBookTime" label="旧预约时间" />
                <el-table-column prop="createUser" label="操作人" />
                <el-table-column prop="createTime" label="操作时间" />
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="logDiaVisible = false">确定</el-button>
            </div>
        </el-dialog>
 

        <serviceBookRef ref="serviceBookRef" @success="reassignSuccess" />
    </div>
</template>
  
<script>
import axios from "axios"; 
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import { getUserCity } from "@/api/city";
import {list,
    cancelBook, 
    orderBookFinish,
    orderBookReassign, tranBookToFra
} from "@/api/orderStorage";

import {getAllFras,getOpLog,} from "@/api/order";
import {
    bookStatusMap,
    cancelReasonList,
    changeReasonMap
} from "@/api/enumUtils"; 
import serviceBookRef from '@/views/order/components/serviceBookRef';
let vm;

export default {
    name: "storageBookList",
    components: { Pagination, serviceBookRef },
    filters: {
        orderStatusFilter(status) {
            return statusMap[status];
        },
    },
    data() {
        return {
            tableHeight: "600px",//表控件高度
            fras: [],
            changeReasonMap: changeReasonMap,
            assignOrderId: '',
            assignOrderStatus: '',
            timerange: [],
            cancelAppointVisible: false,
            cancelOrderItem: "",
            cancelAppointrules: {
                changeReason: [
                    { required: true, message: "请选择取消原因", trigger: "change" },
                ],
            },
            cancelAppointForm: {
                changeReason: "",
            },
            cancelReasonList: cancelReasonList,
            tranBookFormVisible: false,
            tranBookForm: {
                id: '',
                fraId: ''
            },
            timeList: [],
            timeListAppoint: [],
            servantList: [],
            list: [],
            total: 0,
            listLoading: true,
            city: [],
            listQuery: {
                page: 1,
                limit: 20,
                mobile: "",
                timeArray: [],
                detailId: "",
                orderSn: this.$route.query.orderSn,
                orderStatusArray: [],
                cityId: "",
                sort: "create_time",
                order: "desc",
                tab: '1'
            },
            rules: {
                bookDate: [
                    { required: true, message: "请选择改派日期", trigger: "blur" },
                ],
                bookTime: [
                    { required: true, message: "请选择改派时间", trigger: "blur" },
                ],
                servantId: [
                    { required: true, message: "请选择服务者", trigger: "blur" },
                ],
                fraId: [
                    { required: true, message: "请选择加盟商", trigger: "blur" },
                ],
            },
            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]);
                        },
                    },
                ],
            },
            statusMap: bookStatusMap,
            orderDialogVisible: false,
            reassignDialogVisible: false,
            orderDetail: [],
            reassignForm: {
                id: "",
                bookDate: "",
                bookTime: "",
                servantId: "",
                orderId: "",
            },
            logDiaVisible: false,
            logList: [],
        };
    },
    computed: {
        tableMaxHeight() {
            this.tableHeight = window.innerHeight - (window.innerWidth > 1800 ? 280 : 330) + "px";
            return this.tableHeight;
        },
    },
    beforeCreate() {
        vm = this;
    },
    created() { 
        if (this.$route.query.orderSn) {
            this.listQuery.orderSn = this.$route.query.orderSn;
        }
        this.getList();
        getUserCity().then((res) => {
            this.city = res.data.data;
        });
        this.getAllFras();
    },
    methods: {
        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;
            }
            console.info(this.listQuery)
            list(this.listQuery)
                .then((response) => {
                    this.list = response.data.data.list;
                    this.total = response.data.data.total;
                    this.listLoading = false;
                })
                .catch(() => {
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
        },
        getAllFras() {
            getAllFras().then(res => {
                this.fras = res.data.data
            })
        },
        handleTranBook(row) {//调单给加盟商
            if (row.servantId) {
                this.$notify.error({
                    title: "失败",
                    message: "请先取消订单 才可以调单",
                });
                return;
            }
            this.tranBookFormVisible = true;
            this.tranBookForm = {
                fraId: row.fraId,
                bookDetailId: row.id
            }

        },
        saveTranBook() {
            if (this.tranBookForm.fraId == null || this.tranBookForm.fraId == '') {
                this.$notify.error({
                    title: "失败",
                    message: "请选择加盟商",
                });
                return;
            }
            this.$confirm("确定将此服务单调配给此加盟商？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                tranBookToFra(this.tranBookForm).then(res => {
                    this.tranBookFormVisible = false;
                    this.$message.success("调单成功");
                    this.getList();
                }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })

            });

        },
        formatTime(time) {
            if (time == null || time === "") {
                return "";
            }
            const date = new Date(time);
            return formatDate(date, "yyyy-MM-dd hh:mm:ss");
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        handleCancel(row) {
            this.cancelOrderItem = row;
            this.cancelAppointVisible = true;
        },
        cancelBook() {
            this.$refs["cancelAppointForm"].validate((valid) => {
                if (valid) {
                    let params = {
                        detailId: this.cancelOrderItem.id,
                        changeReason: this.cancelAppointForm.changeReason,
                    };
                    cancelBook(params)
                        .then((response) => {
                            this.$message.success("取消成功");
                            this.cancelAppointVisible = false;
                            this.cancelOrderItem.status = 5;
                        })
                        .catch((response) => {
                            this.$notify.error({
                                title: "失败",
                                message: response.data.errmsg,
                            });
                        });
                }
            });
        },
        handleReassign(row, index) {
            let data={ id: row.id,orderId:row.orderId, fraId: row.fraId};
            this.$refs.serviceBookRef.init(data);
            
        },
        reassignSuccess(data) {
            this.getList();
        },
        handleFinish(row) {
            this.$confirm("确定要手动核销完成此服务单吗！", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                orderBookFinish({ id: row.id })
                    .then((response) => {
                        this.$message.success("完结成功");
                        row.status = 4;
                    })
                    .catch((response) => {
                        this.$notify.error({
                            title: "失败",
                            message: response.data.errmsg,
                        });
                    });
            });

        },
        getServantList(id) {
            getAssignmentPerson(id).then((res) => {
                this.servantList = res.data.data;
            });
        },
        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 = "";
        },
        confirmReassign() {
            this.$refs["reassignForm"].validate((valid) => {
                if (valid) {
                    let params = {
                        id: this.reassignForm.id,
                        bookDate: this.reassignForm.bookDate,
                        bookStartTime: this.reassignForm.bookTime.split("-")[0],
                        bookEndTime: this.reassignForm.bookTime.split("-")[1],
                        servantId: this.reassignForm.servantId,
                    };
                    orderBookReassign(params)
                        .then((response) => {
                            this.$message.success("改派成功");
                            console.log(response);
                            this.reassignDialogVisible = false;
                            this.orderBookDetail(this.reassignForm.orderId);
                        })
                        .catch((response) => {
                            this.$notify.error({
                                title: "失败",
                                message: response.data.errmsg,
                            });
                        });
                }
            });
        },
        wholeModify() {
            this.$confirm("若工单预约时间为空需要单独修改预约！", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                onceReassign(this.assignOrderId).then((res) => {
                    console.log(res);
                    if (res.data.errno == 0) {
                        this.$notify.success({
                            title: "成功",
                            message: "改派成功",
                        });
                        this.orderBookDetail(this.assignOrderId);
                    } else {
                        this.$message.error(res.data.errmsg);
                    }

                }).catch(err => {
                    console.log(err);
                    this.$message.error(err.data.errmsg);
                });
            });
        },
        getTagType(row) {
            if (row.status == 0) return "";
            if (row.status == 1) return "info";
            if (row.status == 2 || row.status == 3) return "warning";
            if (row.status == 4 || row.status == 5) return "success";
            return "danger";
        },
        tableRowClassName({ row, index }) {
            return "";
            if (row.status == 5 || row.status == 6) {
                return "";
            }
            else if (row.status == 1) {
                return "waiting";
            }
            else if (row.status == 2) {
                return "processing";
            }
            else if (row.status == 3 || row.status == 4) {
                return "completed";
            }
            else if (row.status == 0)
                return "nobook";
            return "accept";//待接单
        },
        handleLog(row) {
            this.logDiaVisible = true;
            getOpLog({ serviceId: row.id })
                .then((res) => {
                    this.logList = res.data.data.list
                })
                .catch((response) => {
                    this.$notify.error({
                        title: '失败',
                        message: response.data.errmsg
                    })
                })
        },

    },
};
</script>
  
<style scoped>
.el-table .accept {
    background-color: #cc5858;
}

.el-table .completed {
    background-color: #999;
}

.el-table .waiting {
    background-color: #73bfec;
}

.el-table .nobook {
    background-color: #bebbbb;
}

.el-table .cancel {
    background-color: #bebbbb;
}

.el-table .processing {
    background-color: rgb(169 201 234);
}

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

.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;
}

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

.warn-color {
    color: #f56c6c;
}


.fixed-width .el-button--mini {
    width: auto;
    min-width: 55px;
}  
</style>
  