<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="deleteItem(scope)">删除</Button>
            </template>
          </el-table-column>
        </template>
      </xy-table>
    </xy-dialog>
  </div>
</template>

<script>
import {storeMerchantItems,getMerchantItems,destroyMerchantItems} from '@/api/confinementClub'
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 getMerchantItems(){
      this.list = []
      const res = await getMerchantItems({confinement_services_id:this.id})
      this.list.push(...res)
    },

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

    submit(){
      let promiseAll = []
      this.list.forEach(item => {
        if(!item.id){
          promiseAll.push(storeMerchantItems({
            confinement_services_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)
      })
    },

    deleteItem(scope){
      if(scope.row?.id){
        destroyMerchantItems({id:scope.row.id}).then(res => {
          Message({
            type:'success',
            message:'删除成功'
          })
          this.getMerchantItems()
        })
      }else{
        this.list.splice(scope.$index,1)
      }
    }
  },
  watch:{
    isShow(newVal){
      if(newVal){
        this.getMerchantItems()
      }else{
        this.id = ''
        this.list = []
      }
    }
  }

}
</script>

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