<template>
  <div class="app-container">
    <div class="block">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-row>
            <el-col :span="2" style="margin-top: 0.8rem">
              <span style="font-size: 0.7rem">订单状态：</span>
            </el-col>
            <el-col :span="30">
              <el-button :type="query.button.css.status.all" size="small"
                @click.native="queryByState('全部')">全部</el-button>
              <el-button size="mini" :type="query.button.css.status.unPay" @click.native="queryByState('未支付')">待支付
                &nbsp;<el-tag type="success" size="mini" /></el-button>
              <el-button size="mini" :type="query.button.css.status.sended"
                @click.native="queryByState('服务中')">服务中&nbsp;<el-tag type="info" size="mini" /></el-button>
              <el-button size="mini" :type="query.button.css.status.finished"
                @click.native="queryByState('已完成')">已完成&nbsp;<el-tag type="info" size="mini" /></el-button>
              <el-button size="mini" :type="query.button.css.status.cancel"
                @click.native="queryByState('已取消')">已取消&nbsp;<el-tag type="info" size="mini" /></el-button>
            </el-col>
          </el-row>
          <el-row>
            <br>
            <el-col :span="2" style="margin-top: 0.1rem">
              <span style="font-size: 0.7rem">下单日期：</span>
            </el-col>
            <el-col :span="30">
              <el-button size="small" :type="query.button.css.date.all" @click.native="queryByDate('all')">全部</el-button>
              <el-button size="small" :type="query.button.css.date.today"
                @click.native="queryByDate('today')">今天</el-button>
              <el-button size="small" :type="query.button.css.date.seven"
                @click.native="queryByDate('seven')">最近7天</el-button>
              <el-button size="small" :type="query.button.css.date.month"
                @click.native="queryByDate('thirty')">最近三十天</el-button>
              <el-button size="small" :type="query.button.css.date.custom"
                @click.native="DateChonsenDialogVisible = true">自定义</el-button>
            </el-col>
          </el-row>
          <br>
        </el-col>

        <el-col :span="4">
          <el-input v-model.lazy="listQuery.orderSn" size="mini" placeholder="输入订单号查询" />
        </el-col>
        <el-col :span="6">
          <el-button type="success" plain size="mini" icon="el-icon-search" @click.native="search()">搜索</el-button>
          <el-button type="primary" plain size="mini" icon="el-icon-refresh" @click.native="reset">重置</el-button>
        </el-col>
        <el-col><br></el-col>
      </el-row>
    </div>

    <el-table :data="filterTableData" style="width: 100%">
      <el-table-column type="expand">
        <!-- 这里是展开的详细信息 -->
        <template #default="props">
          <el-row>
            <el-col :span="4">
              <h4>订单信息</h4>

              <p m="t-0 b-2">订单号 : {{ props.row.id }}</p>
              <p m="t-0 b-2">服务日期 : {{ props.row.createTime }}</p>
              <p m="t-0 b-2">订单状态 : {{ props.row.status }}</p>
              <p m="t-0 b-2">总金额 : {{ props.row.totalPrice }}</p>
            </el-col>

            <el-col :span="6">
              <br>
              <br>
              <p m="t-0 b-2">家政分类 : {{ props.row.categoryName }}</p>
              <p m="t-0 b-2">服务时间 : {{ props.row.serverTime }}</p>
              <p m="t-0 b-2">待遇 : {{ props.row.treatment }}</p>
            </el-col>

            <el-col :span="6">
              <h4>雇主信息</h4>
              <p m="t-0 b-2">雇主账户名 : {{ props.row.userName }}</p>
              <p m="t-0 b-2">雇主手机号 : {{ props.row.userPhone }}</p>
              <p m="t-0 b-2">雇主地址 : {{ props.row.area }}</p>
            </el-col>

            <el-col :span="6">
              <h4>家政人员信息</h4>
              <p m="t-0 b-2">家政人员账户名 : {{ props.row.serverName }}</p>
              <p m="t-0 b-2">家政人员手机号 : {{ props.row.serverPhone }}</p>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column sortable label="订单号" prop="id" />
      <el-table-column sortable label="创建日期" prop="createTime" />
      <el-table-column sortable label="雇主账户名" prop="userName" />
      <el-table-column sortable label="家政账户名" prop="serverName" />
      <el-table-column sortable label="家政分类" prop="categoryName" />
      <el-table-column sortable label="订单状态" prop="status" />
      <el-table-column sortable label="总金额" prop="totalPrice" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-dropdown size="small" split-button type="primary">
            操作

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.statusName !== '已取消'"
                @click.native="handleEdit(scope.row.id)">修改订单</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === '服务中'">立即退款</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === '服务中'">标记完成</el-dropdown-item>
              <el-dropdown-item @click.native="viewLog(scope.row.id)">操作日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!--操作日志-->
    <el-dialog title="订单日志" :visible.sync="logVisible" width="40%">
      <el-table :data="logs" stripe border style="width: 100%">
        <el-table-column sortable prop="context" label="操作内容" />
      </el-table>
    </el-dialog>

    <!--时间选择器-->
    <el-dialog title="自定义时间范围" :visible.sync="DateChonsenDialogVisible" width="80%" center>
      <el-col :span="9">
        <el-date-picker v-model="orderDate" value-format="yyyy-MM-dd HH:mm:ss" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="截至日期" :picker-options="expireTimeOption" @change="selectRangeTime"
          width="80%">
        </el-date-picker>
      </el-col>

      <span slot="footer" class="dialog-footer">
        <el-button @click="DateChonsenDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click.native="queryByDate('custom')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改信息" :visible.sync="centerDialogVisible" width="87%" center>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="雇主手机号">
              <el-input v-model="form.bossPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="雇主地址">
              <el-input v-model="form.bossAddress" />
            </el-form-item>
          </el-col>
        </el-row> -->
          <!-- <el-row>
          <el-col :span="8">
            <el-form-item label="家政人员手机号">
              <el-input v-model="form.serverPhone" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="总金额">
              <el-input v-model="form.totalPrice" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="服务时间">
              <el-date-picker v-model="form.serverTime" type="datetime" placeholder="选择日期时间" align="right"
                format="yyyy-MM-dd HH:mm:ss" :picker-options="expireTimeOption" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmForm()">确 定</el-button>
      </span>
    </el-dialog>

    <nav v-if="total * 1" style="text-align: -webkit-center">
      <el-pagination :total="total" :page-size="listQuery.pageSize" :current-page="listQuery.pageNum"
        layout="prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </nav>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { GetOrdersList, GetOrderById, getLogById, updateOrder } from '@/api/order'
export default {
  name: 'Order',
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      orderDate: [],
      // 禁用时间选择器开始日期前的时间
      expireTimeOption: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      centerDialogVisible: false,
      DateChonsenDialogVisible: false,
      filterTableData: [],
      // 编辑表单
      labelPosition: 'right',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      },
      // 作为修改订单载体
      form: {
        id: '',
        bossPhone: '',
        bossAddress: '',
        serverPhone: '',
        totalPrice: '',
        serverTime: '',
        serverId: '',
        userId: '',
        createTime: ''
      },
      rules: {

      },
      logs: [
        {
          id: '',
          orderItem: '',
          logTime: '',
          orderId: '',
          context: '',
        }
      ],
      // 请求列表，作为参数提交至后端
      listQuery: {
        pageNum: 1,
        pageSize: 4,
        orderSn: '',
        list: [],
        status: '全部',
        startDate: undefined,
        endDate: undefined
      },
      logQuery: {
        orderId: undefined,
        pageNum: 0,
        pageSize: 10,
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {},
      logVisible: false,
      expressList: [],
      timeFormat: {
        year: '',
        month: '',
        day: '',
        hour: '',
        minute: '',
        second: ''
      },
      query: {
        button: {
          lastStatus: 'all',
          lastDate: 'all',
          css: {
            status: {
              all: 'primary',
              unPay: 'default',
              serving: 'default',
              finished: 'default',
              cancel: 'default'
            },
            date: {
              all: 'primary',
              today: 'default',
              seven: 'default',
              thirty: 'default',
              custom: 'default'
            }
          },
          tag: {
            unPay: 0,
            serving: 0,
            finished: 0,
            cancel: 0
          }
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 根据状态获取订单信息
    fetchData() {
      this.listLoading = true
      const data = {
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        status: this.listQuery.status,
        createTime: this.listQuery.startDate,
        endTime: this.listQuery.endDate
      }
      GetOrdersList(data).then(response => {
        if (response.data.code === 200) {
          this.listLoading = false
          this.total = parseInt(response.data.data.total)
          this.filterTableData = response.data.data.rows
        }
      })
    },
    search() {
      this.listQuery.page = 1
      GetOrderById(this.listQuery.orderSn).then(response => {
        if (response.data.code === 200) {
          this.filterTableData = []
          this.listLoading = false
          this.filterTableData[0] = response.data.data
          this.total = 1
          if (this.filterTableData.length !== 0) {
            Message({
              message: response.data.msg,
              type: 'success',
              duration: 5 * 1000
            })
          } else {
            Message({
              message: '找不到该订单',
              type: 'warning',
              duration: 5 * 1000
            })
          }
        }
      })
    },
    reset() {
      this.listQuery.orderSn = ''
      this.listQuery.page = 1
      this.listQuery.status = '全部'
      this.fetchData()
    },
    // 根据订单状态分类
    queryByState(status) {
      const lastStatus = this.query.button.lastStatus
      // CSS样式
      this.query.button.css.status[lastStatus] = 'default'
      this.query.button.css.status[status] = 'primary'
      this.query.button.lastStatus = status
      if (status !== 'all') {
        this.listQuery.status = status
      } else {
        this.listQuery.status = ''
      }
      this.fetchData()
    },
    // 根据订单时间分类
    queryByDate(date) {
      const lastDate = this.query.button.lastDate
      this.query.button.css.date[lastDate] = 'default'
      this.query.button.css.date[date] = 'primary'
      this.query.button.lastDate = date
      if (date !== 'all' && date !== 'custom') {
        // 限制时间
        let currentTime = new Date()
        currentTime.setHours(0)
        currentTime.setSeconds(0)
        currentTime.setMinutes(0)
        if (date === 'today') {
          this.listQuery.startDate = this.transferTimeFormat(currentTime)
          currentTime.setHours(23)
          currentTime.setMinutes(59)
          currentTime.setSeconds(59)
          this.listQuery.endDate = this.transferTimeFormat(currentTime)
        } else if (date === 'seven') {
          this.listQuery.startDate = this.transferTimeFormat(currentTime)
          currentTime.setDate(currentTime.getDate() + 10)
          this.listQuery.endDate = this.transferTimeFormat(currentTime)
        }
        else if (date === 'thirty') {
          this.listQuery.startDate = this.transferTimeFormat(currentTime)
          currentTime.setDate(currentTime.getDate() + 30)
          this.listQuery.endDate = this.transferTimeFormat(currentTime)
        }
      } else {
        this.listQuery.startDate = ''
        this.listQuery.endDate = ''
      }
      if (date === 'custom') {
        this.listQuery['startDate'] = this.orderDate[0]
        this.listQuery['endDate'] = this.orderDate[1]
        this.DateChonsenDialogVisible = false
      }
      this.fetchData()
    },
    selectRangeTime(e) {
      // 如果时间被清空了，重置限定条件
      if (e === null) {
        this.orderDate[0] = '';
        this.orderDate[1] = '';
        this.expireTimeOption = {
          disabledDate: time => {
            if (this.orderDate[0]) {
              return time.getTime() < Date.now() - 24 * 60 * 60 * 1000 || time > new Date(this.orderDate[0].getTime() + 90 * 24 * 60 * 60 * 1000)
            }
            return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
          },
        }
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    formatPrice(price) {
      return (price / 100).toFixed(2)
    },
    handleEdit(id) {
      GetOrderById(id).then(response => {
        if (response.data.code === 200) {
          const data = response.data.data
          this.form = {
            id: id,
            bossPhone: data.userPhone,
            bossAddress: data.area,
            serverPhone: data.serverPhone,
            totalPrice: data.totalPrice,
            createTime: data.createTime,
            serverTime: data.serverTime,
            serverId: data.serverId,
            userId: data.userId
          }
        }
      })
      this.centerDialogVisible = true
    },
    // 修改订单信息
    // 修改前验证
    validate() {
      const phoneRegx =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
      return phoneRegx.test(this.form.bossPhone)
    },
    // 转换时间格式
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
    },
    confirmForm() {
      const params = {
        id: this.form.id,
        totalPrice: this.form.totalPrice,
        serverTime: this.formatDate(this.form.serverTime.toLocaleString())
      }
      updateOrder(params).then((response) => {
        if (response.data.code === 200) {
          Message({
            message: response.data.msg,
            type: 'success',
            duration: 5 * 1000
          })
        } else {
          Message({
            message: response.data.msg,
            type: 'error',
            duration: 5 * 1000
          })
        }
      })
      this.centerDialogVisible = false
    },
    transferTimeFormat(d) {
      this.timeFormat.year = d.getFullYear();
      this.timeFormat.month = String(d.getMonth() + 1).padStart(2, '0');
      this.timeFormat.day = String(d.getDate()).padStart(2, '0');
      this.timeFormat.hour = String(d.getHours()).padStart(2, '0');
      this.timeFormat.minute = String(d.getMinutes()).padStart(2, '0');
      this.timeFormat.second = String(d.getSeconds()).padStart(2, '0');
      // 传入年-月-日格式的日期
      return `${this.timeFormat.year}-${this.timeFormat.month}-${this.timeFormat.day} ${this.timeFormat.hour}:${this.timeFormat.minute}:${this.timeFormat.second}`
    },
    // 日志
    viewLog(id) {
      this.logVisible = true
      this.logQuery = {
        orderId: id,
        pageNum: 1,
        pageSize: 10
      }
      getLogById(this.logQuery).then(response => {
        if (response.data.code === 200) {
          this.logs = response.data.data.rows
          for (let i = 0; i < this.logs.length; i++) {
            this.logs[i].context = this.logFormat(i)
          }
        }
      })
    },
    // 设置日志格式
    logFormat(index) {
      return `订单编号为${this.logs[index].orderId} 中 ${this.logs[index].orderItem} 于 ${this.logs[index].logTime} 被修改了`
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.fetchData()
    },
  },
}
</script>

<style></style>
