<template>
  <div class="layout-no-flex img-list-tabs">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button @click="saveInfo" plain :loading="confirmLoading" :priv="isEdit ? `ImagePlayerManage.Edit.${imagePlayerID}` : `ImagePlayerManage.Add`">
        <i class="fa fa-save"></i> 保存</el-button>
      <el-button v-if="isEdit" plain @click.stop="publish" title="发布" :priv="`ImagePlayerManage.Publish.${imagePlayerID}`">
        <i class="fa fa-share-square-o"></i>发布
      </el-button>
      <el-button v-if="isEdit" plain @click.stop="preview()" title="预览" priv="ImagePlayerManage">
        <i class="fa fa-eye"></i> 预览</el-button>
      <span v-if="tmpImagePlayer.isNeedAudit">
        <el-button @click="commitAudit" plain v-if="('published'!=tmpImagePlayer.status)&&('auditing'!=tmpImagePlayer.status)&&('passed'!=tmpImagePlayer.status)&&isEdit"
          :priv="`ImagePlayerManage.CommitAudit.${imagePlayerID}`">
          <i class="fa fa-arrow-up"></i> 提交审核</el-button>
        <el-button @click="auditPassed" plain v-if="('auditing'==tmpImagePlayer.status)" :priv="`ImagePlayerManage.Audit.${imagePlayerID}`">
          <i class="fa fa-arrow-right"></i> 审核通过</el-button>
        <el-button @click="auditNotPass" plain v-if="('auditing'==tmpImagePlayer.status)" :priv="`ImagePlayerManage.Audit.${imagePlayerID}`">
          <i class="fa fa-exclamation-triangle text-danger"></i>审核不通过</el-button>
        <el-button @click="editAgain" plain v-if="(('passed'==tmpImagePlayer.status)||('published'==tmpImagePlayer.status))" :priv="`ImagePlayerManage.CommitAudit.${imagePlayerID}`">
          <i class="fa fa-edit"></i> 重新编辑</el-button>
      </span>
    </el-toolbar>

    <div class="detail-panel">
      <div class="panel-header">
        <div class="title">{{isEdit ? '基本信息' : '新建图片播放器'}}</div>
      </div>
      <el-form :model="tmpImagePlayer" :rules="rules" ref="form" label-position="right" label-width="125px" v-loading="formLoading">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称：" prop="name">
              <el-input style="width:80%" v-model="tmpImagePlayer.name" @blur="setAlias"></el-input>
            </el-form-item>
            <el-form-item ref="code" label="别名：" prop="code">
              <el-input style="width:80%" v-model="tmpImagePlayer.code" :disabled="isEdit"></el-input>
            </el-form-item>
            <el-form-item label="关联栏目：" prop="catalogID">
              <tree-select :value.sync="tmpImagePlayer.catalogID" width="80%" :dim-info="{'enable':true}" @click-change="treeClickChange" :disabled="isEdit">
              </tree-select>
            </el-form-item>
            <el-form-item label="图片来源：" prop="imageSource">
              <el-radio-group v-model="tmpImagePlayer.imageSource" @change="imageSourceChangeHandler">
                <el-radio class="radio" label="upload">手工上传</el-radio>
                <el-radio class="radio" label="auto">自动抓取</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="显示宽度：" prop="width">
              <el-input style="width:70%" v-model="tmpImagePlayer.width"></el-input>
              <span>像素</span>
            </el-form-item>
            <el-form-item label="显示高度：" prop="height">
              <el-input style="width:70%" v-model="tmpImagePlayer.height"></el-input>
              <span>像素</span>
            </el-form-item>
            <el-form-item label="缩放模式：" prop="thumbMode">
              <el-select style="width:70%" v-model="tmpImagePlayer.thumbMode">
                <el-option v-for="item in thumbModeOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最大显示数：" prop="displayCount">
              <el-input style="width:70%" v-model="tmpImagePlayer.displayCount"></el-input>
              <span>张</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" sty>
            <el-form-item label="图片播放器样式：" prop="imagePlayerType">
              <el-select style="width:80%" v-model="tmpImagePlayer.imagePlayerType">
                <el-option v-for="item in imagePlayerTypeOptions" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否逆序显示：" prop="displayDesc">
              <el-select style="width:80%" v-model="tmpImagePlayer.displayDesc" @change="changeDisplayDesc">
                <el-option v-for=" item in displayDescOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <div style="width:90%;height:200px;margin-top:100px;">
              <img :src="'assets/imageplayer/template/'+tmpImagePlayer.imagePlayerType+'/thumbIMG.jpg'" width="100%" height="100%" />
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-tabs v-if="isEdit" v-model="activeName" @tab-click="handleClick" class="imageplayertTabs">
      <el-tab-pane name="imageList" label="图片列表">
        <imagePlayer-images :ID="imagePlayerID" ref="images-child" :tmp-panel="tmpImagePlayer"></imagePlayer-images>
      </el-tab-pane>
      <el-tab-pane v-if="tmpImagePlayer.imageSource==='auto'" name="conditions" label="条件信息">
        <conditions :ID="imagePlayerID" ref="conditions-child" @callback="updateCondtion"></conditions>
      </el-tab-pane>
    </el-tabs>
    <imagePlayerAudit-dialog :show.sync="imagePlayerAuditDialogModal" :ID="imagePlayerID" @callback="refreshCallback"></imagePlayerAudit-dialog>
  </div>
</template>

<script>
import imagePlayerImages from './imagePlayerImages.vue'
import conditions from './conditions.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
import imagePlayerAuditDialog from './imagePlayerAuditDialog.vue'
import util from '@src/common/util.js'
export default {
  components: {
    'imagePlayerAudit-dialog': imagePlayerAuditDialog,
    'tree-select': TreeSelect,
    conditions: conditions,
    'imagePlayer-images': imagePlayerImages
  },
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    let nameLengthEXCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入名称'))
      } else {
        let lengthEx = util.getLengthEx(value, true)
        if (lengthEx > 50) {
          callback(new Error('名称必须小于等于16个汉字或者50个字母'))
        } else {
          callback()
        }
      }
    }
    return {
      imagePlayerID: 0,
      confirmLoading: false,
      isEdit: false,
      imagePlayerAuditDialogModal: false,
      formLoading: false,
      conditionVisible: false,
      activeName: 'imageList',
      tmpImagePlayer: {
        name: '',
        code: '',
        catalogID: 0,
        imageSource: 'upload',
        width: '',
        height: '',
        thumbMode: '2',
        displayCount: '',
        imagePlayerType: 'titleanddigital',
        displayDesc: 'N'
      },
      displayDescChanged: false,
      // 是否逆序显示下拉选项
      displayDescOptions: [{ value: 'Y', label: '是' }, { value: 'N', label: '否' }],
      // 最大显示数下拉选项数据
      thumbModeOptions: [{ value: '1', label: '原图' }, { value: '2', label: '裁剪缩放' }, { value: '3', label: '原比例缩放' }],
      // 缩放模式下拉选项
      imagePlayerTypeOptions: [],
      // 校验规则
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }, { validator: nameLengthEXCheck, trigger: 'blur change' }],
        code: [{ required: true, message: '别名不能为空', trigger: 'blur' }],
        // 在validator方法中写正则表达式
        height: [
          {
            required: true,
            validator: (rule, value, back) => {
              if (!value) {
                back(new Error('显示高度不能为空'))
              }
              if (/^[1-9][0-9]*$/.test(value) === false) {
                back(new Error('必须是正整数'))
              } else {
                back()
              }
            },
            trigger: 'blur'
          }
        ],
        width: [
          {
            required: true,
            validator: (rule, value, back) => {
              if (!value) {
                back(new Error('显示宽度不能为空'))
              }
              if (/^[1-9][0-9]*$/.test(value) === false) {
                back(new Error('必须是正整数'))
              } else {
                back()
              }
            },
            trigger: 'blur'
          }
        ],
        displayCount: [
          {
            required: true,
            validator: (rule, value, back) => {
              if (!value) {
                back(new Error('最大显示数不能为空'))
              }
              if (/^[1-9][0-9]*$/.test(value) === false) {
                back(new Error('必须是正整数'))
              } else {
                back()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  async created() {
    this.isEdit = this.ID !== 'new'
    this.imagePlayerID = this.isEdit ? this.ID : 0
    await this.loadData()
  },
  methods: {
    changeDisplayDesc () {
      this.displayDescChanged = true
    },

    async imageSourceChangeHandler(){
      if (this.isEdit) {
        if (this.tmpImagePlayer.imageSource) {
          try {
            //  await this.$confirm('确认要修改图片来源吗？修改后原有图片列表将会改变！' '提示', {
            //    confirmButtonText: '确定'
            //    cancelButtonText: '取消'
            //   type: 'warning'
            // })
            await this.saveInfo()
          } catch (e) {}
        }
        this.show()
      }
    },
    async publish() {
      if (this.tmpImagePlayer.isNeedAudit) {
        if (this.tmpImagePlayer.status !== 'passed' && this.tmpImagePlayer.status !== 'published') {
          this.$alert('审核通过的图片播放器才能发布', '提示', {
            type: 'warning'
          })
          return
        }
      }
      try {
        await this.$confirm('发布之后将重新生成播放器，您确认要发布吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put(`/ui/imageplayer/${this.imagePlayerID}/imgpublish`)
        util.showResponseMessage(res.data)
      } catch (e) {

      }
    },
    refreshCallback() {
      this.init()
    },
    updateCondtion (val) {
      Object.assign(this.tmpImagePlayer, {'conditions': val})
    },
    setAlias() {
      if (!this.isEdit) {
        if (!this.tmpImagePlayer.code) {
          Vue.set(this.tmpImagePlayer, 'code', window.util.getSpell(this.tmpImagePlayer.name, true))
        }
      }
    },

    async loadData() {
      this.formLoading = true
      try {
        let imagePlayerType = await axios.get('/ui/imageplayer/getimageplayertype')
        this.imagePlayerTypeOptions = imagePlayerType.data.data
        await this.init()
      } catch (e) {}
      this.formLoading = false
    },

    treeClickChange(val) {
      this.tmpImagePlayer.catalogname = val.name
    },

    async init() {
      if (!this.imagePlayerID || this.imagePlayerID === 'new'){
        this.$refs.form.resetFields()
        this.$nextTick(_ => {
          this.$refs.form.clearValidate()
        })
        return
      }
      let initImagePlayer = await axios.get('/ui/imageplayer/initimageplayer', {
        params: {
          ID: this.imagePlayerID
        }
      })

      this.tmpImagePlayer = initImagePlayer.data.data
      if (!initImagePlayer.data.data.thumbMode) {
        Vue.set(this.tmpImagePlayer, 'thumbMode', '')
      } else {
        this.tmpImagePlayer.thumbMode = initImagePlayer.data.data.thumbMode + ''
      }
      if (!initImagePlayer.data.data.displayDesc) {
        Vue.set(this.tmpImagePlayer, 'displayDesc', 'N')
      }
      this.$nextTick(_ => {
        this.$refs.form.clearValidate()
      })
    },
    goBack() {
      this.$router.back()
    },
    async show() {
      this.conditionVisible = this.tmpImagePlayer.imageSource === 'auto'
      await this.$nextTick()
      this.activeName = 'imageList'
      this.$refs['images-child'].init()
    },
    handleClick(val) {
      this.activeName = val.name
      let _this = this
      if (val.name === 'conditions') {
        _this.$refs['conditions-child'].init()
        return
      }
      if (val.name === 'imageList') {
        _this.$refs['images-child'].init()
      }
    },
    // 提交审核
    async commitAudit() {
      if (!this.isEdit) {
        this.$alert('请先选择一个图片播放器', '提示', { type: 'info' })
        return
      }
      try {
        await this.$confirm('确定要提交审核申请吗？', '提交确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let commitAudit = await axios.put(`/ui/imageplayer/${this.imagePlayerID}/commitaudit`)
        util.showResponseMessage(commitAudit.data)
        if (commitAudit.data.status === 1) {
          this.init()
        }
      } catch (e) {

      }
    },
    // 审核通过
    async auditPassed() {
      if (!this.isEdit) {
        this.$alert('请先选择一个图片播放器', '提示', { type: 'info' })
        return
      }
      let obj = {
        status: 'passed'
      }
      let audit = await axios.put(`/ui/imageplayer/${this.imagePlayerID}/audit`, obj)
      util.showResponseMessage(audit.data)
      if (audit.data.status === 1) {
        this.init()
      }
    },
    // 审核不通过
    async auditNotPass() {
      if (!this.isEdit) {
        this.$alert('请先选择一个图片播放器', '提示', { type: 'info' })
        return
      }
      this.imagePlayerAuditDialogModal = true
    },
    // 重新编辑
    async editAgain() {
      if (!this.isEdit) {
        this.$alert('请先选择一个图片播放器', '提示', { type: 'info' })
        return
      }
      let obj = {
        status: 'editagain'
      }
      let audit = await axios.put(`/ui/imageplayer/${this.imagePlayerID}/audit`, obj)
      util.showResponseMessage(audit.data)
      if (audit.data.status === 1) {
        this.init()
      }
    },
    checkStatus() {
      if (
        this.tmpImagePlayer.status === 'auditing' ||
        this.tmpImagePlayer.status === 'passed' ||
        this.tmpImagePlayer.status === 'published'
      ) {
        this.$alert('已发布、正在审核、审核通过状态的图片播放器不能编辑', '提示', {
          type: 'warning'
        })
        return false
      } else {
        return true
      }
    },
    async saveInfo() {
      try {
        this.confirmLoading = true
        await util.validateForm(this.$refs['form'])
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
        return
      }
      if (this.tmpImagePlayer.isNeedAudit) {
        if (!this.checkStatus()) {
          this.confirmLoading = false
          return
        }
      }
      if (this.isEdit) {
        let res = await axios.put(`/ui/imageplayer/${this.tmpImagePlayer.ID}`, this.tmpImagePlayer)
        util.showResponseMessage(res.data)
        this.confirmLoading = false
        if (this.displayDescChanged && res.data.status === 1) {
          // 刷新图片列表
          this.$refs['images-child'].init()
          this.displayDescChanged = false
        }
      } else {
        let res = await axios.post('/ui/imageplayer', this.tmpImagePlayer)
        util.showResponseMessage(res.data)
        this.confirmLoading = false
        if (res.data.status === 1) {
          await this.$nextTick()
          await util.updatePriv()
          this.imagePlayerID = this.tmpImagePlayer.ID = res.data.ID
          this.$router.replace(this.$route.path.replace('imageplayer/new', `imageplayer/${this.imagePlayerID}`))
          this.isEdit = true
          if (this.tmpImagePlayer.imageSource === 'auto'){
            this.conditionVisible = true
          }
          this.init()
        }
      }
    },

    preview() {
      window.open(`preview.html?&ID=${this.isEdit ? this.imagePlayerID : 0}&type=ImagePlayer`)
    }
  }
}
</script>

<style scoped>
</style>
