<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="预定日期" prop="sendTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.sendTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择预定日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态" prop="sendStatus">
        <el-select v-model="queryParams.sendStatus" placeholder="请选择发送状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.send_status_dic"
            :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-form>
      <el-form-item label="订餐时间段">
        <el-time-picker
          value-format="HH:mm"
          format="HH:mm"
          is-range
          v-model="timeSlot"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围">
        </el-time-picker>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['consume:maintain:add']"
        >预定发布
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd1"
          v-hasPermi="['consume:maintain:add']"
        >点餐发布
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['consume:maintain:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['consume:maintain:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['consume:maintain:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="maintainList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="订单编号" align="center" prop="id" />-->
      <el-table-column label="菜单" align="center" prop="menuName"/>
      <el-table-column label="发布状态" align="center" prop="sendStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.send_status_dic" :value="scope.row.sendStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="预定日期" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="定时发送" align="center" prop="isTiming" >-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isTiming"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="开始时间" align="center" prop="beginDate"/>
      <el-table-column label="结束时间" align="center" prop="endDate"/>
      <el-table-column label="备注" align="center" prop="describeInfo"/>
      <el-table-column label="是否删除" align="center" prop="isDelete" v-if="false">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isDelete"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['consume:maintain:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['consume:maintain:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改订餐消费维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="预定日期" prop="sendTime">
          <el-date-picker clearable size="small"
                          :picker-options="expireTimeOption"
                          v-model="form.sendTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择预定日期"
                          @change="changeTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="菜单" prop="menuNumber">
          <el-select v-model="form.menuNumber" placeholder="请选择菜单">
            <el-option
              v-for="item in menuOptions"
              :key="item.menuNumber"
              :label="item.menuName"
              :value="item.menuNumber"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="describeInfo">
          <el-input v-model="form.describeInfo" placeholder="请输入描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改订餐消费维护对话框 -->
    <el-dialog :title="title" :visible.sync="open1" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="菜单" prop="menuNumber">
          <el-select v-model="form.menuNumber" placeholder="请选择菜单">
            <el-option
              v-for="item in menuOptions"
              :key="item.menuNumber"
              :label="item.menuName"
              :value="item.menuNumber"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="就餐地" prop="jcd">
          <el-select v-model="form.placeNumber" placeholder="请选择就餐地" clearable size="small">
            <el-option
              v-for="dict in jcd"
              :key="dict.placeNumber"
              :label="dict.placeName"
              :value="dict.placeNumber"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="describeInfo">
          <el-input v-model="form.describeInfo" placeholder="请输入描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(1)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaintain,
  getMaintain,
  delMaintain,
  addMaintain,
  updateMaintain,
  exportMaintain,
  queryMenuDict
} from '@/api/consume/maintain'
import user from '@/store/modules/user'
import { getConfigKey } from '@/api/system/config'
import { getPlace } from '@/api/canteen/order'

export default {
  name: 'Maintain',
  dicts: ['send_status_dic', 'yes_or_no'],
  data() {
    // const validatorTimeSlot = function (rule, value, callback) {
    //   if (!/^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/.test(value)) {
    //     callback(new Error('时间段格式错误,应为HH:mm'))
    //   } else {
    //     callback()
    //   }
    // }

    return {
      jcd: [],
      // 遮罩层
      timeSlot: [],
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订餐消费维护表格数据
      maintainList: [],
      menuOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sendTime: null,
        sendStatus: null,
        isTiming: null,
        menuNumber: null,
        organizationCode: null,
        organizations: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sendTime: [
          { required: true, message: '预定日期不能为空', trigger: 'change' }
        ],
        menuNumber: [
          { required: true, message: '菜单不能为空', trigger: 'blur' }
        ]
        // beginDate: [
        //   { required: true, message : "开始时间段不能为空", trigger: "blur" },
        //   { required: true, validator: validatorTimeSlot, trigger: "blur" }
        // ],
        // endDate: [
        //   { required: true, message : "结束时间段不能为空", trigger: "blur" },
        //   { required: true, validator: validatorTimeSlot, trigger: "blur" }
        // ],
      },
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  created() {
    this.getTimeSlot()
    this.getList()
    this.getPlaceList()
  },
  methods: {
    getPlaceList() {
      var data = {
        organizationCode: user.state.organ
      }
      getPlace(data).then(re => {
        this.jcd = re.data
        console.log(re.data)
      })
    },
    /** 查询订餐消费维护列表 */
    getList() {
      this.queryParams.organizationCode = user.state.organ
      this.loading = true
      listMaintain(this.queryParams).then(response => {
        this.maintainList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.open1 = false
      this.menuOptions = []
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sendTime: null,
        sendStatus: 0,
        describeInfo: null,
        isTiming: null,
        menuNumber: null,
        beginDate: null,
        endDate: null,
        isDelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.timeSlot) {
        this.$message.error('订餐时间段不能为空!')
        return
      }
      this.reset()
      this.open = true
      this.title = '发布预定消费菜单'
      if (this.timeSlot[0] instanceof Date) {
        this.form.beginDate = this.formatDate(this.timeSlot[0])
      } else {
        this.form.beginDate = this.timeSlot[0]
      }
      if (this.timeSlot[1] instanceof Date) {
        this.form.endDate = this.formatDate(this.timeSlot[1])
      } else {
        this.form.endDate = this.timeSlot[1]
      }
      this.form.organizationCode = user.state.organ
    },
    handleAdd1() {
      this.form.sendTime = null
      this.changeTime(null)
      if (!this.timeSlot) {
        this.$message.error('订餐时间段不能为空!')
        return
      }
      this.reset()
      this.open1 = true
      this.title = '发布点餐消费菜单'
      if (this.timeSlot[0] instanceof Date) {
        this.form.beginDate = this.formatDate(this.timeSlot[0])
      } else {
        this.form.beginDate = this.timeSlot[0]
      }
      if (this.timeSlot[1] instanceof Date) {
        this.form.endDate = this.formatDate(this.timeSlot[1])
      } else {
        this.form.endDate = this.timeSlot[1]
      }
      this.form.organizationCode = user.state.organ
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMaintain(id).then(response => {
        this.changeTime(response.data.sendTime)
        this.form = response.data
        this.open = true
        this.title = '修改订餐消费维护'
      })
    },

    compareTime(beginDate, endDate) {
      let beginTime = Number(beginDate.split(':')[0] * 3600) + Number(beginDate.split(':')[1] * 60)
      let endTime = Number(endDate.split(':')[0] * 3600) + Number(endDate.split(':')[1] * 60)
      if (beginTime > endTime) {
        this.$message({ message: '开始时间段不能大于结束时间段!', type: 'warning' })
        return false
      }
      return true
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMaintain(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMaintain(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除订餐消费维护编号为"' + ids + '"的数据项？').then(function() {
        return delMaintain(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm('是否确认导出所有订餐消费维护数据项？').then(() => {
        this.exportLoading = true
        return exportMaintain(queryParams)
      }).then(response => {
        this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },

    changeTime(val) {
      let organizationCode = ''
      organizationCode = user.state.organ
      queryMenuDict({ date: val, jgid: organizationCode }).then(res => {
        if (res.data && res.data.length > 0) {
          this.menuOptions = res.data
        } else {
          this.form.menuNumber = '',
            this.menuOptions = []
        }
      })
    },
    getTimeSlot() {
      getConfigKey('customTimeSlot').then(res => {
        var times = res.msg.split(',')
        this.timeSlot = [this.timeProcess(times[0]), this.timeProcess(times[1])]
      })
    },
    timeProcess(m) {
      if (m != '' || m != undefined) {
        var ms = m.substring(0, 2)
        var me = m.substring(3)
        // 2020,1,1 表示年月日 可自定义（存在的时间即可）
        return new Date(2020, 1, 1, Number(ms), Number(me))
      }
    },
    formatDate(val) {
      const h = val.getHours()
      const m = val.getMinutes()
      return [h, m].map(e => this.formatNumber(e)).join(':')
    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }
  }
}
</script>
