<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="购买时间" prop="payTime">
        <el-date-picker
          clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择购买时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="选择搜索条件" prop="searchField">
        <el-select v-model="queryParams.searchField" placeholder="请选择搜索条件" clearable>
          <el-option v-for="dict in dict.type.buyer_record_search_fields" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入关键词搜索" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="支付状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态" clearable>
          <el-option v-for="dict in dict.type.buyer_record_pay_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in dict.type.buyer_record_order_status" :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="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:record:export']"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column label="订单号" align="center" prop="no" />
      <el-table-column label="企业名称" align="center" prop="company" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="会员购买时长(月)" align="center" prop="memberPayDuration" />
      <el-table-column label="购买数量" align="center" prop="amount" />
      <el-table-column label="实付价格" align="center" prop="payPrice" />
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_record_pay_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_record_order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="购买时间" align="center" prop="payTime" width="180" />
      <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:record:edit']"
            v-if="scope.row.orderStatus === '0'"
          >修改价格
          </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">
        <div class="tips">{{ form.closeSecond > 0 ? '订单将于' + getTime(form.closeSecond) + '后自动关闭' : '订单已超时' }}</div>
        <el-descriptions :column="2" :labelStyle="{color:'#aaa'}">
          <el-descriptions-item label="订单编号">{{ form.no }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ form.goodsName }}</el-descriptions-item>
          <el-descriptions-item label="购买企业">{{ form.company }}</el-descriptions-item>
          <el-descriptions-item label="服务时长">{{ form.memberPayDuration }}个月</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ form.name }}</el-descriptions-item>
          <el-descriptions-item label="单价(元)">{{ form.price }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ form.phone }}</el-descriptions-item>
          <el-descriptions-item label="实付金额"><span style="color: #ff4949">{{ form.payPrice }}</span></el-descriptions-item>
        </el-descriptions>
        <el-form-item label="修改金额" prop="payPrice">
          <el-input v-model="form.payPrice" type="number" placeholder="请填写修改金额" />
        </el-form-item>
        <div class="notice">提示：修改后将直接影响订单，请仔细操作</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.closeSecond < 1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from '@/api/buyer/record'

export default {
  name: 'Record',
  dicts: ['buyer_record_search_fields', 'buyer_record_pay_status', 'buyer_record_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单记录表格数据
      recordList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchField: null,
        keyword: null,
        orderStatus: null,
        payStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        payPrice: [
          { required: true, message: '请填写修改金额', trigger: 'blur' }
        ]
      },
      timer: null
    }
  },
  watch: {
    'form.closeSecond': {
      handler(val) {
        if (val < 1) {
          console.log('clear')
          clearInterval(this.timer)
          this.getList()
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {

    /** 查询订单记录列表 */
    getList() {
      this.loading = true
      listRecord(this.addSearchField(this.queryParams, this.queryParams.searchField, this.queryParams.keyword))
        .then(response => {
          this.recordList = response.rows
          this.total = response.total
          this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      clearInterval(this.timer)
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      delete this.queryParams[this.queryParams.searchField]
      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 = '添加订单记录'
    },
    getTime(time) {
      // 转换为式分秒
      let h = parseInt(time / 60 / 60 % 24)
      h = h < 10 ? '0' + h : h
      let m = parseInt(time / 60 % 60)
      m = m < 10 ? '0' + m : m
      let s = parseInt(time % 60)
      s = s < 10 ? '0' + s : s
      // 作为返回值返回
      return `${m} 分${s} 秒`
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data
        this.timer = setInterval(() => {
          if (this.form.closeSecond > 0) {
            this.form.closeSecond--
          } else {
            this.getList()
          }
        }, 1000)
        this.open = true
        this.title = '修改订单记录'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除订单记录选中的数据项？').then(function() {
        return delRecord(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.notice {
  font-size: 12px;
  color: #555;
}
</style>
