<template>
  <div class="app-container">
    <el-form class="form" :model="form" ref="form" :rules="rules" label-width="100px" :disabled="disabled">
      <el-form-item label="播客名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入播客名称" show-word-limit />
      </el-form-item>
      <el-form-item label="主播名称：" prop="podcasterIds">
        <el-select v-model="form.podcasterIds" multiple filterable remote reserve-keyword
          placeholder="请输入主播名称" :remote-method="getSelect" no-data-text="请新增主播">
          <el-option v-for="item in anchorOptions" :key="item.value" :value="item.value"
            :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="播客分类：" prop="categoryIds">
        <el-select v-model="form.categoryIds" multiple placeholder="请选择播客分类">
          <el-option v-for="item in classifyOptions" :key="item.value" :value="item.value.toString()"
            :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="播客介绍：" prop="description">
        <el-input v-model="form.description" type="textarea" :autosize="{ minRows: 5, maxRows: 10}"
          maxlength="300" show-word-limit placeholder=" 请输入播客介绍" />
      </el-form-item>
      <el-form-item label="资源平台：" prop="platformId">
        <el-select v-model="form.platformId" placeholder="请选择资源平台" :disabled="disabledPlatformId(form.platformId)">
          <el-option v-for="item in platformOptions" :key="item.value" :value="item.value"
            :label="item.label" :disabled="disabledJoinType(item.joinType)" />
        </el-select>
      </el-form-item>
      <el-form-item label="付费类型：" prop="charging">
        <el-select v-model="form.charging" placeholder="请选择付费类型">
          <el-option v-for="item in payTypeOptions" :key="item.value" :value="item.value"
            :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.charging !== 1" label="原价：" prop="price">
        <el-input-number v-model="form.price" placeholder="请输入原价" :min="1" :precision="2" :controls="false" />
      </el-form-item>
      <el-form-item v-if="form.charging !== 1" label="折扣价：" prop="discountedPrice">
        <el-input-number v-model="form.discountedPrice" placeholder="请输入折扣价" :min="1" :precision="2"
          :controls="false" />
      </el-form-item>
      <el-form-item label="播客封面" prop="thumb">
        <Upload listType="picture-card" :url="form.thumb" @upload="upload" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="关联节目：" prop="adminPodCastProgramDetailResp">
        <el-button type="primary" @click="getDialog">关联节目</el-button>
        <el-button @click="getDelete" :disabled="ids.length > 0 ? false : true">解除关联</el-button>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-table :data="form.adminPodCastProgramDetailResp" height="497" @selection-change="handleSelect">
          <el-table-column type="selection" align="center" />
          <el-table-column label="ID" prop="id" align="center" show-overflow-tooltip />
          <el-table-column label="节目名称" prop="name" align="center" show-overflow-tooltip />
          <el-table-column label="资源平台" prop="platformId" align="center" :formatter="platformFormatter" />
          <el-table-column label="当前状态" prop="status" align="center" :formatter="statusFormatter" />
        </el-table>
      </el-form-item>
    </el-form>
    <div class="form-btn">
      <el-button @click="cancel">取消</el-button>
      <el-button v-if="!disabled" type="primary" @click="getSubmit">确定</el-button>
    </div>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="关联节目" width="1200px">
      <el-form inline size="mini" style="width: 100%">
        <el-form-item label="节目ID：">
          <el-input v-model="dialogForm.id" placeholder="请输入节目ID" clearable />
        </el-form-item>
        <el-form-item label="节目名称：">
          <el-input v-model="dialogForm.name" placeholder="请输入节目名称" clearable />
        </el-form-item>
        <el-form-item label="付费类型：">
          <el-select v-model="dialogForm.isFree" placeholder="请选择付费类型" clearable>
            <el-option v-for="item in freeOptions" :key="item.value" :value="item.value"
              :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源平台：">
          <el-select v-model="dialogForm.platformId" placeholder="请选择资源平台">
            <el-option v-for="item in platformOptions.filter(i => !i.joinType.includes('1'))" :key="item.value" :value="item.value"
              :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="getRefresh">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="dialogTableData" v-loading="loading">
        <el-table-column label="ID" prop="id" align="center" />
        <el-table-column label="节目名称" prop="name" align="center" show-overflow-tooltip />
        <el-table-column label="资源平台" prop="platformId" align="center" :formatter="platformFormatter" />
        <el-table-column label="付费类型" prop="isFree" align="center" :formatter="freeFormatter" />
        <el-table-column label="当前状态" prop="status" align="center" :formatter="statusFormatter" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="getChecked(scope.row)"
              :disabled="form.adminPodCastProgramDetailResp.findIndex(i => i.id === scope.row.id) === -1 ? false : true">
              选择
            </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 { classifyMixin, platformMixin, payTypeMixin, onOrOffMixin, isFreeMixin } from '@/mixin/index'
import { selectAnchor } from '@/api/music/anchor'
import { detail, submit, relieve, checkList } from '@/api/music/blog'
export default {
  mixins: [classifyMixin, platformMixin, payTypeMixin, onOrOffMixin, isFreeMixin],
  data() {
    // 判断原价是否大于折扣价
    var checkPrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入原价'))
      } else if (value.toString().length > 10) {
        callback(new Error('字符长度不超过10个'))
      } else if (this.form.discountedPrice) {
        value > this.form.discountedPrice ? callback() : callback(new Error('原价必须大于折扣价'))
      }
    }
    // 判断折扣价是否小于原价
    var checkDiscount = (rule, value, callback) => {
      if (value) {
        if (value.toString().length > 10) {
          callback(new Error('字符长度不超过10个'))
        } else if (this.form.price) {
          value < this.form.price ? callback() : callback(new Error('折扣价必须小于原价'))
        }
      }
    }
    return {
      // 遮罩层
      loading: false,
      // 表单
      form: {
        adminPodCastProgramDetailResp: [],
        podcastProgramIds: [],
        categoryIds: [],
        status: 1
      },
      // 主播
      anchorOptions: [],
      // 弹窗
      dialogVisible: false,
      // 弹窗表单
      dialogForm: {
        pageNum: 1,
        pageSize: 10,
        status: 1,
        platformId: null
      },
      // 总数据
      total: 0,
      // 弹窗列表
      dialogTableData: [],
      // 只读
      disabled: false,
      // 校验
      rules: {
        name: [{
          required: true, message: '请输入播客专辑名称', trigger: 'blur'
        }],
        podcasterIds: [{
          required: true, message: '请输入主播名称', trigger: 'blur'
        }],
        categoryIds: [{
          required: true, message: '请选择播客分类', trigger: 'change'
        }],
        platformId: [{
          required: true, message: '请选择资源平台', trigger: 'change'
        }],
        charging: [{
          required: true, message: '请选择付费类型', trigger: 'change'
        }],
        price: [{
          required: true, validator: checkPrice, trigger: 'blur'
        }],
        discountedPrice: [{
          validator: checkDiscount, trigger: 'blur'
        }],
        thumb: [{
          required: true, message: '请上传播客封面', trigger: 'change'
        }],
        adminPodCastProgramDetailResp: [{
          required: true, message: '请关联节目', trigger: 'change'
        }]
      },
      // 解除关联
      ids: [],
      // 是否已选
      disabledChecked: false
    }
  },
  mounted() {
    // 获取资源平台
    this.getPlatform({
      audioType: 8
    })
    // 分类
    this.getClassify(8)
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      this.disabled = Boolean(this.$route.query.disabled)
      this.getDetail()
    }
  },
  methods: {
    // 详情
    getDetail() {
      detail(this.form.id).then(res => {
        if (res.code === 0) {
          this.form = res.data
          this.anchorOptions = []
          res.data.adminPrdCasterResp.map(i => {
            this.anchorOptions.push({
              value: i.podcasterId,
              label: i.podcasterName
            })
          })
          this.form.podcasterIds = res.data.podcasterIds.split(',')
        }
      })
    },

    // 查询主播
    getSelect(e) {
      if (e) {
        setTimeout(() => {
          this.anchorOptions = []
          selectAnchor(e).then(res => {
            if (res.code === 0) {
              res.data.map(i => {
                this.anchorOptions.push({
                  value: i.id,
                  label: i.nickname
                })
              })
            }
          }, 500)
        })
      }
    },

    // 上传
    upload(e) {
      this.form.thumb = e.file
    },

    // 弹窗
    getDialog() {
      this.dialogVisible = true
      this.dialogForm.platformId = this.platformOptions.filter(i => !i.joinType.includes('1'))[0].value
      this.getList()
    },

    // 节目列表
    getList() {
      this.loading = true
      checkList(this.dialogForm).then(res => {
        if (res.code === 0) {
          this.dialogTableData = res.data.records
          this.total = res.data.total
          this.loading = false
        }
      })
    },

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

    // 重置
    getRefresh() {
      this.dialogForm = {
        pageNum: 1,
        pageSize: 10,
        status: 1,
        platformId: this.platformOptions[0].value
      }
      this.getList()
    },

    // 选择
    getChecked(row) {
      this.form.adminPodCastProgramDetailResp.push(row)
      this.$message.success('选择成功！')
    },

    // 解除关联
    getDelete() {
      if (this.form.id) {
        relieve({
          id: this.form.id,
          podcastProgramIds: this.ids
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('解除成功！')
            this.getDetail()
          }
        })
      } else {
        this.ids.map(i => {
          this.form.adminPodCastProgramDetailResp.map((j, index) => {
            if (j.id === i) {
              this.form.adminPodCastProgramDetailResp.splice(index, 1)
              this.$message.success('解除成功！')
            }
          })
        })
      }
    },

    // 确定
    getSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let title = this.form.id ? '编辑成功！' : '新增成功！'
          this.form.podcastProgramIds = []
          this.form.adminPodCastProgramDetailResp.map(i => {
            this.form.podcastProgramIds.push(i.id)
          })
          submit(this.form).then(res => {
            if (res.code === 0) {
              this.$message.success(`${title}`)
              if (this.form.id) {
                delete this.form.adminPodCastProgramDetailResp
                this.getDetail()
              } else {
                this.cancel()
              }
            }
          })
        } else {
          return false
        }
      })
    },

    // 多选
    handleSelect(e) {
      this.ids = []
      e.map(i => {
        this.ids.push(i.id)
      })
    },

    // 取消
    cancel() {
      this.$tab.closeOpenPage('/music/blog')
    },

    // 字典翻译
    platformFormatter(row) {
      return this.selectDictLabel(this.platformOptions, row.platformId)
    },
    statusFormatter(row) {
      return this.selectDictLabel(this.onOrOffOptions, row.status)
    },
    freeFormatter(row) {
      return this.selectDictLabel(this.freeOptions, row.isFree)
    }
  }
}
</script>

<style lang="scss" scoped>

.form {
  .el-form-item {
    width: 500px;
  }
}
</style>