<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.orderId" 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  filterable style="width: 160px" 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 style="width: 160px" 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="至" start-placeholder="下单开始日期" end-placeholder="下单下单结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd hh:mm:ss" />

      <el-button v-permission="['GET /admin/orderbook/cyclelist']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="客户手机" prop="customerTel" fixed="left" width="135" />
      <el-table-column align="center" label="服务订单编号" width="135" prop="orderId" />
      <el-table-column align="center" label="支付订单编号" width="145" prop="orderSn" />
      <el-table-column align="center" label="服务单状态" width="125">
        <template slot-scope="scope">
          {{ statusMap[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品名称" prop="goodsName" />

      <!-- <el-table-column align="center" label="城市" width="135" prop="city" /> -->
      <el-table-column align="center" width="135" label="城市" prop="address">
        <template slot-scope="scope">
          {{cityFilter(scope.row.address)}}
        </template>
      </el-table-column>

     <el-table-column align="center" label="总次数" width="80" prop="serviceTimes" />
      <el-table-column align="center" label="已服务次数" width="100" prop="servicedTimes" />
      <el-table-column align="center" label="已预约次数"  width="100" prop="bookedTimes" />
      <el-table-column align="center" label="未服务次数">
        <template slot-scope="scope">
          {{ scope.row.serviceTimes - scope.row.servicedTimes }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="下单时间" min-width="90" prop="createTime" />
      <!-- <el-table-column align="center" label="收货人联系方式" prop="mobile" />
      <el-table-column align="center" label="预约时间" min-width="150" prop="orderDate" />
      <el-table-column align="center" label="城市" prop="address" >
        <template slot-scope="scope">
          {{cityFilter(scope.row.address)}}
        </template>
      </el-table-column>  -->

      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" width="140">
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/orderbook/detail']" type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="服务订单详情" width="1000px">
      <p>
        <el-button v-permission="['POST /admin/orderbookdetail/changeWorker']" type="primary" size="mini" @click="wholeAppoint" v-if="orderItem.status == 0">一键预约</el-button>
      </p>
      <div style="padding:20px 40px; width:800px">
        <el-calendar>
          <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
          <template slot="dateCell" slot-scope="{date, data}">
            <p :class="appointmentList.indexOf(data.day)>-1 ? 'is-appointment' : ''">
              {{ data.day.split('-').slice(1).join('-') }}
              <!-- {{ data.day }} -->
              {{ appointmentList.indexOf(data.day)>-1 ? '已预约' : ''}}

              <el-button v-permission="['POST /admin/orderbookdetail/changeWorker']" type="primary" size="mini" @click="handleCalendarReassign(data.day)" v-if="appointmentList.indexOf(data.day)>-1">修改预约</el-button>
            </p>
          </template>
        </el-calendar>
      </div>
      <!-- <el-card shadow="never" style="margin-top: 15px"> -->

      <el-table :data="orderDetail" style="margin-top: 20px" border fit>
        <el-table-column align="center" label="id" prop="id" />
        <el-table-column align="center" label="服务订单编号" prop="orderId" />
        <!-- <el-table-column align="center" label="预约日期" prop="bookDate" /> -->
        <el-table-column label="预约时间" width="180" prop="bookTime" align="center">
          <!-- <template slot-scope="scope">
            {{ scope.row.bookStartTime==null?"":scope.row.bookStartTime 
            + "-" + 
            scope.row.bookEndTime==null?"":scope.row.bookEndTime }}
          </template> -->
        </el-table-column>

        <el-table-column align="center" label="服务者姓名" prop="servantName" />
        <el-table-column align="center" label="服务者手机号" prop="servantMobile" />
                <el-table-column align="center" label="加盟商" prop="fraName" />
        <el-table-column align="center" label="服务单状态" width="135">
          <template slot-scope="scope">
            {{ statusMap[scope.row.status] }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button v-permission="['POST /admin/orderbookdetail/changeWorker']" type="primary" size="mini" @click="handleReassign(scope.row)" v-if="scope.row.status == 1||scope.row.status == 0||scope.row.status == 7">修改预约</el-button>
            <el-button v-permission="['GET /admin/orderbook/cancelBook']" type="danger" plain size="mini" @click="handleCancel(scope.row)" v-if="scope.row.status == 1||scope.row.status == 7">取消预约</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- </el-card> -->
    </el-dialog>

    <!-- 改派对话框 -->
    <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="wholeAppointVisible" title="一键预约" center>
      <el-form ref="wholeAppointForm" :model="wholeAppointForm" status-icon label-position="left" label-width="140px" style="width: 800px; margin-left:50px;" :rules="appointRules">
        <el-form-item label="服务频次" prop="type">
          <el-radio-group v-model="wholeAppointForm.type" @change="typeChange">
            <el-radio :label="1">一周1次</el-radio>
            <el-radio :label="2">一周2次</el-radio>
            <el-radio :label="3">二周1次</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="时间段" prop="bookTime">
          <el-cascader v-if="cascaderShow" :key="refreshItem" ref="weektimeList" v-model="wholeAppointForm.bookTime" :options="weektimeList" :props="{ multiple: wholeAppointForm.type==2?true:false }" @change="handleChange" clearable></el-cascader>
          <!-- <el-select v-model="wholeAppointForm.bookTime" placeholder="请选择">
            <el-option
              v-for="item in timeList"
              :key="item.id"
              :label="item.time"
              :value="item.time"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item label="首次服务时间" prop="startDate">
          <!-- <el-date-picker
            v-model="wholeAppointForm.startDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker> -->
          <el-select v-model="wholeAppointForm.startDate" placeholder="请选择首次服务时间">
            <el-option v-for="item in firstTimeList" :key="item.date" :label="item.date+' '+item.week" :value="item.date" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="wholeAppointVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmWholeAppoint">确定</el-button>
      </div>
    </el-dialog>

    <!-- 取消预约对话框 -->
    <el-dialog :visible.sync="cancelAppointVisible" title="取消预约">
      <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> 

    
    <serviceBookRef ref="serviceBookRef" />
  </div>
</template>

<script>
import axios from "axios";
import {
  cyclelist,
  orderBookDetail,
  orderBookReassign,
  cancelBook,
  getAssignmentPerson,
  orderBook,
  getAssignmentPersonTime,
} from "@/api/order";
import { allChannel } from "@/api/channel";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import checkPermission from "@/utils/permission"; // 权限判断函数
import { getToken } from "@/utils/auth";
import { getUserCity } from "@/api/city";
import { bookStatusMap,cancelReasonList,
  changeReasonMap } from "@/api/enumUtils";  
import serviceBookRef from "@/views/order/components/serviceBookRef";
let vm;

export default {
  name: "Order",
  components: { Pagination,serviceBookRef },
  filters: {
    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;
      }
    },
  },
  data() {
    return {
      cancelAppointVisible: false,
      cancelOrderItem: "",
      cancelAppointrules: {
        changeReason: [
          { required: true, message: "请选择取消原因", trigger: "change" },
        ],
      },
      cancelAppointForm: {
        changeReason: "",
      },
      cancelReasonList: cancelReasonList,
      wholeAppointVisible: false,
      cascaderShow: true,
      wholeAppointForm: {
        type: 1,
        startDate: "",
        bookTime: [],
      },
      //  props: { multiple: false },
      refreshItem: 0,
      firstTimeList: [],
      weektimeList: [
        { value: 1, label: "周一" },
        { value: 2, label: "周二" },
        { value: 3, label: "周三" },
        { value: 4, label: "周四" },
        { value: 5, label: "周五" },
        { value: 6, label: "周六" },
        { value: 0, label: "周日" },
      ],
      orderItem: {},
      appointmentList: [],
      timeList: [],
      timeListAppoint: [],
      servantList: [],
      actualPrice: "", //退款金额
      refundAmount: "",
      list: [],
      total: 0,
      listLoading: true,
      city: [],
      listQuery: {
        page: 1,
        limit: 20,
        mobile: "",
        timeArray: [],
        orderId: "",
        orderStatusArray: [],
        cityId: "",
        sort: "create_time",
        order: "desc",
      },
      rules: {
        bookDate: [
          { required: true, message: "请选择改派日期", trigger: "blur" },
        ],
        bookTime: [
          { required: true, message: "请选择改派时间", trigger: "blur" },
        ],
        servantId: [
          { required: true, message: "请选择服务者", trigger: "blur" },
        ],
      },
      appointRules: {
        type: [
          { required: true, message: "请选择服务频次", trigger: "change" },
        ],
        startDate: [
          { required: true, message: "请选择首次服务时间", trigger: "blur" },
        ],
        bookTime: [
          { 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]);
            },
          },
        ],
      },
      channels: [],
      statusMap: bookStatusMap,
      orderDialogVisible: false,
      reassignDialogVisible: false,
      orderDetail: [],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined,
      },
      importForm: {
        channelId: 1,
        file: undefined,
        filename: undefined,
      },

      reassignForm: {
        id: "",
        bookDate: "",
        bookTime: "",
        servantId: "",
        orderId: "",
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined,
      },
      refundDialogVisible: false,
      importLoading: false,
      headers: { "Content-Type": "multipart/form-data" },
    };
  },
  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {
    this.getList();
    getUserCity().then((res) => {
      this.city = res.data.data;
    });
  },
  methods: {
    checkPermission,
    getTimeList(type) {
      let timeList = [];
      switch (type) {
        case 1:
          timeList = [
            {
              id: 1,
              time: "08:30-09:30",
              value: "08:30-09:30",
            },
            {
              id: 2,
              time: "10:45-11:45",
              value: "10:45-11:45",
            },
            {
              id: 3,
              time: "13:00-14:00",
              value: "13:00-14:00",
            },
            {
              id: 4,
              time: "14:45-15:45",
              value: "14:45-15:45",
            },
            {
              id: 5,
              time: "17:30-18:30",
              value: "17:30-18:30",
            },
            {
              id: 6,
              time: "20:00-21:00",
              value: "20:00-21:00",
            },
          ];
          break;
        case 2:
          timeList = [
            {
              id: 1,
              time: "08:00-10:00",
              value: "08:00-10:00",
            },
            {
              id: 2,
              time: "13:00-15:00",
              value: "13:00-15:00",
            },
            {
              id: 3,
              time: "17:30-19:30",
              value: "17:30-19:30",
            },
          ];
          break;
        case 3:
          timeList = [
            {
              id: 1,
              time: "08:00-11:00",
              value: "08:00-11:00",
            },
            {
              id: 2,
              time: "13:00-16:00",
              value: "13:00-16:00",
            },
            {
              id: 3,
              time: "17:30-20:30",
              value: "17:30-20:30",
            },
          ];
          break;
        case 4:
          timeList = [
            {
              id: 1,
              time: "08:00-12:00",
              value: "08:00-12:00",
            },
            {
              id: 2,
              time: "13:00-17:00",
              value: "13:00-17:00",
            },
          ];
          break;
        case 6:
          timeList = [
            {
              id: 1,
              time: "08:00-14:00",
              value: "08:00-14:00",
            },
            {
              id: 2,
              time: "13:00-19:00",
              value: "13:00-19:00",
            },
          ];
          break;
        default:
          timeList = [];
      }
      return timeList;
    },
    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;
      }

      cyclelist(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;
        });
    },
    cityFilter(address) {
      if (address) {
        if (address.indexOf("上海市") >= 0) return "上海市";
        if (address.indexOf("北京市") >= 0) return "北京市";
        if (address.indexOf("南京") >= 0) return "南京市";
        if (address.indexOf("深圳") >= 0) return "深圳市";
        if (address.indexOf("苏州") >= 0) return "苏州市";
        if (address.indexOf("无锡") >= 0) return "无锡市";
         if (address.indexOf("杭州") >= 0) return "杭州市";
        if (address.indexOf("宜昌") >= 0) return "宜昌市";
        if (address.indexOf("青岛") >= 0) return "青岛市";
        if (address.indexOf("成都") >= 0) return "成都市";
        if (address.indexOf("重庆") >= 0) return "重庆市";
        if (address.indexOf("广州") >= 0) return "广州市";
      }
      return "";
    },
    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();
    },
    formatStepStatus(value, time) {
      if (value === 201) {
        // 待发货
        return 2;
      } else if (value === 301) {
        // 已发货
        return 3;
      } else if (value === 401 || value === 402) {
        // 已完成
        if (time != null && time != "undefined") {
          return 5;
        } else {
          return 4;
        }
      } else {
        // 待付款、已关闭、无限订单
        return 1;
      }
    },
    handleDetail(row) {
      // orderBookDetail(row.orderId).then(response => {
      //   this.orderDetail = response.data.data
      // });
      this.orderBookDetail(row.orderId);
      this.orderDialogVisible = true;
      this.orderItem = row;
    },
    orderBookDetail(orderId) {
      orderBookDetail(orderId).then((response) => {
        this.orderDetail = response.data.data;
        let appointmentList = [];
        response.data.data.forEach((item) => {
          if (item.status == 1) {
            appointmentList.push(item.bookTime.substr(0, 10));
          }
        });
        this.appointmentList = appointmentList;
        console.log(this.appointmentList);
      });
    },
    handleCancel(row) {
      // this.$confirm("确定要取消吗！", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => {
      //   this.cancelBook(row.id, row.orderId);
      // });

      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.orderBookDetail(this.cancelOrderItem.orderId);
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleCalendarReassign(day) {
      let row = this.orderDetail.filter((item) => {
        if (item.status == 1) {
          return item.bookTime.substr(0, 10) == day;
        }
      });
      console.log(row);
      this.handleReassign(row[0]);
    },
    handleReassign(row) { 
      let data={ id: row.id,orderId:row.orderId, fraId: row.fraId};
      this.$refs.serviceBookRef.init(data);
    },
    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.time.split("-")[0],
            endTime: item.time.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,
              });
            });
        }
      });
    },

    confirmShip() {
      this.$refs["shipForm"].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm)
            .then((response) => {
              this.shipDialogVisible = false;
              this.$notify.success({
                title: "成功",
                message: "确认发货成功",
              });
              this.getList();
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleDeleteConfirm(row) {
      this.$confirm("订单删除后无法恢复，确定继续删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.handleDelete(row);
      });
    },
    handleDelete(row) {
      deleteOrder({ orderId: row.id })
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "订单删除成功",
          });
          this.getList();
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id;
      if (row.refundAmount) {
        this.refundForm.refundMoney = (
          row.actualPrice - row.refundAmount
        ).toFixed(2);
        this.refundAmount = row.refundAmount;
      } else {
        this.refundForm.refundMoney = row.actualPrice;
      }

      this.actualPrice = row.actualPrice;

      this.refundDialogVisible = true;
      this.$nextTick(() => {
        this.$refs["refundForm"].clearValidate();
      });
    },
    confirmRefund() {
      this.$refs["refundForm"].validate((valid) => {
        if (valid) {
          let balance = (this.actualPrice - this.refundAmount).toFixed(2);
          console.log(balance);
          if (Number(this.refundForm.refundMoney) == 0) {
            this.$message.warning("申请退款金额不能为零!");
          } else if (Number(this.refundForm.refundMoney) > balance) {
            this.$message.warning("申请退款金额不能大于未退款金额!");
          } else {
            refundOrder(this.refundForm)
              .then((response) => {
                this.refundDialogVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "确认退款成功",
                });
                this.getList();
              })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg,
                });
              });
          }
        }
      });
    },
    handleImport() {
      this.importLoading = true;
      this.importForm.file = undefined;
    },
    beforeUpload(file) {
      // this.files = file;
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!extension && !extension2) {
        this.$message.warning("上传模板只能是 xls、xlsx格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.warning("上传模板大小不能超过 5MB!");
        return;
      }
      this.importForm.filename = file.name;
      this.importForm.file = file;
      return false; // 返回false不会自动上传
    },
    confirmImport() {
      // 确定上传
      console.info(this.importForm);
      var formData = new FormData();
      formData.append("file", this.importForm.file);
      formData.append("channelId", this.importForm.channelId);

      var config = {
        headers: { "Content-Type": "multipart/form-data" },
      };

      importOrder(formData, config).then((res) => {});
    },
    printOrder() {
      if (this.$print != undefined) {
        this.$print(this.$refs.print);
        this.orderDialogVisible = false;
      }
    },

    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "客户手机",
          "订单编号",
          "下单时间",
          "收货人联系方式",
          "上门地址",
          "城市",
          "上级合伙人",
          "订单状态",
          "支付金额",
          "支付时间",
        ];
        const filterVal = [
          "customer.tel",
          "orderSn",
          "createTime",
          "mobile",
          "address",
          "city",
          "rCustomer.customerName",
          "orderStatus",
          "actualPrice",
          "payTime",
        ];
        var lists = [];
        if (this.list && this.list.length > 0) {
          for (let i = 0; i < this.list.length; i++) {
            var order = this.list[i];
            order.city = this.cityFilter(order.address);
            order.orderStatus = statusMap[order.orderStatus];
            lists.push(order);
          }
          console.info(lists);
        }
        excel.export_json_to_excel2(tHeader, lists, filterVal, "订单");
        this.downloadLoading = false;
      });
    },
    handleChange(value) {
      console.log(value);
      if (value.length >= 1) {
        let futureDateList = this.getDateList(
          new Date(new Date().getTime() + 60 * 60 * 1000 * 24),
          1
        );
        let selectedWeekList = [];
        // let minIndex=Math.min.apply(null, selectedWeekList);
        // let beginDate=futureDateList.filter(item=>{return (new Date(item.date)).getDay()==(this.weektimeList[minIndex]).value});
        let minIndex = this.isDeepArray(value) ? value[0][0] : value[0];
        console.log(minIndex);
        let beginDate = futureDateList.filter((item) => {
          return new Date(item.date).getDay() == minIndex;
        });
        console.log(beginDate);
        let inter = this.wholeAppointForm.type == 2 ? 14 : 7;
        let firstTimeList = this.getDateList(
          new Date(new Date(beginDate[0].date).getTime()),
          inter
        );
        this.firstTimeList = firstTimeList;
        console.log(firstTimeList);
      }
    },
    isDeepArray(a) {
      let str1 = true;
      let str2 = false;
      for (let i of a) {
        if (Array.isArray(i)) return str1;
      }
      return str2;
    },
    getDateList(date, interval) {
      let dateList = [];
      for (let i = 0; i < 7; i++) {
        let datestamp = new Date(
          date.getTime() + i * 60 * 60 * 1000 * 24 * interval
        );
        let dateItem = {
          week: this.formatweek(datestamp),
          date: this.formetdate(datestamp),
          id: new Date(datestamp).getDay(),
        };
        dateList.push(dateItem);
      }
      return dateList;
    },
    formetdate(date) {
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return [year, month, day].map(this.formatNumber).join("-");
    },
    formatNumber(n) {
      n = n.toString();
      return n[1] ? n : "0" + n;
    },
    formatweek(date) {
      let week = date.getDay();
      let weekArr = "";
      switch (week) {
        case 1:
          weekArr = "周一";
          break;
        case 2:
          weekArr = "周二";
          break;
        case 3:
          weekArr = "周三";
          break;
        case 4:
          weekArr = "周四";
          break;
        case 5:
          weekArr = "周五";
          break;
        case 6:
          weekArr = "周六";
          break;
        case 0:
          weekArr = "周日";
          break;
      }
      return weekArr;
    },
    wholeAppoint() {
      this.wholeAppointVisible = true;
      this.wholeAppointForm = {
        type: 1,
        bookTime: [],
        startDate: "",
      };
      let timeList = this.getTimeList(this.orderItem.serviceDuration);
      let weektimeList = this.weektimeList;
      weektimeList.forEach((item) => {
        item.children = timeList;
      });
      var str = JSON.stringify(weektimeList).replace(/time/g, "label");

      this.weektimeList = JSON.parse(str);
    },
    typeChange(value) {
      //   this.$refs.weektimeList.$refs.panel.clearCheckedNodes(); //清空选中的节点
      //  this.$refs.weektimeList.$refs.panel.activePath = []; //设置为空可以让节点不高亮显示
      //  this.$set(this.wholeAppointForm,'bookTime',[]);
      this.refreshItem++;
      this.wholeAppointForm.bookTime = [];
      console.log(this.wholeAppointForm.bookTime);
    },
    confirmWholeAppoint() {
      this.$refs["wholeAppointForm"].validate((valid) => {
        if (valid) {
          let isaa = !this.isDeepArray(this.wholeAppointForm.bookTime);
          if (
            this.wholeAppointForm.type == 2 &&
            this.wholeAppointForm.bookTime.length != 2
          ) {
            this.$message({
              type: "warning",
              message: "服务频次时间为一周两次",
            });
            return;
          } else {
            let weeks = [];
            if (this.wholeAppointForm.type == 2) {
              this.wholeAppointForm.bookTime.forEach((item) => {
                let obj = {
                  dayOfWeek: item[0],
                  startTime: item[1].split("-")[0],
                  endTime: item[1].split("-")[1],
                };
                weeks.push(obj);
              });
            } else {
              let obj = {
                dayOfWeek: this.wholeAppointForm.bookTime[0],
                startTime: this.wholeAppointForm.bookTime[1].split("-")[0],
                endTime: this.wholeAppointForm.bookTime[1].split("-")[1],
              };
              weeks.push(obj);
            }
            let params = {
              bookId: this.orderItem.id,
              startDate: this.wholeAppointForm.startDate,
              type: this.wholeAppointForm.type,
              weeks: weeks,
            };
            orderBook(params)
              .then((response) => {
                if (response.data.errno == 0) {
                  // this.$message.success("预约成功,其中"+response.data.data+'次暂未预约上');
                  this.$message.success("预约成功");
                  this.orderItem.status = 1;
                  this.wholeAppointVisible = false;
                  this.orderBookDetail(this.orderItem.orderId);
                }
              })
              .catch((response) => {
                this.$notify.error({
                  title: "预约失败",
                  message: response.data.errmsg,
                });
              });
          }
        }
      });
    },
  },
};
</script>

<style>
.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;
}
.is-appointment {
  color: #1989fa;
}
.el-cascader--medium {
  width: 360px;
}
</style>
