<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="批次号" prop="batchCode">
        <el-input v-model="queryParams.batchCode" placeholder="请输入批次号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="码号" prop="codeNumber">
        <el-input v-model="queryParams.codeNumber" placeholder="请输入码号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="couponStatus">
        <el-select v-model="queryParams.couponStatus" placeholder="请选择状态" clearable size="small" style="width: 240px">
          <el-option v-for="(v,i) in couponStatusList" :key="i" v-if="!v.hide" :label="v.label" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售状态" prop="codeStatus">
        <el-select v-model="queryParams.codeStatus" placeholder="请选择状态" clearable size="small" style="width: 240px">
          <el-option v-for="(v,i) in codeStatusList" :key="i" :label="v.label" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售时间">
        <el-date-picker v-model="daterangeCreateTime" size="small" 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-date-picker v-model="daterangeCreateTime1" size="small" 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-date-picker v-model="daterangeCreateTime2" size="small" 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>
        <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-button icon="el-icon-back" size="mini" @click="goBack()">返回</el-button>
      </el-form-item>
    </el-form>
    <div class="list">
      <div class="item">项目名称：<span>{{$route.query.title}}</span></div>
      <div class="item">码库总数：<span>{{statistics.codeSum}}</span></div>
      <div class="item">待销售：<span>{{statistics.waitSaleSum}}</span></div>
      <div class="item">已销售：<span>{{statistics.saleSum}}</span></div>
      <div class="item">待使用：<span>{{statistics.waitUseSum}}</span></div>
      <div class="item">已核销：<span>{{statistics.useSum}}</span></div>
      <div class="item">已过期：<span>{{statistics.expiredSum}}</span></div>
      <div class="item">已作废：<span>{{statistics.cancelSum}}</span></div>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="CouponVerification()">核销</el-button>
        <el-button type="primary" plain size="mini" @click="openBatchWriteOff()">批量核销</el-button>
        <el-button type="primary" plain size="mini" @click="cancellation()">作废</el-button>
        <el-button type="primary" plain size="mini" @click="dialogVisible = true">延期</el-button>
        <el-button type="danger" plain size="mini" @click="handleDelete()">删除</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImport()">导入码</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="码号" align="center" prop="codeNumber" />
      <el-table-column label="销售状态" align="center" prop="codeStatus">
        <template slot-scope="{row}">
          <el-tag v-if="row.codeStatus===0">待销售</el-tag>
          <el-tag v-if="row.codeStatus===1" type="danger">已销售</el-tag>
          <el-tag v-if="row.codeStatus===9" type="info">已作废</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="couponStatus">
        <template slot-scope="{row}">
          <span v-for="(v,i) in couponStatusList" :key="i" v-if="row.couponStatus===v.value">{{v.label}}</span>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售时间" align="center" prop="orderTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}')||'--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售订单号" align="center" prop="orderNumber" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.orderNumber||'--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="核销时间" align="center" prop="useTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.useTime, '{y}-{m}-{d} {h}:{i}')||'--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="核销人" align="center" prop="verificationSysUserName">
        <template slot-scope="scope">
          <span>{{ scope.row.verificationSysUserName||'--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款时间" align="center" prop="refundTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.refundTime, '{y}-{m}-{d} {h}:{i}')||'--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d} {h}:{i}')||'--' }}</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)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" @click="setStatus(scope.row)">{{scope.row.status?'下架':'上架'}}</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="导入码" :visible.sync="upload.open" width="400px" append-to-body :before-close="closeUpload">
      <el-upload ref="upload1" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url+'?productId='+$route.query.productId" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="closeUpload()">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量核销 -->
    <batchWriteOff :productId="$route.query.productId" ref="batchWriteOffRef" @success="getList()" />
    <!-- 延期弹窗 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="close">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="延期天数" prop="dayNum">
          <el-input-number v-model="form.dayNum" controls-position="right" :min="0" :precision="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="postpone()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import batchWriteOff from "@/views/goods/batchWriteOff.vue"
import { getToken } from "@/utils/auth";
import { businessProductCodePage, verification, businessProductCodeCancel, businessProductCodeDelay, businessProductCodeStatistics, businessProductCodeDel, businessProductCodeVerification } from "@/api/goods.js"
export default {
  components: { batchWriteOff },
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      daterangeCreateTime1: [],
      daterangeCreateTime2: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 导入码参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/businessProductCode/import"
      },
      form: {
        dayNum: undefined
      },
      rules: {
        dayNum: [
          { required: true, message: '请输入延期天数', trigger: 'blur' }
        ],
      },
      dialogVisible: false,
      codeStatusList: [
        { label: "待销售", value: 0 },
        { label: "已销售", value: 1 },
        { label: "已作废", value: 9 }
      ],
      statistics: {},
      couponStatusList: [
        { label: "--", value: null, tag: "", hide: true },
        { label: "待使用", value: 0, tag: "" },
        { label: "已使用", value: 10, tag: "" },
        { label: "已退款", value: 20, tag: "", hide: true },
        { label: "退款中", value: 21, tag: "" },
        { label: "已过期", value: 30, tag: "", hide: true },
      ]
    }
  },
  created () {
    this.getList();
  },
  methods: {
    handleAdd () {

    },
    closeUpload () {
      this.upload.open = false
    },
    goBack () {
      if (this.$route.query.queryParams) {
        localStorage.setItem('queryParams', this.$route.query.queryParams)
      }
      this.$router.go(-1);
    },
    close () {
      this.form = {
        dayNum: undefined
      };
      this.$refs.ruleForm.resetFields();
      this.dialogVisible = false
    },
    getStatistics () {
      businessProductCodeStatistics({ productId: this.$route.query.productId }).then(res => {
        this.statistics = res.data
      })
    },
    CouponVerification () {
      const ids = this.ids;
      this.$modal.confirm('确定核销已选择的券码吗？').then(() => {
        this.loading = true;
        return businessProductCodeVerification({ codeIdList: ids });
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("核销成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    // 作废
    cancellation (row = {}) {
      const ids = row.codeId || this.ids;
      this.$modal.confirm('确定作废已选择状态为待销售的券码吗？').then(() => {
        this.loading = true;
        return businessProductCodeCancel({ codeIdList: ids });
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("作废成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    // 延期
    postpone () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const ids = this.ids;
          this.$modal.confirm('确定延期已选择的券码吗？').then(() => {
            this.loading = true;
            this.form.codeIdList = ids
            return businessProductCodeDelay(this.form);
          }).then(() => {
            this.loading = false;
            this.getList();
            this.close()
            this.$modal.msgSuccess("延期成功");
          }).finally(() => {
            this.loading = false;
          });
        }
      })
    },
    // 删除
    handleDelete () {
      const ids = this.ids;
      this.$modal.confirm('确定删除已选择的券码吗？').then(() => {
        this.loading = true;
        return businessProductCodeDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.codeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.daterangeCreateTime1 = [];
      this.daterangeCreateTime2 = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询测试单表列表 */
    getList () {
      this.loading = true;
      this.queryParams["createTimeStart"] = undefined;
      this.queryParams["createTimeEnd"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["orderTimeStart"] = this.daterangeCreateTime[0] + ' 00:00:00';
        this.queryParams["orderTimeEnd"] = this.daterangeCreateTime[1] + ' 23:59:59';
      }
      this.queryParams["useTimeStart"] = undefined;
      this.queryParams["useTimeEnd"] = undefined;
      if (null != this.daterangeCreateTime1 && '' != this.daterangeCreateTime1) {
        this.queryParams["useTimeStart"] = this.daterangeCreateTime1[0] + ' 00:00:00';
        this.queryParams["useTimeEnd"] = this.daterangeCreateTime1[1] + ' 23:59:59';
      }
      this.queryParams["createTimeStart"] = undefined;
      this.queryParams["createTimeEnd"] = undefined;
      if (null != this.daterangeCreateTime2 && '' != this.daterangeCreateTime2) {
        this.queryParams["createTimeStart"] = this.daterangeCreateTime2[0] + ' 00:00:00';
        this.queryParams["createTimeEnd"] = this.daterangeCreateTime2[1] + ' 23:59:59';
      }
      this.queryParams.productId = this.$route.query.productId
      businessProductCodePage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
        this.getStatistics()
      });
    },
    openBatchWriteOff () {
      this.$refs.batchWriteOffRef.open()
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.open = true;
      this.$refs.upload1.clearFiles()
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('/system/businessProductCode/export-template', {
      }, `券码导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (response, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload1.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload1.submit();
    }
  },
}
</script>

<style lang='scss' scoped>
.list {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 20px;
  span {
    color: #b69139;
  }
}
</style>