<template>
  <div class="app-container">
    <el-form size="mini" inline :disabled="isRead">
      <el-form-item label="模块名称：">
        <el-input v-model="form.title" placeholder="请输入模块名称" />
      </el-form-item>
      <el-form-item label="有效时间：">
        <el-date-picker v-model="form.timeList" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button v-if="!isRead" type="primary" icon="el-icon-plus" @click="getPush">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 模块 -->
    <div style="display: flex; flex-wrap: wrap;">
      <el-form class="form" :model="item" :rules="rules" ref="list" v-for="(item, index) in form.list" :key="item.id"
        label-width="auto" :disabled="isRead">
        <el-form-item class="sort" :label="(index + 1).toString()">
          <el-link v-if="!isRead" icon="el-icon-close" :underline="false" @click="getDelete(index)" />
        </el-form-item>
        <el-form-item v-if="'title' in item" label="标题：" prop="title">
          <el-input v-model="item.title" placeholder="请输入内容标题" />
        </el-form-item>
        <el-form-item v-if="'description' in item" label="简介：" prop="description">
          <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="内容：" prop="contentName">
          <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="跳转方式：" prop="forwardType">
          <el-select v-model="item.forwardType" placeholder="请选择跳转方式" @change="forwardTypeChange(item, index)">
            <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="跳转地址：" prop="forwardUrl">
          <el-input v-model="item.forwardUrl" placeholder="请输入跳转地址" />
        </el-form-item>
        <el-form-item v-if="'contentId' in item" label="专区页面：" prop="contentId">
          <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="封面模式：" prop="isCustom">
          <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="图片：" prop="pic">
          <Upload listType="picture-card" :url="item.pic" @upload="upload($event, item)"
            :disabled="isRead || item.isCustom === 1" />
        </el-form-item>
        <el-form-item v-if="'sort' in item" label="排序：" prop="sort">
          <el-input-number v-model="item.sort" />
        </el-form-item>
        <el-form-item v-if="'childList' in item" label="列表：" prop="childList">
          <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="当前状态：" prop="status">
          <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" v-if="!isRead">
          <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" key="selection" reserve-selection />
        <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-column v-if="!isSelection" 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>
      <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,
      // 表单
      form: {
        // 模板列表
        list: []
      },
      // 模板
      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: {},
      // 校验
      rules: {
        title: [{
          required: true, message: '请输入标题', trigger: 'blur'
        }],
        description: [{
          required: true, message: '请输入简介', trigger: 'blur'
        }],
        contentName: [{
          required: true, message: '请选择内容', trigger: 'blur'
        }],
        forwardType: [{
          required: true, message: '请选择跳转方式', trigger: 'change'
        }],
        forwardUrl: [{
          required: true, message: '请输入跳转地址', trigger: 'blur'
        }],
        contentId: [{
          required: true, message: '请选择跳转专区', trigger: 'change'
        }],
        isCustom: [{
          required: true, message: '请选择封面模式', trigger: 'change'
        }],
        pic: [{
          required: true, message: '请上传图片', trigger: 'change'
        }],
        sort: [{
          required: true, message: '请选择排序', trigger: 'change'
        }],
        childList: [{
          required: true, message: '请关联内容', trigger: 'change'
        }],
        status: [{
          required: true, message: '请选择当前状态', trigger: 'change'
        }]
      }
    }
  },
  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.push('contentName', 'module')
            } else if (i === '9') {
              this.module.push('childList')
            } else {
              this.module.push(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) {
          this.form = JSON.parse(JSON.stringify(res.data))
          this.form.list = []
          // 将详情数据遍历
          res.data.list.map((i, index) => {
            let obj = {}

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

            // 只保留组件模板的参数
            for (const key in i) {
              if (this.module.find(j => j === 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.list.push(obj)
          })
        }
      })
    },

    // 新增模块
    getPush() {
      let obj = {}
      this.module.map(i => {
        obj[i] = i === 'childList' ? [] : i === 'module' ? {} : ''
      })
      obj.status = 0
      this.form.list.push(obj)
    },

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

    // 跳转方式
    forwardTypeChange(item, index) {
      this.$refs.list[index].clearValidate()
      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
          this.$refs.dialogTableData.clearSelection()
          if (this.form.list[this.index].childList && this.form.list[this.index].childList.length > 0) {
            this.form.list[this.index].childList.map(i => {
              let row = res.data.records.find(j => j.audioId === i.module.contentId)
              // 有相同数据就回显勾选
              if (row) {
                this.$refs.dialogTableData.toggleRowSelection(row, true)
              }
            })
          }
          this.loading = false
        }
      })
    },

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

    rowKey(row) {
      return row.audioId
    },

    // 选择
    getSelect(row) {
      let e = this.form.list[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 (this.module.find(i => i === 'description')) {
        e.description = row.description
      }
      this.$message.success('选择成功！')
      this.dialogVisible = false
      this.$refs.list[this.index].clearValidate('contentName')
    },

    // 批量选择
    handleSelectionChange(row) {
      if (row.length > 0) {
        row.map(i => {
          if (this.form.list[this.index].childList.findIndex(j => j.module.contentId === i.audioId) === -1) {
            this.form.list[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, index) {
      for (const key in item) {
        if (key !== 'id') {
          item[key] = key === 'childList' ? [] : key === 'module' ? {} : ''
        }
        // 如果有跳转方式 删除附带组件
        if (key === 'forwardType') {
          delete item.contentName
          delete item.forwardUrl
          delete item.contentId
        }
        // 如果有封面模式 删除缓存的内容图片
        if (key === 'isCustom') {
          this.picList[index] = ''
        }
      }
    },

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

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

    // 提交
    getSubmit() {
      let isValid = true
      if (this.$refs.list) {
        this.$refs.list.map(i => i.validate((valid) => {
          if (!valid) {
            isValid = false
            return false
          }
        }))

        if (isValid) {
          // 区分2级新增 还是 3级编辑
          this.$route.query.secondId ? this.form.secondId = this.$route.query.secondId : this.form.threeId = this.$route.query.threeId
          // 删除仅作展示的缓存数据
          for (const index in this.form.list) {
            delete this.form.list[index].contentId
            if ('description' in this.form.list[index]) {
              this.form.list[index].module.description = this.form.list[index].description
              delete this.form.list[index].description
            }
          }
          submitThree(this.form).then(res => {
            if (res.code === 0) {
              this.$message.success('提交成功！')
              this.cancel()
            }
          })
        }
      }else{
        this.$message.error('请添加新增内容')
      }
    },

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

    // 字典翻译
    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>