<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增配置</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="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="名次" align="center" prop="rankNum" />
      <el-table-column label="兑换豆" align="center" prop="pointCount" />
      <el-table-column label="优惠券数量" align="center" prop="couponCount" />
      <el-table-column label="实物商品数量" prop="productQuantity" align="center" />
      <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" v-if="(scope.$index+1)==list.length" icon="el-icon-delete" @click="handleDelete(scope.row)">移除</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-drawer title="奖品配置" :visible.sync="open" size="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名次" prop="rankNum">
          <el-input v-model="form.rankNum" style="width: 200px;" disabled placeholder="" />
        </el-form-item>
        <el-form-item label="兑换豆" prop="pointCount">
          <el-input-number v-model="form.pointCount" controls-position="right" :min="1" :precision="0"></el-input-number>
          <div class="el-upload__tip">最低配置1个</div>
        </el-form-item>
        <el-form-item label="优惠券商品" prop="couponCount">
          <el-input-number v-model="form.couponCount" controls-position="right" :min="1" :precision="0"></el-input-number>
          <div class="el-upload__tip">0为不发放，发放不同券，不要重复发放</div>
        </el-form-item>
        <el-form-item label="实物积分商品" prop="productName">
          <el-button type="primary" size="small" @click="openSel()">选择</el-button>
          <el-table v-loading="loading" style="margin-top:10px;" :data="form.productName?[form]:[]" @selection-change="handleSelectionChange">
            <el-table-column type="index" width="55" label="序号" align="center">
              <template slot-scope="scope">
                <div>
                  {{scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" align="center" prop="productName" />
            <el-table-column prop="supplierId" label="所属供应商" align="center">
              <template slot-scope="scope">
                <div>
                  {{scope.row.supplier?scope.row.supplier.supplierName: scope.row.supplierName? scope.row.supplierName:'--'}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="categoryId" label="所属分类" align="center">
              <template slot-scope="scope">
                <div>
                  {{scope.row.productCategory?scope.row.productCategory.categoryName:scope.row.categoryName? scope.row.categoryName:'--'}}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" align="center" prop="salePrice" />
            <el-table-column label="所需兑换豆" align="center" prop="points" />
            <el-table-column label="库存" align="center" prop="stock" />
            <el-table-column label="个数" align="center" prop="image" width="120">
              <template slot-scope="scope">
                <div>
                  <el-input-number style="width: 100px;" v-model="scope.row.productQuantity" controls-position="right" :min="0" :precision="0"></el-input-number>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="itemDel(scope.row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <SelPointsGoods ref="SelPointsGoods" @result="selectResult" />
  </div>
</template>

<script>
import { shakeGameAwardList, shakeGameAwardAdd, shakeGameAwardDel, shakeGameAwardInfo, shakeGameAwardEdit } from "@/api/shake.js";
import { getToken } from "@/utils/auth";
import SelPointsGoods from "@/components/SelPointsGoods/index.vue";
export default {
  components: {
    SelPointsGoods,
  },
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "添加广告",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/demo/demo/importData"
      },
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        adName: undefined,
        status: undefined,
        locationCode: undefined
      },
      // 表单参数
      form: {
        orderIndex: 1,
        innerPageCode: null,
        outsideAddress: null,
        resourceModel: null,
        resourceModelId: null,
        resourceModelTitle: null
      },
      // 表单校验
      rules: {
        pointCount: [
          { required: true, message: "请输入兑换豆", trigger: "blur" }
        ],
        couponCount: [
          { required: true, message: "请输入优惠券商品", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "请选择实物积分商品", trigger: "blur" }
        ],
      },
      jumpTypeList: [
        { label: "内部页面", value: 0 },
        { label: "外部链接", value: 1 },
        { label: "内部资源", value: 2 },
      ],
      resourceModelList: [
        // { label: '无', value: 0 },
        { label: "公告", value: 1 },
        { label: "积分商品", value: 2 },
        { label: "商户", value: 3 },
      ],
    };
  },
  created () {
    this.getList();
  },
  methods: {
    openSel () {
      this.$refs.SelPointsGoods.open()
    },
    selectResult (e) {
      this.form.productName = e.title;
      this.form.productId = e.productId;
      Object.assign(this.form, e)
      this.$forceUpdate()
    },
    jumpTypeChange () {
      this.form.innerPageCode = undefined;
      this.form.outsideAddress = undefined;
      this.form.resourceModel = undefined;
      this.form.resourceModelId = undefined;
      this.form.resourceModelTitle = undefined;
      this.$refs.form.clearValidate()
    },
    resourceModelChange () {
      this.form.resourceModelTitle = undefined;
      this.form.resourceModelId = undefined;
      this.$refs.form.clearValidate()
    },
    itemDel (row) {
      this.$modal.confirm('是否确认移除此数据项？').then(() => {
        this.form.productName = undefined;
        this.form.productId = undefined;
        this.$forceUpdate()
      })
    },
    /** 查询测试单表列表 */
    getList () {
      this.loading = true;
      this.queryParams["createTimeStart"] = undefined;
      this.queryParams["createTimeEnd"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["createTimeStart"] = this.daterangeCreateTime[0];
        this.queryParams["createTimeEnd"] = this.daterangeCreateTime[1];
      }
      shakeGameAwardList(this.queryParams).then(response => {
        this.list = response.data;
        // this.total = response.total;
        this.loading = false;
      });
    },
    handleResourceTip (type) {
      for (let item of this.resourceModelList) {
        if (type == item.value) {
          return item.label || "";
        }
      }
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.adId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加广告";
      this.form.rankNum = this.list.length + 1;
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      shakeGameAwardInfo(row.id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.form.productQuantity) {
            this.$message.error("请输入商品数量");
            return false;
          }
          this.buttonLoading = true;
          if (this.form.id) {
            shakeGameAwardEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            shakeGameAwardAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除名次为"' + row.rankNum + '"的数据项？').then(() => {
        this.loading = true;
        return shakeGameAwardDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('demo/demo/export', {
        ...this.queryParams
      }, `demo_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
<style lang="scss">
.el-drawer__body {
  padding: 0 20px !important;
}
</style>
<style lang="scss" scoped>
.flex {
  display: flex;
}
.demo-drawer__footer {
  margin-left: 120px;
}
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff;
  color: rgb(96, 98, 102);
}
.el-upload__tip {
  display: inline-block;
  margin-left: 30px;
}
</style>
