<template>
  <el-dialog
    @close="closeDialog"
    title="选图清单"
    :close-on-click-modal="false"
    width="90%"
    top="2vh"
    :visible.sync="visible">
    <div>清单名称：{{dataForm.cardName}}</div>
    <br/>
    <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="dataForm">
      <el-form-item prop="seriesName" label="团队组合" class="search-form-item">
        <el-select size="small" v-model="searchForm.seriesId" placeholder="筛选团体组合" :filterable="true" :clearable="true" @change="handleChangeSeries">
          <el-option v-for="series in seriesList" :label="series.seriesName" :value="series.seriesId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="成员名称" prop="personName">
        <el-select size="small" v-model="searchForm.personId" placeholder="筛选爱豆" clearable filterable @change="handleChangePerson">
          <el-option v-for="person in filterPersonList" :label="person.personName" :value="person.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px" v-if="mode === 'edit'">
      <span>批量设置每款张数：</span>
      <el-input v-model="batchNum" min="1" placeholder="请输入批量设置的数量" type="number" size="small" style="width: 200px; margin-right: 5px"></el-input>
      <el-button type="primary" size="small" @click="saveBatchNumSet">保存批量设置</el-button>
    </div>
    <div v-if="mode === 'choose' && selectNum > 0" class="default-btn primary-btn" @click="openAddToGroupBuyDialog">加入团购</div>
    <div>
      <el-radio v-model="mode" label="view">预览模式</el-radio>
      <el-radio v-model="mode" label="edit">编辑图片</el-radio>
      <span style="color: red; font-size: 16px;font-weight: bold">{{stat}}</span>
    </div>
    <div class="card-box" @scroll="backScrollEvent">
      <div class="create-card-lib" v-for="(cardItem, index) in cardLibItemList" :key="index">
        <div :style="(mode === 'choose' && cardItem.isSelected? divLightStyle : {border: '3px solid #fff'})" @click="mode==='choose'? cardItemSelect(cardItem) : (mode==='check'? cardItemCheck(cardItem): '')">
          <el-row :gutter="12">
            <div style="padding: 1px; text-align: center">
              <span>{{cardItem.seriesName}}</span>
              <br/>
              <span>{{cardItem.personName}}</span>
            </div>
            <el-col :span="12">
              <el-card :body-style="{ padding: '0px' }">
                <div style="padding: 3px; text-align: center">
                  <span>正面</span>
                </div>
                <div style="width: 100px;height: auto">
                  <img :src="resourcesUrl + cardItem.thumbnailFront"/>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card :body-style="{ padding: '0px' }">
                <div style="padding: 3px; text-align: center">
                  <span>背面</span>
                </div>
                <div style="width: 100px;height: auto">
                  <img :src="resourcesUrl + cardItem.thumbnailBack"/>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <el-row style="width: 210px; height: 30px; text-align: center ;color: red; font-weight: bold">
          <el-button v-if="mode==='edit' && cardItem.id" type="danger" size="mini" style="margin-right: 5px" @click="deleteCardItem(cardItem, index)">移除</el-button>
        </el-row>
        <el-row style="width: 210px; height: 30px; text-align: center ;color: red; font-weight: bold">
          <span>数量：</span>
          <span v-if="mode==='view'">{{cardItem.cardCount}}</span>
          <el-input type="number" size="mini" style="width: 90px;height: 20px" v-if="mode==='edit'" v-model="cardItem.cardCount"></el-input>
          <el-button v-if="mode==='edit'" type="primary" size="mini" style="display:inline-flex;margin-left: 10px" @click="updateUserPurchaseItem(cardItem)">保存</el-button>
        </el-row>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button class="default-btn" @click="visible = false">{{$t("crud.filter.cancelBtn")}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {

  data () {
    return {
      mode: 'view',
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      visible: false,
      dataForm: {
        seriesId: null,
        seriesName: null,
        shopId: 1
      },
      batchNum: 10,
      cardLibItemList: [],
      dataRule: {
      },
      selectNum: 0,
      divLightStyle: {border: '3px solid red'},
      addToGroupBuyVisible: false,
      groupBuyData: {},
      prodList: [],
      seriesList: [],
      personList: [],
      filterPersonList: [],
      searchForm:{},
      stat: null,
      activeName: '',
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 50 // 每页显示多少条
      },
    }
  },
  created() {

  },
  methods: {
    clickTab(){
      this.handleChangePerson()
    },
    handleChangeSeries(seriesId){
      this.searchForm.personId = null
      this.filterPersonList = []
      this.filterPersonList.push({id: 0, personName: '全部'})
      this.filterPersonList.push(...this.personList.filter(item => item.seriesId === seriesId))
      this.handleChangePerson()
    },
    saveBatchNumSet(){
      if(this.batchNum <= 0){
        this.$message.error("必须是大于0")
      }
      this.cardLibItemList.forEach(item=> item.cardCount = this.batchNum)
      let cardItem = {userPurchaseId: this.dataForm.userPurchaseId, cardCount: this.batchNum}
      this.$http({
        url: this.$http.adornUrl('/card/cardUserPurchaseItem/updateBatch'),
        method: 'post',
        data: this.$http.adornData(cardItem)
      }).then(({data}) => {
        this.$message({
          message: this.$i18n.t('publics.operation'),
          type: 'success',
          duration: 500,
        })
      })
    },
    updateUserPurchaseItem(cardItem){
      this.$http({
        url: this.$http.adornUrl('/card/cardUserPurchaseItem/update'),
        method: 'post',
        data: this.$http.adornData(cardItem)
      }).then(({data}) => {
        this.$message({
          message: this.$i18n.t('publics.operation'),
          type: 'success',
          duration: 500,
        })
      })
    },
    init (cardUserPurchase) {
      this.dataForm.cardName = cardUserPurchase.cardName
      this.dataForm.userPurchaseId = cardUserPurchase.id
      this.visible = true
      this.$nextTick(() => {
        this.getSeriesAndPersonList(this.dataForm.seriesId)
        this.getUserPurchaseStat()
        this.getCardItemList()
      })

    },
    getUserPurchaseStat(){
      this.$http({
        url: this.$http.adornUrl('/card/cardUserPurchase/stat/' + this.dataForm.userPurchaseId),
        method: 'get'
      }).then(({data}) => {
        this.stat = '统计情况：已选' + '团队组合数：' + data.seriesNum + '个， 成员人数：' + data.personNum + '个，图片款数：' + data.cardNum + '款，定制总张数：' + data.cardCount + '张'
      })
    },
    backScrollEvent (e) {
      if (e.srcElement.scrollTop + e.srcElement.clientHeight + 1 > e.srcElement.scrollHeight){
        this.loadMore()
      }
    },
    loadMore () {
      this.page.currentPage = this.page.currentPage + 1
      this.getCardItemList(true)
    },
    handleChangePerson(value){
      this.page.currentPage = 1
      this.getCardItemList()
    },
    getCardItemList(isLoadMore){
      this.$http({
        url: this.$http.adornUrl('/card/cardUserPurchaseItem/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign({
              size: this.page.pageSize,
              current: this.page.currentPage,
              shopId: 1,
              userPurchaseId: this.dataForm.userPurchaseId,
              personId: this.searchForm.personId ===0? null: this.searchForm.personId,
              seriesId: this.searchForm.seriesId === 0? null: this.searchForm.seriesId
            }
          )
        )
      }).then(({data}) => {
        if(isLoadMore === true){
          this.cardLibItemList.push(...data.records)
        }else{
          this.cardLibItemList = data.records
        }
      })
    },
    getSeriesAndPersonList (seriesId) {
      this.$http({
        url: this.$http.adornUrl('/card/cardUserPurchase/seriesPersonList'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign({
              size: 20,
              id: this.dataForm.userPurchaseId
            },
          )
        )
      }).then(({data}) => {
        this.seriesList.push({seriesId: 0, seriesName: '全部'})
        this.seriesList.push(...data.seriesList)
        this.personList.push({id: 0, personName: '全部'})
        this.personList.push(...data.personList)
      })
    },
    deleteCardItem(item, index){
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/card/cardUserPurchaseItem/' + item.id),
          method: 'delete',
        }).then(({ data }) =>{
          if(data){
            this.$delete(this.cardLibItemList, index);
            this.$message.success("删除成功");
            this.getUserPurchaseStat()
          }else{
            this.$message.error("删除失败");
          }
        })
      });
    },
    cardItemSelect(cardItem){
      let idx = this.cardLibItemList.findIndex(item => item.id === cardItem.id)
      if (idx !== -1) {
        if (cardItem.isSelected) {
          cardItem.isSelected = false
          if (this.selectNum !== 0) {
            this.selectNum = this.selectNum - 1
          }
        } else {
          cardItem.isSelected = true
          this.selectNum = this.selectNum + 1
        }
        this.$set(this.cardLibItemList, idx, cardItem)
      }
    },
    cardItemCheck(cardItem){
      this.$http({
        url: this.$http.adornUrl('/card/cardLib/checkCardLibSize'),
        method: 'post',
        data: this.$http.adornData(cardItem)
      }).then(({data}) => {
        this.$message({
          message: '检测正常',
          type: 'success',
          duration: 500,
        })
      })
    },
    openAddToGroupBuyDialog(){
      this.addToGroupBuyVisible = true
      this.getGroupBuyProdList()
    },
    getGroupBuyProdList(){
      this.$http({
        url: this.$http.adornUrl('/prod/prod/getProdPage'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign({
              current: 1,
              size: 200,
              shopId: 1,
              customType: 2
            },
          )
        )
      }).then(({data}) => {
        this.prodList = data.records
      })
    },
    closeDialog(){
      this.dataForm = {}
      this.selectNum = 0
      this.seriesList = []
      this.personList = []
      this.searchForm = {}
      this.mode = 'view'
    },
  }
}
</script>
<style scoped>
  .create-card-lib {
    border: 2px solid pink;
    display: inline-block;
    margin-right: 15px
  }
  .card-box {
    margin-top: 10px;
    width: 100%;
    padding: 10px;
    height: 700px;
    overflow-y: auto; /* 当内容超出时显示垂直滚动条 */
    overflow-x: hidden; /* 隐藏水平滚动条 */
  }
</style>
