<template>
  <div class="app-container">
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="getPush">新增</el-button>
    <!-- 模块 -->
    <div style="display: flex; flex-wrap: wrap;">
      <el-form class="form" v-for="(item, index) in form" :key="item.id" label-width="auto" :disabled="isRead">
        <el-form-item class="sort" :label="(index + 1).toString()">
          <el-link icon="el-icon-close" :underline="false" @click="getDelete(index)" />
        </el-form-item>
        <el-form-item v-if="'title' in item" label="标题：">
          <el-input v-model="item.title" placeholder="请输入内容标题" />
        </el-form-item>
        <el-form-item v-if="'description' in item" label="简介：">
          <el-input v-model="item.description" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }"
            placeholder="请输入简介" />
        </el-form-item>
        <el-form-item v-if="'contentName' in item" label="内容：">
          <el-input v-model="item.contentName" prefix-icon="el-icon-search" placeholder="选择内容"
            @focus="getDialog(item, index, false)" />
        </el-form-item>
        <el-form-item v-if="'forwardType' in item" label="跳转方式：">
          <el-select v-model="item.forwardType" placeholder="请选择跳转方式" @change="forwardTypeChange(item)">
            <el-option v-for="item in forwardTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="'forwardUrl' in item" label="跳转地址：">
          <el-input v-model="item.forwardUrl" placeholder="请输入跳转地址" />
        </el-form-item>
        <el-form-item v-if="'contentId' in item" label="专区页面：">
          <el-select v-model="item.contentId" placeholder="请选择跳转专区" @change="contentIdChange(item)">
            <el-option v-for="item in sceneOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="'isCustom' in item" label="封面模式：">
          <el-select v-model="item.isCustom" placeholder="选择封面模式" @change="isCustomChange(item, index)">
            <el-option v-for="item in coverOptions" :key="item.value" :label="item.label" :value="Number(item.value)" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="'pic' in item" label="图片：">
          <Upload listType="picture-card" :url="item.pic" @upload="upload($event, item)" :disabled="isRead" />
        </el-form-item>
        <el-form-item v-if="'sort' in item" label="排序：">
          <el-input-number v-model="item.sort" />
        </el-form-item>
        <el-form-item v-if="'childList' in item" label="列表：">
          <el-button type="primary" @click="getDialog(item, index, true)">添加内容</el-button>
          <el-table :data="item.childList">
            <el-table-column label="电台名称" prop="contentName" align="center" show-overflow-tooltip />
            <el-table-column label="当前状态" prop="status" align="center" :formatter="statusFormatter" />
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="delete" @click="getRemove(scope.row, index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="当前状态：">
          <el-select v-model="item.status" placeholder="请选择当前状态">
            <el-option v-for="item in disabledOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="info" @click="getEmpty(item, index)">清空</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 提交 返回按钮 -->
    <div class="btn">
      <el-button @click="cancel">取消</el-button>
      <el-button v-if="!isRead" type="primary" @click="getSubmit">确定</el-button>
    </div>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="添加内容" width="1000px">
      <el-form inline size="mini">
        <el-form-item label="音频类型：">
          <el-select v-model="dialogForm.audioType" placeholder="请选择类型" :disabled="disabled">
            <el-option v-for="item in audioOptions" :key="item.value" :label="item.label" :value="Number(item.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源平台：">
          <el-select v-model="dialogForm.platformId" placeholder="请选择平台">
            <el-option v-for="item in platformOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容：">
          <el-input v-model="dialogForm.keyword" placeholder="请输入内容关键词" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getSearch">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="dialogTableData" ref="dialogTableData" :row-key="rowKey" @selection-change="handleSelectionChange"
        v-loading="loading">
        <el-table-column v-if="isSelection" type="selection" align="center" reserve-selection key="selection" />
        <el-table-column v-else label="操作" align="center" key="change">
          <template slot-scope="scope">
            <el-button type="text" @click="getSelect(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="音频ID" prop="audioId" align="center" key="audioId" show-overflow-tooltip />
        <el-table-column label="音频名称" prop="audioName" align="center" key="audioName" show-overflow-tooltip />
        <el-table-column label="音频封面" align="center" key="audioPic" width="100px">
          <template slot-scope="scope">
            <el-image :src="scope.row.audioPic" />
          </template>
        </el-table-column>
        <el-table-column label="音频作者" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>
              {{ scope.row.singerName ? scope.row.singerName : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="专辑名称" prop="songName" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>
              {{ scope.row.songName ? scope.row.songName : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="音频类型" prop="audioType" align="center" key="audioType" :formatter="audioFormatter" />
        <el-table-column label="音频数量" prop="programCount" align="center" key="programCount" />
        <el-table-column label="付费类型" align="center" key="isFree" :formatter="freeFormatter" width="100px" />
        <el-table-column label="当前状态" align="center" key="status" :formatter="statusFormatter" />
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="dialogForm.pageNum" :limit.sync="dialogForm.pageSize"
        @pagination="getList" />
    </el-dialog>
  </div>
</template>

<script>
import { list } from '@/api/operation/scene'
import { detail, moduleList, radioList, submitThree } from '@/api/operation/recommend'
import { coverMixin, audioMixin, platformMixin, isFreeMixin, disabledMixin } from '@/mixin/index'
export default {
  mixins: [coverMixin, audioMixin, platformMixin, isFreeMixin, disabledMixin],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 二级id
      secondId: this.$route.query.secondId,
      // 三级id
      threeId: this.$route.query.threeId,
      // 表单
      form: [],
      // 模板
      module: {},
      // 弹窗
      dialogVisible: false,
      // 弹窗表单
      dialogForm: {
        pageNum: 1,
        pageSize: 10,
        audioType: '',
        platformId: ''
      },
      // 弹窗列表
      dialogTableData: [],
      // 总数据
      total: 0,
      // 禁止操作
      disabled: false,
      // 是否启用多选
      isSelection: true,
      // 弹窗索引
      index: 0,
      // 专区模块
      sceneOptions: [],
      // 跳转方式
      forwardTypeOptions: [{
        value: 0,
        label: 'APP内容跳转广播',
        type: 2
      }, {
        value: 1,
        label: 'APP内容跳转歌曲',
        type: 11
      }, {
        value: 2,
        label: 'APP内容跳转歌单',
        type: 10
      }, {
        value: 3,
        label: 'APP内容跳转专辑',
        type: 8
      }, {
        value: 4,
        label: 'APP内容跳转节目',
        type: 6
      }, {
        value: 7,
        label: 'APP内容跳转专区',
        type: 16
      }, {
        value: 5,
        label: 'H5内链'
      }, {
        value: 6,
        label: 'H5外链'
      }],
      // 只读
      isRead: false,
      // 缓存内容图片
      picList: {}
    }
  },
  watch: {
    'dialogForm.audioType'(val) {
      this.getPlatform({
        audioType: val
      })
    }
  },
  mounted() {
    this.getSceneList()
    this.getModule()
  },
  methods: {
    // 模块 详情
    getModule() {
      let moduleOptions = {
        1: 'title',
        3: 'description',
        4: 'contentName',
        5: 'forwardType',
        6: 'isCustom',
        7: 'pic',
        8: 'sort',
        9: 'childList'
      }
      moduleList(this.$route.query.moduleTypeId).then(res => {
        if (res.code === 0) {
          res.data.elementIds.map(i => {
            if (i === '4') { // 内容 关联 音频数据 存在底层module
              this.module.contentName = ''
              this.module.module = {}
            } else if (i === '9') {
              this.module.childList = []
            } else {
              this.module[moduleOptions[i]] = ''
            }
          })
          if (this.$route.query.threeId) {
            this.getDetail()
            this.isRead = Boolean(this.$route.query.boolean)
          }
        }
      })
    },

    // 详情
    getDetail() {
      detail(this.$route.query.threeId).then(res => {
        if (res.code === 0 && res.data.list.length > 0) {
          // 将详情数据遍历
          res.data.list.map((i, index) => {
            let obj = {}

            // 是否有简介
            if ('description' in this.module) {
              obj.description = i.module.description
            }

            // 只保留组件模板的参数
            for (const key in i) {
              if (this.module.hasOwnProperty(key)) {
                obj[key] = i[key]
                // 跳转方式关联 内容 栏目 地址
                if ([0, 1, 2, 3, 4].includes(i.forwardType)) {
                  obj.contentName = i.contentName
                  obj.module = i.module
                } else if ([5, 6].includes(i.forwardType)) {
                  obj.forwardUrl = i.forwardUrl
                } else if ([7].includes(i.forwardType)) {
                  obj.contentId = i.module.contentId
                  obj.module = i.module
                }

                // 封面模式 关联 图片 缓存内容图片
                if (i.isCustom === 1) {
                  this.picList[index] = i.pic
                }
              }
              obj.status = i.status
            }
            this.form.push(obj)
          })
        }
      })
    },

    // 新增模块
    getPush() {
      this.form.push(this.module)
    },

    // 爱听专区
    getSceneList() {
      list().then(res => {
        if (res.code === 0) {
          res.data.map(i => {
            this.sceneOptions.push({
              value: i.id,
              label: i.name
            })
          })
        }
      })
    },

    // 跳转方式
    forwardTypeChange(item) {
      this.$set(item, 'module', {}),
        [0, 1, 2, 3, 4].includes(item.forwardType) ? [
          this.$set(item, 'contentName', ''),
          delete item.forwardUrl,
          delete item.contentId
        ] : [5, 6].includes(item.forwardType) ? [
          this.$set(item, 'forwardUrl', ''),
          delete item.contentName,
          delete item.contentId
        ] : [
          this.$set(item, 'contentId', ''),
          delete item.contentName,
          delete item.forwardUrl
        ]
    },

    // 封面模式
    isCustomChange(item, index) {
      item.isCustom === 1 ? item.pic = this.picList[index] : item.pic = ''
    },

    // 上传图片
    upload(e, item) {
      item.pic = e.file
    },

    // 专区页面
    contentIdChange(item) {
      item.module = {}
      item.forwardType === 7 ? [
        item.module.contentType = 16,
        item.module.contentId = item.contentId
      ] : ''
    },

    // 弹窗
    getDialog(item, index, boolean) {
      this.dialogVisible = true
      this.index = index
      this.isSelection = boolean
      if ('forwardType' in item) {
        this.dialogForm.audioType = this.forwardTypeOptions.find(i => i.value === item.forwardType).type
        this.disabled = true
      } else {
        this.dialogForm.audioType = this.audioOptions[0].value
      }
      this.getList()
    },

    // 音频列表
    getList() {
      this.loading = true
      radioList(this.dialogForm).then(res => {
        if (res.code === 0) {
          this.dialogTableData = res.data.records
          this.total = res.data.total
          let row = ''
          if (this.form[this.index].childList && this.form[this.index].childList.length > 0) {
            this.form[this.index].childList.map(i => {
              row = res.data.records.find(j => j.audioId === i.module.contentId)
            })
          }
          row ? this.$refs.dialogTableData.toggleRowSelection(row) : this.$refs.dialogTableData.clearSelection();
          this.loading = false
        }
      })
    },

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

    rowKey(row) {
      return row.audioId
    },

    // 选择
    getSelect(row) {
      let e = this.form[this.index]
      e.module = {
        contentId: row.audioId,
        platformId: row.platformId,
        contentType: row.audioType,
        description: row.description
      }
      e.contentName = row.audioName
      e.pic = row.audioPic
      // 封面模式自定义封面会丢失内容封面图片 所以缓存以便改回来使用
      this.picList[this.index] = row.audioPic
      // 是否有简介 若有则将音频的简介赋值进去
      if ('description' in this.module) {
        e.description = row.description
      }
      this.$message.success('选择成功！')
      this.dialogVisible = false
    },

    // 批量选择
    handleSelectionChange(row) {
      this.form[this.index].childList = []
      if (row.length > 0) {
        row.map(i => {
          if (this.form[this.index].childList.findIndex(j => j.module.contentId === i.audioId) === -1) {
            this.form[this.index].childList.push({
              module: {
                contentId: i.audioId,
                platformId: i.platformId,
                contentType: i.audioType,
                description: i.description,
              },
              contentName: i.audioName,
              pic: i.audioPic,
              status: i.status
            })
          }
        })
      }
    },

    // 清空
    getEmpty(item) {
      for (const key in item) {
        if (key !== 'id') {
          item[key] = key === 'childrenList' ? [] : key === 'module' ? {} : ''
        }
      }
    },

    // 提交
    getSubmit() {
      let data = this.secondId ? {
        secondId: this.secondId,
        list: this.form
      } : {
        threeId: this.threeId,
        list: this.form
      }
      // 删除仅作展示的缓存数据
      for (const index in this.form) {
        delete this.form[index].contentId
        this.form[index].module.description = this.form[index].description
        delete this.form[index].description
      }
      submitThree(data).then(res => {
        if (res.code === 0) {
          this.$message.success('提交成功！')
          this.cancel()
        }
      })
    },

    // 返回
    cancel() {
      this.$tab.closeOpenPage("/operation/operationRecommend");
    },

    // 删除模块
    getDelete(index) {
      this.form.splice(index, 1)
    },

    // 删除关联
    getRemove(row, index) {
      let e = this.form[index].childList.findIndex(i => i.contentId === row.contentId)
      this.form[index].childList.splice(e, 1)
    },

    // 字典翻译
    audioFormatter(row) {
      return this.selectDictLabel(this.audioOptions, row.audioType)
    },
    freeFormatter(row) {
      return this.selectDictLabel(this.freeOptions, row.isFree)
    },
    statusFormatter(row) {
      return this.selectDictLabel(this.disabledOptions, row.status)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding-bottom: 100px;
}

.form {
  width: 500px;
  border: 1px solid #dcdfe6;
  box-shadow: 5px 5px 5px 0 #dcdfe6;
  padding: 20px;
  margin-bottom: 20px;
  position: relative;
  margin-right: 20px;

  .sort {
    ::v-deep .el-form-item__label-wrap {
      margin: 0 !important;
    }

    .el-link {
      float: right;
    }
  }
}

.btn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  border-top: 1px solid #dcdfe6;
  box-shadow: 5px 0 10px 0 #dcdfe6;
  line-height: 100px;
  text-align: right;
  padding: 0 20px;
  background: #FFF;
}
</style>