<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <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="payTime">
        <el-date-picker
          v-model="queryParams.payTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="付款方式">
        <el-select v-model="queryParams.payType" placeholder="请选择付款方式" clearable>
          <el-option
            v-for="dict in dict.type.buyer_pay_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务时长">
        <el-select v-model="queryParams.memberPayDuration" placeholder="请选择服务时长" clearable @change="handleDurationChange">
          <el-option
            v-for="item in goodsList"
            :key="item.id"
            :label="getLabel(item)"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开票状态">
        <el-select v-model="queryParams.billStatus" placeholder="请选择开票状态" clearable>
          <el-option
            v-for="dict in dict.type.buyer_user_bill_status"
            :key="dict.value"
            :label="dict.duration"
            :value="dict.label"
          />
        </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-tabs v-model="activeName" type="card" class="custom-tab" @tab-click="getList">
      <el-tab-pane label="全部订单" name="全部">
      </el-tab-pane>
      <el-tab-pane label="待付款" name="0">
      </el-tab-pane>
      <el-tab-pane label="已完成" name="1">
      </el-tab-pane>
      <el-tab-pane label="已关闭" name="2">
      </el-tab-pane>
    </el-tabs>
    <el-table stripe v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <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="payTime" width="180" />
      <el-table-column label="发票状态" align="center" prop="billStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_user_bill_status" :value="scope.row.billStatus" v-if="scope.row.billStatus" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_record_order_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_pay_type" :value="scope.row.payType" v-if="scope.row.payType" />
          <span v-else>-</span>
        </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,'pay')"
            v-hasPermi="['system:record:edit']"
            v-if="scope.row.payStatus === '0'"
          >去支付
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAddBill(scope.row)"
            v-hasPermi="['system:record:edit']"
            v-if="scope.row.billStatus === '0' && scope.row.payStatus === '1'"
          >申请开票
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownloadBill(scope.row)"
            v-hasPermi="['system:record:edit']"
            v-if="scope.row.billStatus === '2' && scope.row.payStatus === '1'"
          >下载开票
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row,'cancel')"
            v-hasPermi="['system:record:edit']"
            v-if="scope.row.payStatus === '0'"
          >取消订单
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:record:remove']"
            v-if="scope.row.payStatus !== '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="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="125px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" :disabled="true" />
        </el-form-item>
        <el-form-item label="服务时长(月)" prop="memberPayDuration">
          <el-input v-model="form.memberPayDuration" placeholder="请输入会员购买时长(月)" :disabled="true" />
        </el-form-item>
        <el-form-item label="单价(元)" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入购买价格" :disabled="true" />
        </el-form-item>
        <el-form-item label="实付金额" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入购买价格" :disabled="true" />
        </el-form-item>
        <div class="pay-tip">提示：本服务不支持退款，请仔细核对信息</div>
        <el-form-item label="选择快捷支付方式" prop="payPrice">
          <el-button type="success">微信支付</el-button>
          <el-button type="primary">支付宝</el-button>
        </el-form-item>
        <div class="close-count">{{ form.closeSecond > 0 ? '订单将于' + getTime(form.closeSecond) + '后自动关闭' : '订单已超时' }}</div>
      </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="billOpen" width="600px" append-to-body>
      <el-form ref="billForm" :model="billForm" :rules="rules" label-width="125px">
        <el-form-item label="发票类型" prop="billType">
          <el-radio-group v-model="billForm.billType">
            <el-radio
              v-for="dict in dict.type.buyer_bill_type"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="抬头类型" prop="billHeadType">
          <el-radio-group v-model="billForm.billHeadType">
            <el-radio
              v-for="dict in dict.type.buyer_bill_head_type"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发票抬头" prop="billHeadTitle">
          <el-input v-model="billForm.billHeadTitle" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="taxNumber" v-if="billForm.billHeadType === '0'">
          <el-input v-model="billForm.taxNumber" placeholder="请输入纳税人识别号" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="billForm.email" 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 { listRecord, getRecord, delRecord, addRecord, updateRecord } from '@/api/buyer/record'
import { listGoods } from '@/api/buyer/goods'
import { addBill } from '@/api/buyer/bill'
import { fileDownload } from '@/utils'

export default {
  name: 'Record',
  dicts: [
    'buyer_project_search_fields',
    'buyer_user_bill_status',
    'buyer_pay_type',
    'buyer_record_order_status',
    'buyer_duration_unit',
    'buyer_bill_type',
    'buyer_bill_head_type'
  ],
  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,
        payTime: null,
        payType: null,
        memberPayDuration: null,
        billStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billType: [
          { required: true, message: '请选择发票类型', trigger: 'blur' }
        ],
        billHeadType: [
          { required: true, message: '请选择抬头类型', trigger: 'blur' }
        ],
        billHeadTitle: [
          { required: true, message: '发票抬头不能为空', trigger: 'blur' }
        ],
        taxNumber: [
          { required: true, message: '纳税人识别号不能为空', trigger: 'blur' }
        ]
      },
      activeName: '全部',
      goodsList: [],
      timer: null,
      billForm: {
        billType: '0',
        billHeadType: '0'
      },
      billOpen: false
    }
  },
  watch: {
    'form.closeSecond': {
      handler(val) {
        if (val < 1) {
          console.log('clear')
          clearInterval(this.timer)
        }
      }
    }
  },
  created() {
    this.getList()
    this.getGoodsList()
  },
  methods: {
    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} 秒`
    },
    getLabel(item) {
      const unit = this.selectDictLabel(this.dict.type.buyer_duration_unit, item.unit)
      return item.duration + unit
    },
    handleDurationChange() {
      const matchItem = this.goodsList.find(item => item.id === this.form.memberPayDuration)
      this.queryParams.duration = matchItem.duration
      this.queryParams.unit = matchItem.unit
    },
    getGoodsList() {
      listGoods({ pageNum: 1, pageSize: 999999 }).then(res => {
        this.goodsList = res.rows
      })
    },
    /** 查询订单记录列表 */
    getList() {
      this.queryParams.orderStatus = this.activeName === '全部' ? '' : this.activeName
      this.loading = true
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      clearInterval(this.timer)
      this.reset()
    },
    // 表单重置
    reset() {
      this.billForm = {
        billType: '0',
        billHeadType: '0'
      }
      this.resetForm('billForm')
    },
    /** 搜索按钮操作 */
    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, type = '') {
      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 = '选择支付'
      })
    },
    // 开票
    handleAddBill(row) {
      this.reset()
      const id = row.id || this.ids
      getRecord(id).then(response => {
        Object.assign(this.billForm, response.data)
        this.billOpen = true
        this.title = '申请开票'
      })
    },
    handleDownloadBill(row) {
      const filePathArray = row.fileNames
      fileDownload({ filePathArray })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['billForm'].validate(valid => {
        if (valid) {
          this.billForm.orderId = this.billForm.id
          addBill(this.billForm).then(response => {
            this.$modal.msgSuccess('开票申请成功')
            this.billOpen = false
          })
          updateRecord({ ...this.billForm, billStatus: '1' }).then(() => {
            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('buyer/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.pay-tip {
  margin: 15px 0;
}
</style>
