<template>
  <el-dialog class="activity-dialog" :visible.sync="visible" v-bind="modalOptions">
    <div>
      <div style="padding: 6px;font-size: 20px;font-weight: bold;">活动列表/报名</div>
      <div>
        <div v-if="formData.ifBond">
          <el-steps :active="activeStep">
            <el-step title="选择商品" />
            <el-step v-if="formData.ifBond" title="缴纳保证金" />
            <el-step title="完成" />
          </el-steps>
        </div>
        <div v-if="activeStep === 1">
          <!-- 查询和其他操作 -->
          <div class="filter-container">
            <el-select
              v-model="listQuery.condition" clearable size="mini" class="filter-item"
              style="width: 200px;"
              placeholder="请选择查找类型"
            >
              <el-option label="商品id" value="1" />
              <el-option label="商品名称" value="2" />
            </el-select>
            <el-input
              v-model="listQuery.search" clearable size="mini" class="filter-item"
              style="width: 200px;margin-left: 10px;" placeholder="请输入内容"
            />
            <el-cascader
              v-model="listQuery.classifyId" placeholder="请选择官方分类" :options="categoryList"
              :props="{ checkStrictly: true, expandTrigger: 'hover', label: 'categoryName', value: 'id', children: 'childs' }"
              clearable size="mini" class="filter-item" style="width: 200px;margin-left: 10px;"
            />
            <el-select
              v-model="listQuery.groupId" size="mini" class="filter-item"
              style="width: 200px;margin-left: 10px;" placeholder="请选择商品分组"
            >
              <el-option
                v-for="(item, index) in groupList" :key="index" :label="item.groupName"
                :value="item.shopGroupId"
              />
            </el-select>
            <el-button
              size="mini" class="filter-item" type="primary" icon="el-icon-search"
              style="margin-left:10px;"
              @click="handleSearch"
            >
              查找
            </el-button>
            <el-button size="mini" type="info" class="filter-item" @click="handleReset">
              重置
            </el-button>
          </div>

          <!-- 表格 -->
          <div style="position: relative;padding: 0 0 10px;">
            <div style="font-size: 20px;">
              已选中{{ multipleSelection.length }}商品
            </div>
            <el-table
              ref="multipleTable" v-loading="listLoading" :data="tableDataList" border
              :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
              :row-key="(row) => row.productId" @selection-change="(e) => multipleSelection = e"
            >
              <el-table-column type="selection" :reserve-selection="true" width="55" />
              <el-table-column prop="productId" label="商品id" />
              <el-table-column label="商品主图" width="220" align="center" prop="image">
                <template slot-scope="{ row }">
                  <el-image
                    v-if="row.image" lazy :src="common.seamingImgUrl(row.image)" style="width:80px;height:80px;"
                    fit="cover" :preview-src-list="[ common.seamingImgUrl(row.image) ]"
                  />
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" />
              <el-table-column prop="sectionPrice" label="售价区间" />
              <el-table-column prop="stockNumber" label="库存" />
              <el-table-column label="商品限量（件）">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.number" maxlength="9" value="$page"
                    oninput="value=value.replace(/[^\d]/g,'')" @blur="handleBlurNumber(scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
            <div style="position: sticky;bottom: -5px;z-index: 1;padding: 10px;background-color: #eeeeee;">
              <el-pagination
                :current-page="listQuery.page" :page-sizes="[50, 100, 200, 500, 1000]"
                :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="(val) => ((listQuery.pageSize = val) && getList())"
                @current-change="(val) => ((listQuery.page = val) && getList())"
              />
            </div>
          </div>
        </div>
        <!-- 缴纳保证金 -->
        <div v-if="activeStep === 2">
          <div style="text-align: center;">
            <div style="font-size: 18px;font-weight: bold;">保 证 金：￥{{ formData.bondMoney }}</div>
            <div style="margin: 6px 0 0;">
              <div id="qrcode">
                <el-image
                  v-if="payImage" lazy :src="payImage" style="width:200px;height:200px;"
                  fit="cover" :preview-src-list="[ payImage ]"
                />
              </div>
              <div style="font-size: 16px;font-weight: bold;">扫我付钱</div>
            </div>
            <ul style="margin: 6px 0 0;">
              <li>tips:</li>
              <li
                v-for="(item, index) in ['、缴纳保证金是为了防止活动中出现纠纷或退款时账户无钱退返的情况。', '、平台不接触保证金，会由第三方存管机构冻结。', '、活动结束后15天内将退返保证金', '、活动开始后未完成审核将自动退返保证金', '、报名失败且3天内未重新报名也会自动退返保证金']" :key="index"
              >
                {{ index + 1 }}{{ item }}
              </li>
            </ul>
          </div>
        </div>
        <!-- 报名成功 -->
        <div v-if="activeStep === 3">
          <div style="font-size: 16px;text-align: center;">
            <div style="font-size: 18px;font-weight: bold;">报名成功</div>
            <div v-if="infoData.signCode">成功支付￥{{ infoData.price }}</div>
            <div v-if="infoData.signCode">
              <span>交易类型:{{ infoData.type }}</span>
              <span>交易流水号:{{ infoData.signCode }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">返 回</el-button>
      <el-button v-if="activeStep !== 3" type="primary" size="mini" @click="handleSubmit">报 名</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getClassify } from '@/api/commodity'
import { getGroups, getProducts, activitySave, checkPay } from '@/api/active'

export default {
  name: 'SignActivity',
  components: {
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '1120px',
        title: ''
      },
      visible: false,
      formData: {
        type: 1,
        activityId: '',
        bondMoney: '',
        ifBond: '',
        signType: ''
      },

      groupList: [],
      categoryList: [],
      activeStep: 1,
      listQuery: {
        page: 1,
        pageSize: 50,
        condition: '1', // 商品模糊搜索条件 1-商品id 2-商品名称
        search: '', // 搜索字段
        classifyId: '', // 分类id
        groupId: '' // 商品分组id
      },
      infoData: {
        price: '',
        type: '',
        signCode: ''
      },
      total: 0,
      tableDataList: [],
      multipleSelection: [],
      payImage: '',
      boneTimer: null,
      listLoading: false,
      inputTableData: [] // 存储输入框有值的数据
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async initList() {
      // 初始化查询商品分组
      const res1 = await getGroups({})
      this.groupList = res1.data
      // 初始化查询所有分类
      const res2 = await getClassify()
      this.categoryList = res2.data
    },
    handleOpen(params = {}) {
      this.modalOptions.title = params.activityId ? '活动报名' : '报名'
      this.formData.activityId = params.activityId
      this.formData.bondMoney = params.bondMoney
      this.formData.ifBond = params.ifBond
      this.formData.signType = params.signType
      this.activeStep = 1
      this.visible = true
      this.$nextTick(() => {
        this.inputTableData = []
        this.$refs.multipleTable && this.$refs.multipleTable.clearSelection()
      })
      this.initList()
      if (params.activityId) {
        // this.getInfo(params.activityId)
        this.getList()
        // this.initSignProcess()
      } else {
        this.$refs.formData && this.$refs.formData.resetFields()
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await xxx({ id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          xxx: res.data.xxx || ''
        })
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate()
        })
      } finally {
        loading.close()
      }
    },
    handleSubmit() {
      this.$confirm('请问您是否需要报名参加此次活动?', '提示', {
        confirmButtonText: '确定参加',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if ((this.activeStep === 2) && !this.infoData.signCode) return this.$message.error('请支付保证金')
        if (!this.multipleSelection.length) return this.$message.error('请选择商品')
        if (this.activeStep === 1) {
          const tempArray = []
          let limitFlag = false
          this.multipleSelection.forEach((element) => {
            const item = {}
            item.productId = element.productId
            if (element.number) {
              if (element.number > element.stockNumber) {
                this.$message.warning('商品限量不能大于库存数')
                limitFlag = true
              } else {
                item.number = parseInt(element.number)
              }
            }
            tempArray.push(item)
          })
          if (limitFlag) return false
          const loading = this.$loading({ text: '提交中，请稍候……' })
          try {
            if (this.formData.ifBond) {
              const res = await activitySave({
                activityId: this.formData.activityId,
                signType: this.formData.signType,
                bondMoney: this.formData.bondMoney,
                products: tempArray
              })
              this.activeStep = 2
              this.payImage = res.data.url
              this.boneTimer = setInterval(this.getResult, 3000)
            } else {
              await activitySave({
                activityId: this.formData.activityId,
                signType: this.formData.signType,
                products: tempArray
              })
              this.activeStep = 3
            }
            loading.close()
            this.$message({ message: `操作成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        }
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消成功'
          })
        })
    },
    // 查询付款结果
    async getResult() {
      const res = await checkPay({
        activityId: this.formData.activityId
      })
      if (res.data.code === 'SUCCESS') {
        this.activeStep = 3
        this.infoData = res.data
        clearInterval(this.boneTimer)
      }
    },

    // async initSignProcess() {
    //   const res = await getActivitySignDetail({ activityId: this.formData.activityId })
    //   if (res.code === '') {
    //     if (res.data) {
    //       this.activeStep = 2
    //     }
    //   }
    // },
    handleBlurNumber(data) {
      const index = this.inputTableData.findIndex((item) => item.productId === data.productId)
      if (index === -1) {
        this.inputTableData.push(data)
      } else {
        this.inputTableData[index].number = data.number
      }
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = { page: 1, pageSize: 10, condition: '1', search: '', classifyId: '', groupId: '' }
      this.getList()
    },
    // 初始化查询所有数据
    async getList() {
      this.listLoading = true
      try {
        const res = await getProducts({
          ...this.listQuery,
          classifyId: Array.isArray(this.listQuery.classifyId) && this.listQuery.classifyId.length ? this.listQuery.classifyId[this.listQuery.classifyId.length - 1] : ''
        })
        res.data.list.forEach((item) => {
          // 处理切换分页输入框内容保留
          if (this.inputTableData.length > 0) {
            const index = this.inputTableData.findIndex((cItem) => cItem.productId === item.productId)
            if (index !== -1) {
              item.number = this.inputTableData[index].number
            }
          }
          // 处理库存
          item.number = item.stockNumber
        })
        this.tableDataList = res.data.list
        this.total = res.data.total
      } finally {
        this.listLoading = false
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.filter-container {
	.filter-item {
		display: inline-block;
		vertical-align: middle;
		margin-bottom: 10px;
	}
}

.small-padding {
	.cell {
		padding-left: 5px;
		padding-right: 5px;
	}
}

.fixed-width {
	.el-button--mini {
		padding: 7px 10px;
	}
}

.activity-dialog {
	::v-deep .el-dialog__body {
		padding: 30px 20px 0;
	}
}
</style>
