<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="订单ID" prop="orderId">-->
<!--        <el-input-->
<!--          v-model="queryParams.orderId"-->
<!--          placeholder="请输入订单ID"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="订单号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐ID" prop="setmealId">
        <el-input
          v-model="queryParams.setmealId"
          placeholder="请输入套餐ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总月数" prop="month">
        <el-input
          v-model="queryParams.month"
          placeholder="请输入总月数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前次数" prop="count">
        <el-input
          v-model="queryParams.count"
          placeholder="请输入当前次数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      0待处理, 1正在处理, 2成功, -1失败, 3用户拒签或者退货-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
          <el-option v-for="(item, index) in statusOptions"
                     :key="index"
                     :label="item.dictLabel"
                     :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.orderTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="优惠券ID" prop="couponId">
        <el-input
          v-model="queryParams.couponId"
          placeholder="请输入优惠券ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预计发送时间" prop="sendTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.sendTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择预计发送时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际发送时间" prop="actualSendTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.actualSendTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择实际发送时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMessage">
        <el-input
          v-model="queryParams.errorMessage"
          placeholder="请输入错误信息"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryCount">
        <el-input
          v-model="queryParams.retryCount"
          placeholder="请输入重试次数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" 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="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:schedule:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:schedule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:schedule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:schedule:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="订单号" align="center" prop="orderCode" />
      <el-table-column label="套餐ID" align="center" prop="setmealId" />
      <el-table-column label="总月数" align="center" prop="month" />
      <el-table-column label="当前次数" align="center" prop="count" />
<!--      0待处理, 1正在处理, 2成功, -1失败, 3用户拒签或者退货-->
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope" v-if="statusOptions">
          <span>{{statusText(scope.row.status)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券ID" align="center" prop="couponId" />
      <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="actualSendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualSendTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center" prop="errorMessage" />
      <el-table-column label="重试次数" align="center" prop="retryCount" />
<!--      <el-table-column label="订单来源" align="center" prop="sourceType" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <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="['system:schedule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:schedule: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" disabled/>
        </el-form-item>
<!--        <el-form-item label="订单ID" prop="orderId">-->
<!--          <el-input v-model="form.orderId" placeholder="请输入订单ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="套餐ID" prop="setmealId">
          <el-input v-model="form.setmealId" placeholder="请输入套餐ID" disabled/>
        </el-form-item>
        <el-form-item label="总月数" prop="month">
          <el-input v-model="form.month" placeholder="请输入总月数" />
        </el-form-item>
        <el-form-item label="当前次数" prop="count">
          <el-input v-model="form.count" placeholder="请输入当前次数" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="scheduleCouponStatus" placeholder="请选择" clearable size="small">
            <el-option v-for="(item, index) in statusOptions"
                       :key="index"
                       :label="item.dictLabel"
                       :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="下单时间" prop="orderTime">-->
<!--          <el-date-picker clearable size="small" style="width: 200px"-->
<!--            v-model="form.orderTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="选择下单时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->


        <el-form-item label="预计发送时间" prop="sendTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.sendTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择预计发送时间">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="实际发送时间" prop="actualSendTime">-->
<!--          <el-date-picker clearable size="small" style="width: 200px"-->
<!--            v-model="form.actualSendTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="选择实际发送时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="重试次数" prop="retryCount">
          <el-input v-model="form.retryCount" placeholder="请输入重试次数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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>
  </div>
</template>

<script>
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule, exportSchedule } from "@/api/store/schedule";
import {getDicts} from "../../../api/system/dict/data";

export default {
  name: "Schedule",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时发放优惠券队列表格数据
      scheduleList: [],
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        orderId: null,
        orderCode: null,
        setmealId: null,
        month: null,
        count: null,
        status: null,
        orderTime: null,
        executeTime: null,
        couponId: null,
        couponBatchId: null,
        sendTime: null,
        actualSendTime: null,
        errorMessage: null,
        retryCount: null,
        maxRetries: null,
        nextRetryTime: null,
        sourceType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        orderId: [
          { required: true, message: "订单ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();

    getDicts("coupon_issue_status").then(response=>{
      this.statusOptions = response.data;
    })
  },
  computed: {
    statusText() {
      return (status) => {
        console.log(this.statusOptions)

        const item = this.statusOptions.find(option => option.dictValue == status);
        return item ? item.dictLabel : ''; // 或者一个默认值
      };
    },
    scheduleCouponStatus: {
      get(){
        return this.form.status?.toString()
      },
      set(newVal){
        this.form.status = Number(newVal)
      }
    }
  },
  methods: {
    /** 查询定时发放优惠券队列列表 */
    getList() {
      this.loading = true;
      listSchedule(this.queryParams).then(response => {
        this.scheduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        orderId: null,
        orderCode: null,
        setmealId: null,
        month: null,
        count: null,
        status: 0,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        orderTime: null,
        executeTime: null,
        couponId: null,
        couponBatchId: null,
        sendTime: null,
        actualSendTime: null,
        errorMessage: null,
        retryCount: null,
        maxRetries: null,
        nextRetryTime: null,
        sourceType: null,
        remark: 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() {
      this.reset();
      this.open = true;
      this.title = "添加定时发放优惠券队列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSchedule(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改定时发放优惠券队列";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSchedule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addSchedule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除定时发放优惠券队列编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSchedule(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有定时发放优惠券队列数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSchedule(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
