<template>
  <div class="app-container">
    <el-form label-width="auto">
      <!-- 一级标签 -->
      <el-form-item label="一级标签：" style="width: 500px">
        <el-input v-model="form.firstName" placeholder="请输入一级标签" />
      </el-form-item>

      <!-- 二级标签 -->
      <el-form-item label="二级标签：" size="mini">
        <el-tag v-for="item in form.secondTags" :key="item.secondId" closable
          @close="getClose(item.secondId, item.secondName)" style="margin: 0 10px 10px 0">
          {{ item.secondName }}
        </el-tag>
        <el-input v-if="inputVisible" v-model="secondTags" ref="input" @blur="getBlur" style="width: 90px" />
        <el-button v-else icon="el-icon-plus" @click="showInput">添加</el-button>
      </el-form-item>

      <!-- 三级标签 -->
      <el-form-item label="三级标签：" size="mini" style="margin: 0">
        <div style="display:flex; width: 500px">
          <el-select v-if="form.secondTags.length > 0" v-model="type" placeholder="请选择二级标签"
            style="margin-right: 10px;">
            <el-option v-for="(item, index) in form.secondTags" :key="index" :label="item.secondName"
              :value="index" />
          </el-select>
          <el-input v-model="threeTag.threeName" placeholder="请输入三级标签" style="margin-right: 10px;" />
          <el-select v-model="threeTag.propertyId" placeholder="请选择标签属性" style="margin-right: 10px;">
            <el-option v-for="item in lableTypeOptions" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
          <el-button type="primary" icon="el-icon-plus" @click="getInput">添加</el-button>
        </div>
        <div v-if="form.secondTags.length > 0">
          <div v-for="item in form.secondTags" :key="item.secondId">
            <span style="margin: 0 10px 10px 0">{{ item.secondName }}</span>
            <el-tag v-for="i in item.threeTag" :key="i.threeId" closable
              @close="getClose(i.threeId, i.threeName)" style="margin: 0 10px 10px 0">
              {{ i.threeName }} {{ propertyFormatter(i.propertyId )}}
            </el-tag>
          </div>
        </div>
        <div v-else>
          <el-tag v-for="item in form.threeTag" :key="item.threeId" closable
            @close="getClose(item.threeId, item.threeName)" style="margin: 0 10px 10px 0">
            {{ item.threeName }} {{ propertyFormatter(item.propertyId )}}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item size="mini">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="getSubmit">提交</el-button>
      </el-form-item>
      <!-- 列表 -->
      <el-form-item label="频道内容">
        <el-select v-model="tagId" placeholder="请选择已添加的三级标签" style="width: 200px;">
          <el-option v-for="item in threeTagOptions" :key="item.threeId" :label="item.threeName"
            :value="item.threeId" />
        </el-select>
        <el-select v-model="dialogForm.type" disabled style="width: 200px; margin: 0 10px">
          <el-option v-for="item in dict.type.audio_type" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="getDialog">新增内容</el-button>
        <el-table :data="tableData" height="489" lazy>
          <el-table-column label="内容ID" prop="audioId" align="center" />
          <el-table-column label="内容名称" prop="audioName" align="center" />
          <el-table-column label="内容封面" align="center" width="100px">
            <template slot-scope="scope">
              <el-image :src="scope.row.audioPic" />
            </template>
          </el-table-column>
          <el-table-column label="内容属性" prop="audioType" align="center" :formatter="typeFormatter" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="delete" @click="getDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="新增频道内容">
      <el-form inline size="mini" @submit.native.prevent>
        <el-form-item label="内容名称：">
          <el-input v-model="dialogForm.name" placeholder="请输入内容名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="getSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="getRefresh">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table :data="dialogData" height="476" ref="table" :row-key="getRowKey"
        @selection-change="getChange">
        <el-table-column type="selection" align="center" reserve-selection />
        <el-table-column label="内容ID" prop="id" align="center" />
        <el-table-column label="音频名称" prop="audioName" align="center" />
        <el-table-column label="音频封面" align="center" width="100">
          <template slot-scope="scope">
            <el-image :src="scope.row.audioPic" />
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="audioType" align="center" :formatter="typeFormatter" />
        <el-table-column label="节目数量" prop="programCount" align="center" />
        <el-table-column label="付费类型" prop="isFree" align="center" :formatter="freeFormatter" />
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="dialogForm.pageNum"
        :limit.sync="dialogForm.pageSize" @pagination="getPage" />
      <div slot="footer">
        <el-button type="primary" @click="getAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { contentList, findList, detail, edit, createTag, remove, removeChildren } from '@/api/operation/tag'
import { isFreeMixin } from '@/mixin/index'
export default {
  dicts: ['audio_type'],
  mixins: [isFreeMixin],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 弹窗
      dialogVisible: false,
      // 表单
      form: {
        secondTags: []
      },
      // 列表
      tableData: [],
      // 添加内容id数组
      ids: [],
      // 二级标签
      secondTags: '',
      // 控制输入框显示
      inputVisible: false,
      // 三级标签
      type: null,
      threeTag: {
        threeName: '',
        propertyId: ''
      },
      // 选择三级标签
      tagId: '',
      threeTagOptions: [],
      // 弹窗
      dialogForm: {
        type: '',
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      // 弹窗列表
      dialogData: [],

      // 标签属性
      lableTypeOptions: [{
        value: 2,
        label: '广播'
      }, {
        value: 6,
        label: '节目'
      }, {
        value: 8,
        label: '专辑'
      }]
    }
  },
  watch: {
    tagId(val) {
      this.dialogForm.type = this.threeTagOptions.find(i => i.threeId === val).propertyId
      if (val) {
        this.getList()
      }
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.form.firstId = this.$route.query.id
      this.getDetail()
    }
  },
  methods: {
    // 详情
    getDetail() {
      detail(this.form.firstId).then(res => {
        if (res.code === 0) {
          this.form = res.data
          if (res.data.secondTags.length === 0 && res.data.threeTag === null) {
            this.form.threeTag = []
          }
          if (res.data.secondTags.length > 0) {
            this.threeTagOptions = []
            res.data.secondTags.map(i => {
              i.threeTag.map(j => {
                this.threeTagOptions.push(j)
              })
            })
          } else {
            this.threeTagOptions = res.data.threeTag
          }
        }
      })
    },

    // 已选中的频道内容
    getList() {
      findList({
        tagId: this.tagId,
        type: this.dialogForm.type
      }).then(res => {
        if (res.code === 0) {
          this.tableData = res.data
        }
      })
    },

    // 显示输入框
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },

    // 失去焦点保存
    getBlur() {
      if (this.secondTags) {
        if (this.form.secondTags.indexOf(this.secondTags) == -1) {
          this.form.secondTags.push({
            secondName: this.secondTags,
            threeTag: []
          })
          this.form.threeTag = []
        } else {
          this.$message.error('请勿新增相同的标签！')
        }
      }
      this.inputVisible = false
      this.secondTags = ''
    },

    // 删除标签
    getClose(id, name) {
      this.$confirm(`是否删除 ${name} 标签?`, '提示', {
        type: 'warning'
      }).then(() => {
        removeChildren(id).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功！')
            this.getDetail()
          }
        })
      })
    },

    // 添加三级标签
    getInput() {
      if (this.form.secondTags.length > 0 && this.type == null) {
        this.$message.error('请选择二级标签！')
      } else if (!this.threeTag.threeName) {
        this.$message.error('请输入三级标签！')
      } else if (!this.threeTag.propertyId) {
        this.$message.error('请选择标签属性！')
      } else {
        if (this.form.secondTags.length > 0) {
          if (this.form.secondTags[this.type].threeTag.findIndex(i => i.threeName === this.threeTag.threeName && i.propertyId === this.threeTag.propertyId) == -1) {
            this.form.secondTags[this.type].threeTag.push(this.threeTag)
            this.threeTag = {}
          } else {
            this.$message.error('该三级标签已存在！')
          }
        } else {
          if (this.form.threeTag.findIndex(i => i.threeName === this.threeTag.threeName && i.propertyId === this.threeTag.propertyId) == -1) {
            this.form.threeTag.push(this.threeTag)
            this.threeTag = {}
          } else {
            this.$message.error('该三级标签已存在！')
          }
        }
      }
    },

    // 弹窗
    getDialog() {
      if (this.dialogForm.type) {
        this.dialogVisible = true
        this.ids = []
        this.getPage()
      } else {
        this.$message.error('请选择三级标签再新增内容！')
      }
    },

    // 全部内容列表
    getPage() {
      this.loading = true
      contentList(this.dialogForm).then(res => {
        if (res.code === 0) {
          this.dialogData = res.data.records
          this.total = res.data.total
          this.$refs.table.clearSelection()
          this.$nextTick(() => {
            this.tableData.map(i => {
              let row = this.dialogData.find(j => j.id == i.audioId)
              if (row) {
                this.$refs.table.toggleRowSelection(row)
              }
            })
          })
          this.loading = false
        }
      })
    },

    // 取消
    cancel() {
      this.$tab.closeOpenPage("/operation/tag");
    },

    // 提交
    getSubmit() {
      edit(this.form).then(res => {
        if (res.code === 0) {
          this.$message.success('修改成功！')
          this.getDetail()
        }
      })
    },

    // 搜索
    getSearch() {
      this.dialogForm.pageNum = 1
      this.getPage()
    },

    // 重置
    getRefresh() {
      this.dialogForm.name = ''
      this.dialogForm.pageNum = 1
      this.dialogForm.pageSize = 10
      this.getPage()
    },

    getRowKey(row) {
      return row.id
    },
    // 表格多选
    getChange(row) {
      this.ids = []
      if (row.length > 0) {
        row.map(i => {
          if (this.ids.findIndex(j => j === i.id) === -1) {
            this.ids.push(i.id)
          }
        })
      }
    },

    // 添加频道内容
    getAdd() {
      createTag({
        tagId: this.tagId,
        type: this.dialogForm.type,
        ids: this.ids
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('添加成功！')
          this.dialogVisible = false
          this.getList()
        }
      })
    },

    // 删除某个频道内容
    getDelete(id) {
      remove(id).then(res => {
        if (res.code === 0) {
          this.$confirm('是否删除?', '警告', {
            type: 'warning'
          }).then(() => {
            this.$message.success('删除成功！')
            this.getList()
          })
        }
      })
    },


    // 字典翻译
    propertyFormatter(row) {
      return this.selectDictLabel(this.lableTypeOptions, row)
    },
    typeFormatter(row) {
      return this.selectDictLabel(this.lableTypeOptions, row.audioType)
    },
    freeFormatter(row) {
      return this.selectDictLabel(this.freeOptions, row.isFree)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag,
.tagInput,
.tagSelect {
  margin-right: 10px;
}

.tagInput {
  width: 100px;
}

.tagSelect {
  width: 150px;
}
</style>