<!--
 * @Description: create
 * @Version: 1.0
 * @Autor: XuTongZhang
 * @Date: 2020-07-28 16:00:46
 * @LastEditors: XuTongZhang
 * @LastEditTime: 2020-08-11 15:48:51
-->
<template>
<div class="indexPage">
    <v-input :btn="btn" :list="list" @add="add" @addVideo="addVideo"></v-input>
    <v-table :table="table" :tableList="tableList" :sortType="true" :queryData="queryData" @details="details" @editor="editor" @del="del"></v-table>
    <!-- :prop="'questionList.' + index + '.questionName'" -->
    <v-pager @page="callPage" :total="totalrecords"></v-pager>
    <el-dialog :visible.sync="dialogFormVisible" width="660px" :before-close="close" :close-on-click-modal="false">
        <el-form :model="form" ref="form" label-width="120px" label-position="left">
            <el-form-item label="岗位名称" prop="processName" :rules="{
              required: true, message: '请输入岗位名称', trigger: 'blur'
            }">
                <el-input v-model.trim="form.processName" placeholder="请输入岗位名称" v-if="state!=2" autocomplete="off"  maxlength="32" show-word-limit></el-input>
                <div v-else>{{form.processName}}</div>
            </el-form-item>
            <el-form-item v-for="(item, index) in form.questionList" :label="'面试问题' + (index + 1)" :key="item.key" :prop="'questionList.' + index" :rules="{
              required: true, validator: validatePass, trigger: 'change'
            }">
                <div v-if="state!=2">
                    <div class="flex">
                        <el-input v-model="item.questionName" type="textarea" :rows="2" resize="none" placeholder="请输入面试问题" maxlength="128" show-word-limit></el-input>
                        <el-button v-if="index==0" @click="addDomain" type="success">新增</el-button>
                        <el-button type="danger" v-else @click.prevent="index === 0 || removeDomain(item)">删除</el-button>
                    </div>
                    <el-select v-model="item.videoIdList" multiple filterable :disabled="state === 2" default-first-option placeholder="请选择面试视频">
                        <el-option v-for="item in downList" :key="item.key || item.id" :label="item.videoName" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div v-else>
                    <div v-html="item.questionName && item.questionName.replace(/\n/g,'<br/>')">
                    </div>
                    <video width="100%" v-if="item.videoIdList && item.videoIdList.length" :src="downList.some(i => i.id === item.videoIdList[item.active]) ? $img + downList.find(i => i.id === item.videoIdList[item.active]).videoPath : ''" controls></video>
                    <div class="flex">
                        <div v-for="(i, j) in item.videoIdList" :key="i" class="active" @click="updateActive(item, index, j)" :class="item.active === j ? 'is-active' : ''">{{downList.some(k => k.id === i) ? downList.find(k => k.id === i).videoName : '(已删除)'}}</div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="结束视频设置" prop="ending" :rules="{
              required: true, message: '请输入结束语', trigger: 'blur'
            }">
                <div v-if="state!=2">
                    <el-input v-model="form.ending" type="textarea" :rows="2" resize="none" placeholder="请输入结束语" style="padding-bottom: 5px" maxlength="128" show-word-limit></el-input>
                </div>
                <div v-else>
                    <div>
                        {{form.ending}}
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="" prop="endVideoId" :rules="{
              required: true, message: '请选择结束视频', trigger: 'blur'
            }">
                <div v-if="state!=2">
                    <el-select v-model="form.endVideoId" filterable :disabled="state === 2" default-first-option placeholder="请选择结束视频" clearable>
                        <el-option v-for="item in downList" :key="item.key || item.id" :label="item.videoName" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div v-else>
                    <video width="100%" v-if="form.endVideoId" :src="downList.some(i => i.id === form.endVideoId) ? $img + downList.find(i => i.id === form.endVideoId).videoPath : ''" controls></video>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" v-if="state!==2" @click="branch">确 定</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
export default {
  data () {
    let validatePass = function (rule, value, callback) {
      if ((!value.questionName || !value.questionName.length) && (!value.videoIdList || !value.videoIdList.length)) {
        callback(new Error('请输入面试问题或选择面试视频'))
      } else {
        callback()
      }
    }
    return {
      tableList: [],
      dialogFormVisible: false,
      page: 1,
      totalrecords: 0,
      form: {
        questionList: [{
          key: 1
        }]
      },
      state: 0,
      active: 0,
      activeId: '',
      downList: [],
      pickList: [],
      list: [],
      delId: [],
      btn: [{
        name: '添加',
        type: 'success',
        method: 'add'
      },
      {
        name: '添加视频',
        type: 'primary',
        method: 'addVideo'
      }
      ],
      table: {
        column: [{
          label: '序号',
          props: 'serialNumber'
        },
        {
          label: '岗位名称',
          props: 'processName'
        }
        ],
        handle: [{
          title: '查看',
          method: 'details',
          type: 'info'
        },
        {
          title: '编辑',
          method: 'editor',
          type: 'warning'
        },
        {
          title: '删除',
          method: 'del',
          type: 'danger'
        }
        ]
      },
      validatePass
    }
  },
  created () {
    this.queryData()
    this.queryDownList()
  },
  methods: {
    queryData (form = {}) {
      let page = this.page
      let reqdata = form
      this.$api
        .post('/process/queryProcessList', {
          reqdata,
          page
        })
        .then((res) => {
          this.totalrecords = res.totalrecords
          this.tableList = res.list.map((item, index) => {
            item.serialNumber = (this.page - 1) * 10 + index + 1
            return item
          })
        })
    },
    queryDownList () {
      this.$api
        .post('/video/queryVideoList', {
          reqdata: {},
          rows: 50
        })
        .then((res) => {
          this.downList = res.list
        })
    },
    updateActive (item, index, j) {
      console.log(item, index, j)
      // this.form.questionList[index].active = j
      item.active = j
      this.$set(this.form.questionList, index, item)
      console.log(this.form.questionList[index].active)
    },
    add () {
      this.open()
      this.state = 0
    },
    getDetails (row) {
      let reqdata = {
        id: row.id
      }
      this.$api
        .post('/process/queryProcessDetail', {
          reqdata
        })
        .then((res) => {
          this.open()
          this.form = JSON.parse(JSON.stringify(res.object))
          this.form.questionList = this.form.questionList.map(item => {
            item.active = 0
            return item
          })
          console.log(this.form)
        })
    },
    addVideo () {
      this.$router.push({
        name: 'videoManage'
      })
    },
    details (row) {
      this.getDetails(row)
      this.state = 2
    },
    editor (row) {
      this.getDetails(row)
      this.state = 1
    },
    del (row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let reqdata = {
          id: row.id
        }
        this.$api
          .post('/process/deleteProcess', {
            reqdata
          })
          .then((res) => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.queryData()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    branch () {
      if (this.state) {
        this.uploadQuestion()
      } else {
        this.determine()
      }
    },
    uploadQuestion () {
      let a
      this.$refs['form'].validate((valid) => {
        a = valid
      })
      if (!a) return
      let list = this.form.questionList.filter(item => !item.id)
      let b = 0
      list.length
        ? list.forEach(item => {
          let reqdata = item
          reqdata.processId = this.form.id
          this.$api
            .post('/question/saveQuestion', {
              reqdata
            })
            .then((res) => {
              b++
              item.id = res.object.id
              // this.form.questionList[this.form.questionList.length - index - 1].id = res.object.id
              console.log(this.form)
              // console.log(b, num)
              if (b === list.length) {
                this.determine()
              }
            })
        })
        : this.determine()
    },
    determine () {
      let a
      this.$refs['form'].validate((valid) => {
        a = valid
      })
      if (!a) return
      let url = this.state ? '/process/updateProcess' : '/process/saveProcess'
      let reqdata = JSON.parse(JSON.stringify(this.form))
      if (this.state) {
        reqdata.questionList.map(item => {
          item.questionId = item.id
          return item
        })
        // this.delId.forEach(item => {
        //   reqdata.questionList.push({ questionId: item })
        // })
      }
      this.$api
        .post(url, {
          reqdata
        })
        .then((res) => {
          this.close()
          this.queryData()
          this.delId = []
        })
    },
    removeDomain (item) {
      var index = this.form.questionList.indexOf(item)
      if (index !== -1) {
        this.delId.push(this.form.questionList[index].id)
        this.form.questionList.splice(index, 1)
      }
    },
    open () {
      this.dialogFormVisible = true
    },
    close () {
      this.dialogFormVisible = false
      setTimeout(() => {
        this.form = {
          processName: '',
          questionList: []
        }
        this.form.questionList.push({
          key: 1,
          questionName: ''
        })
      }, 200)
      // this.$forceUpdate()
      console.log(this.form)
    },
    addDomain () {
      this.form.questionList.push({
        key: Date.now()
      })
    },
    callPage (val) {
      this.page = val
      this.queryData()
    }
  },
  watch: {
    dialogFormVisible: function (val, oldVla) {
      if (this.state === 2) {
        if (this.$refs['form'] !== undefined) {
          this.$refs['form'].resetFields()
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
    display: flex;
    justify-content: center;
    align-items: center;
}

.flex {
    margin-bottom: 5px;
    display: flex;

    .active {
        cursor: pointer;
        color: rgb(42, 117, 216);
        margin: 5px 10px;
    }

    .is-active {
        color: #000;
        font-size: 16px;
    }
}
</style>
