<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="活动列表" prop="eventId">
        <el-select v-model="queryParams.eventId" placeholder="请选择活动列表" clearable size="small">
          <el-option
            v-for="item in eventList"
            :key="item.id"
            :label="item.eventName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="placeNumber">
        <el-select v-model="queryParams.zfbz" placeholder="请选择订单类型" clearable size="small">
          <el-option
            v-for="item in [{label:'预定兑换',id:1},{label:'现场兑换',id:2}]"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="领取地点" prop="placeNumber">
        <el-select v-model="queryParams.placeNumber" placeholder="请选择领取地点" clearable size="small">
          <el-option
            v-for="item in placeList"
            :key="item.placeName"
            :label="item.placeName"
            :value="item.placeName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="daterangePaytime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="订单状态" prop="zfbz">-->
      <!--        <el-select v-model="queryParams.zfbz" placeholder="请选择订单状态" clearable size="small">-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.order_type"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="5" class="mb8">
      <el-col :span="16">
        <el-card class="box-card">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                :loading="exportLoading"
                @click="handleExport"
                v-hasPermi="['canteen:order:export']"
              >导出
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-sold-out"
                size="mini"
                :loading="exportLoading"
                @click="shopOrderSata"
              >订购统计
              </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange"
                    @row-click="openUpdaetText">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="订单编号" align="center" prop="orderNumber" width="110"/>
            <el-table-column label="用户编号" align="center" prop="userNumber"/>
            <el-table-column label="姓名" align="center" prop="userName"/>
            <el-table-column label="手机号" align="center" prop="phone"/>
            <el-table-column label="活动名称" align="center" prop="eventName"/>
            <el-table-column label="订单类型" align="center" prop="bfbz">
              <template slot-scope="scope">
                <span v-if="scope.row.zfbz === 1">
                  预定兑换
                </span>
                <span v-if="scope.row.zfbz === 2">
                  现场兑换
                </span>
              </template>
            </el-table-column>
            <el-table-column label="订单总额" align="center" prop="orderTotal"/>
            <el-table-column label="下单时间" align="center" prop="paytime" width="95">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.paytime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="领取地点" align="center" prop="placeNumber"/>
            <el-table-column label="领取时间" align="center" prop="eventTime"/>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <div class="item">
            <Detail ref="detail" :orderNo="orderNo"></Detail>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :title="shopOrderSataForm.title" :visible.sync="shopOrderSataForm.open" width="800px" append-to-body
               @cancel="cancel">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-select v-model="shopOrderSataForm.eventId" placeholder="请选择活动列表" clearable size="small">
            <el-option
              v-for="item in eventList"
              :key="item.id"
              :label="item.eventName"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleShopOrderQuery">查询</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="shopOrderSataForm.exportLoading"
            @click="doShopOrderStatExport"
          >导出
          </el-button>
        </el-col>
      </el-row>
      <el-table v-loading="shopOrderSataForm.loading" :data="shopOrderSataForm.list">
        <el-table-column label="礼品名称" align="center" prop="giftName" width="200"/>
        <el-table-column label="数量" align="center" prop="amount"/>
        <el-table-column label="单价" align="center" prop="price"/>
        <el-table-column label="总价" align="center" prop="total"/>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>


import {
  listOrder,
  getOrder,
  delOrder,
  updateOrder,
  exportOrder,
  backOrder,
  partbackOrder,
  payMiwp, takeOrder
} from '@/api/canteen/giftOrder'
import { integralExchangeGetPlace } from '@/api/canteen/place'

import { shopOrderStat, shopOrderStatExport } from '@/api/canteen/giftDetail'
import { listEvent } from '@/api/eventConfig/event'
// import OrderProcess from "../../service/orderProcess";
import Detail from './detail'
import result from '@/components/Crontab/result'

export default {
  name: 'Order',
  dicts: ['consumption_period', 'consumption_pattern', 'consumption_period', 'yes_or_no', 'order_type', 'sys_normal_disable'],
  components: {
    // OrderProcess,
    Detail
  },
  data() {
    return {
      tableHeight: document.documentElement.scrollHeight - 345 + 'px',
      shopOrderSataForm: {
        open: false,
        loading: false,
        title: '订购统计信息',
        exportLoading: false,
        eventId: null,
        list: []
      },
      eventList: [],
      placeList: [],
      orderNo: '',
      openText: false,
      text: '',
      userList: [],
      menus: [],
      wrong: false,
      search: '',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 食堂订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        menuNumber: null,
        eventId: null,
        deviceNumber: null,
        deviceName: null,
        nickName: null,
        placeNumber: null,
        // periodId: null,
        // patternId: null,
        // consumerType: null,
        paytime: new Date(),
        zfbz: 1,
        jgid: null,
        orderNo: ''
      },
      jcd: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      dataList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      registerList: [],
      cuisine_ids: [],
      orderProcessList: []
    }
  },
  created() {
    this.getList()
    this.getListEvent()
    this.getIntegralExchangeGetPlace()
    //this.getPlaceList()
    //this.queryNickName()
  },
  methods: {
    getSOStat() {
      this.shopOrderSataForm.loading = true
      shopOrderStat(this.shopOrderSataForm.eventId).then(result => {
        if (result.code === 200) {
          this.shopOrderSataForm.list = result.data
        }
        this.shopOrderSataForm.loading = false
      })
    },
    getIntegralExchangeGetPlace() {
      integralExchangeGetPlace().then(result => {
        this.placeList = result.data
      })
    },
    openUpdaetText(row, column, event) {
      this.orderNo = row.orderNumber
      setTimeout(() => {
        this.$refs.detail.getList()
      }, 200)
      row.isNewsUser = '0'
      updateOrder(row)
    },
    subtext() {
      this.form.cardCode = this.text
      takeOrder(this.form).then(re => {
        if (re.code === 200) {
          this.$modal.msgSuccess('更新成功')
          this.getList()
        }
      })
      this.openText = false
    },
    takeOrder(data, text) {
      if (data.zfbz === 2) {
        this.$modal.msgError('请勿重复接单')
        return
      }
      this.$modal.confirm('确认是否接单？').then(function() {
        data.statusText = text
        return takeOrder(data)
      }).then(() => {
        this.$modal.msgSuccess('接单成功')
        this.getList()
      }).catch(() => {
      })
    },
    jcdChang(val) {
      this.form.placeName = val.placeName
    },
    userChang(val) {
      this.form.nickName = val.nickName
    },
    cuisineSelectionChange(selection) {
      this.cuisine_ids = selection
      let ls = 0
      for (let i = 0; i < selection.length; i++) {
        if (selection[i].cuisinePrice) {
          ls += selection[i].cuisinePrice
        }
      }
      this.form.list = selection
      this.form.orderTotal = ls
    },

    changeMenu(val) {
      console.dir(val)
      if (val !== '') {
        this.menus.map(item => {
          if (item.menuNumber === val) {
            this.tjdc.tjdcTiele = item.menuName
          }
        })
      }
    },
    getListEvent() {
      listEvent().then(result => {
        this.eventList = result.rows
      })
    },
    /** 查询食堂订单列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangePaytime && '' !== this.daterangePaytime) {
        this.queryParams.params['beginPaytime'] = this.daterangePaytime[0]
        this.queryParams.params['endPaytime'] = this.daterangePaytime[1]
      }
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.openText = false
      this.wrong = false
      this.getList()
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNumber: null,
        menuNumber: null,
        orderTotal: 0,
        backTotal: null,
        deviceNumber: null,
        deviceName: null,
        // periodId: null,
        // patternId: null,
        // consumerType: null,
        paytime: null,
        zfbz: null,
        isDelete: null,
        jgid: null
      }
      this.resetForm('form')
    },
    /** 查询订购统计按钮操作 */
    handleShopOrderQuery() {
      this.getSOStat()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePaytime = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改食堂订单'
      })
    },

    handlePartBack(row) {
      this.reset()
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data
        this.wrong = true
        this.title = '退还订单详情'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          payMiwp(this.form).then(response => {
            this.$modal.msgSuccess('成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids
      this.$modal.confirm('是否确认删除食堂订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 作废按钮操作 */
    handleBack(row) {
      const orderIds = row.orderId || this.ids
      this.$modal.confirm('是否作废食堂订单编号为"' + orderIds + '"的数据项？').then(function() {
        return backOrder(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('作废成功')
      }).catch(() => {
      })
    },
    // search: function(event) {
    //   //方法一：直接通过event.data可以获得文本内容
    //   if (event.data != null) {
    //     this.form.leftTotal = parseFloat(this.form.orderTotal) - parseFloat(event.data)
    //   }
    // },
    submitForm2() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            if (this.form.zfbz === 2) {
              this.form.orderTotal = this.form.backTotal
              partbackOrder(this.form).then(response => {
                this.$modal.msgSuccess('退还成功')
                this.open = false
                this.wrong = false
                this.getList()
              })
            } else {
              this.$modal.msgError('订单未取餐，不可因错退还')
            }
          } else {
            this.wrong = false
            this.getList()
          }
        }
      })
    },
    shopOrderSata() {
      this.shopOrderSataForm.open = true
    },
    doShopOrderStatExport() {
      this.shopOrderSataForm.exportLoading = true
      shopOrderStatExport(this.shopOrderSataForm.eventId).then(response => {
        this.$download.name(response.msg)
        this.shopOrderSataForm.exportLoading = false
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm('是否确认导出所有食堂订单数据项？').then(() => {
        this.exportLoading = true
        return exportOrder(queryParams)
      }).then(response => {
        this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    }
    // orgFormatter(val) {
    //   let name = ''
    //     if (item.deptCode == val) {
    //       name = item.deptName
    //     }
    //   })
    //   return name
    // }
  }
}
</script>

<style>
.line-left-right {
  line-height: 1px;
  border-left: 510px solid rgb(221, 221, 221);
  text-align: center;
  height: 2px;
}

.redItem {
  color: #fff;
}
</style>
