<template>
  <div>
    <xy-dialog :is-show.sync="isShow" title="产品套餐" ok-text="保存" @on-ok="submit">
      <Button type="primary" icon="md-add" @click="addList" style="margin-bottom: 10px">新增</Button>

      <xy-table :height="260" :is-page="false" :list="list" :table-item="table">
        <template v-slot:btns>
          <el-table-column label="操作" width="90" header-align="center" align="center">
            <template slot-scope="scope">
              <Button size="small" type="primary" ghost @click="deleteCombo(scope)">删除</Button>
            </template>
          </el-table-column>
        </template>
      </xy-table>
    </xy-dialog>
  </div>
</template>

<script>
import {getCombo,destroyCombo,storeCombo} from '@/api/clubProduct'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      id:'',
      isShow:false,

      list:[],
      table:[
        {
          label:'名称',
          sortable:false,
          minWidth:60,
          customFn:(row)=>{
            return (
              <div>
                <el-input size='small' placeholder="请输入名称" value={row.name} on={{['input']:(e)=>{row.name = e}}}/>
              </div>
            )
          }
        },
        {
          label:'内容',
          sortable:false,
          customFn:(row)=>{
            return (
              <div>
                <el-input size='small' placeholder="请输入内容" value={row.content} on={{['input']:(e)=>{row.content = e}}}/>
              </div>
            )
          }
        }
      ],
    }
  },
  methods: {
    async getCombo(){
      this.list = []
      const res = await getCombo({confinement_products_id:this.id})
      this.list.push(...res)
    },

    addList(){
      this.list.push({
        name:'',
        content:''
      })
    },

    deleteCombo(scope){
      if(scope.row?.id){
        destroyCombo({id:scope.row.id}).then(res => {
          this.getCombo()
        })
      }else{
        this.list.splice(scope.$index,1)
      }
    },
    submit(){
      let promiseAll = []
      this.list.forEach(item => {
        if(!item.id){
          promiseAll.push(storeCombo({
            confinement_products_id:this.id,
            name:item.name,
            content:item.content
          }))
        }
      })
      Promise.all(promiseAll).then(res => {
        Message({
          type:'success',
          message:`新增${res.length}条套餐`
        })
        this.isShow = false
      }).catch(err => {
        console.log(err)
      })
    }
  },
  watch:{
    isShow(newVal){
      if(newVal){
        this.getCombo()
      }else{
        this.id = ''
        this.list = []
      }
    }
  }

}
</script>

<style scoped lang="scss">
</style>
