<!--
 * @Description: create
 * @Version: 1.0
 * @Autor: XuTongZhang
 * @Date: 2020-07-28 16:00:46
 * @LastEditors: XuTongZhang
 * @LastEditTime: 2020-08-11 13:00:39
-->
<template>
  <div class="indexPage">
    <v-input :btn="btn" :list="list" @add="add"></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="140px" 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"></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.trim="item.questionName" placeholder="请输入面试问题"></el-input>
              <el-button type="danger" @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>
              {{item.questionName}}
            </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>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button v-if="state!==2" @click="addDomain" type="success">新增</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) {
        callback(new Error('请输入面试问题'))
      } else {
        if (!value.videoIdList || !value.videoIdList.length) {
          callback(new Error('请选择面试视频'))
        }
        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'
        }
      ],
      table: {
        column: [
          {
            label: '编号',
            props: 'id'
          },
          {
            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
        })
    },
    queryDownList () {
      this.$api
        .post('/video/queryVideoList', {
          reqdata: {}
        })
        .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)
        })
    },
    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
      this.form = { processName: '', questionList: [] }
      this.form.questionList.push({ key: 1, questionName: '' })
      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.$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;
  }
  .is-active {
    color: #000;
    font-size: 16px;
  }
}
</style>
