<!--
 * @Description: create
 * @Version: 1.0
 * @Autor: XuTongZhang
 * @Date: 2020-07-28 16:28:13
 * @LastEditors: XuTongZhang
 * @LastEditTime: 2020-08-17 17:38:04
-->
<template>
<div class="templateManage">
    <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" @qrCode="qrCode"></v-table>
    <v-pager @page="callPage" :total="totalrecords"></v-pager>
    <el-dialog :visible.sync="dialogFormVisible" :before-close="close" width="650px" :close-on-click-modal="false">
        <el-form :model="form" ref="form" label-width="140px" :rules="rule" label-position="left">
            <el-form-item label="关联场景" prop="sceneId">
                <el-select v-if="state !== 2" filterable clearable v-model="form.sceneId" placeholder="请选择关联场景">
                    <el-option v-for="item in downList0" :key="item.id" :label="item.sceneName" :value="item.id"></el-option>
                </el-select>
                <div v-else>{{this.downList0.some(i => i.id === form.sceneId) ? this.downList0.find(i => i.id === form.sceneId).sceneName : ''}}</div>
            </el-form-item>
            <el-form-item :label="form.sceneId === 1||form.sceneId === 4?'邮件主题':'邀约岗位'" prop="templateName">
                <el-autocomplete v-if="state !== 2" v-model.trim="form.templateName" :fetch-suggestions="querySearch" :placeholder="'请输入'+form.sceneId === 1||form.sceneId === 4?'邮件主题':'邀约岗位'" @select="handleSelect" :maxlength="32" show-word-limit></el-autocomplete>
                <div v-else>{{form.templateName}}</div>
            </el-form-item>
            <el-form-item v-if="form.sceneId === 1||form.sceneId === 4" label="邮件内容" prop="templateIntroduce">
              <div v-if="state !== 2">
                <el-input type="textarea" :rows="4" resize="none" placeholder="请输入邮件内容" v-model="form.templateIntroduce" maxlength="1024" show-word-limit></el-input>
                <div v-html="form.sceneId === 1 ? prompt1.replace(/\n/g,'<br/>') : prompt2.replace(/\n/g,'<br/>')"></div>
              </div>
                <div v-else>{{form.templateIntroduce}}</div>
            </el-form-item>
            <el-form-item v-if="form.sceneId == 1||form.sceneId == 3" label="关联岗位" prop="processId">
                <el-select v-if="state !== 2" filterable clearable v-model="form.processId" placeholder="请选择关联岗位">
                    <el-option v-for="item in downList1" :key="item.id" :label="item.processName" :value="item.id"></el-option>
                </el-select>
                <div v-else>{{this.downList1.some(i => i.id === form.processId) ? this.downList1.find(i => i.id === form.processId).processName : ''}}</div>
            </el-form-item>
            <el-form-item v-if="form.sceneId == 2||form.sceneId == 3" label="关联表单" prop="formId">
                <el-select v-if="state !== 2" filterable clearable v-model="form.formId" placeholder="请选择关联表单">
                    <el-option v-for="item in downList2" :key="item.id" :label="item.formName" :value="item.id"></el-option>
                </el-select>
                <div v-else>{{this.downList2.some(i => i.id === form.formId) ? this.downList2.find(i => i.id === form.formId).formName : ''}}</div>
            </el-form-item>
            <el-form-item label="" label-width="0">
              <el-link type="primary" @click="help">使用帮助</el-link>
            </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="determine">确 定</el-button>
        </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" width="650px" :before-close="closeDia" :close-on-click-modal="false">
        <el-form :model="codeForm" ref="codeForm" label-width="200px" :rules="rules" label-position="left">
            <el-form-item label="二维码名称" prop="qrcodeName">
                <el-input v-model="codeForm.qrcodeName" placeholder="请输入二维码名称" autocomplete="off" maxlength="32" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="二维码有效期" prop="time">
                <el-date-picker v-model="codeForm.time" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="二维码状态" prop="status">
                <el-radio-group v-model="codeForm.status">
                    <el-radio :label="0">启用中</el-radio>
                    <el-radio :label="1">禁用中</el-radio>
                </el-radio-group>
            </el-form-item>
            <div class="flex">
                <el-button @click="createQrCoed">{{codeForm.qrcodePath ? '修改二维码' : '生成二维码'}}</el-button>
            </div>
            <el-image class="img" :src="codeForm.qrcodePath ? $img + codeForm.qrcodePath : ''" :preview-src-list="[$img + codeForm.qrcodePath]">
            </el-image>
            <div class="flex">
                <el-button @click="downLoad">下载</el-button>
            </div>
        </el-form>
    </el-dialog>
</div>
</template>

<script>
export default {
  data () {
    let validator = (rule, value, callback) => {
      console.log(rule, value, callback)
      if (!value) {
        return callback(new Error('请输入邀约岗位!'))
      } else if (this.restaurants.map(item => item.value).filter(item => item !== this.form.name).includes(value)) {
        return callback(new Error('该名称已被使用!'))
      } else {
        callback()
      }
    }
    return {
      tableList: [],
      page: 1,
      totalrecords: 0,
      dialogVisible: false,
      dialogFormVisible: false,
      state: 0,
      form: {},
      url: '',
      codeForm: {},
      pickList: [],
      downList0: [],
      downList1: [],
      downList2: [],
      restaurants: [],
      prompt1: `示例：
    简历已通过初步筛选，邀请您参加视频初试环节，请注意：
    1. 二维码扫描只可使用一次，有效期自2020年9月8日-9月9日24点止，请使用手机确保周围环境安静的前提下开始。
    2. 请确保网络环境畅通，在录制面试视频时不要接打电话和网络语音。
    3. 每个问题有一分钟的时间进行回答。
    谢谢！`,
      prompt2: `示例：
    感谢您的参与！
    工作人员将通过电话或邮件与您联系后续相关安排，敬请留意！`,
      rule: {
        templateName: [{
          required: true,
          validator,
          trigger: 'change'
        }],
        sceneId: [{
          required: true,
          message: '请选择关联场景',
          trigger: 'blur'
        }],
        processId: [{
          required: true,
          message: '请选择关联岗位',
          trigger: 'blur'
        }],
        formId: [{
          required: true,
          message: '请选择关联表单',
          trigger: 'blur'
        }],
        templateIntroduce: [{
          required: true,
          message: '请输入模板内容',
          trigger: 'blur'
        }]
      },
      rules: {
        qrcodeName: [{
          required: true,
          message: '请输入二维码名称',
          trigger: 'blur'
        }],
        time: [{
          required: true,
          message: '请输入时间区间',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          message: '请选择二维码状态',
          trigger: 'blur'
        }]
      },
      list: [],
      btn: [{
        name: '添加',
        type: 'success',
        method: 'add'
      }],
      table: {
        column: [{
          label: '序号',
          props: 'serialNumber'
        },
        {
          label: '邀约岗位',
          props: 'templateName'
        },
        {
          label: '关联场景',
          props: 'sceneName'
        },
        {
          label: '关联岗位',
          props: 'processName'
        },
        {
          label: '关联表单',
          props: 'formName'
        }
        ],
        width: 400,
        handle: [{
          title: '查看',
          method: 'details',
          type: 'info'
        },
        {
          title: '修改',
          method: 'editor',
          type: 'warning'
        },
        {
          title: '删除',
          method: 'del',
          type: 'danger'
        },
        {
          title: '二维码',
          method: 'qrCode',
          type: 'info',
          props: 'type',
          key: false
        }
        ]
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created () {
    this.queryDownList()
  },
  methods: {
    querySearch (queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    queryData (form = {}) {
      let page = this.page
      let reqdata = form
      this.$api
        .post('/template/queryTemplateList', {
          reqdata,
          page
        })
        .then((res) => {
          this.totalrecords = res.totalrecords
          this.tableList = res.list.map((item, index) => {
            item.sceneName = this.downList0.some(i => i.id === item.sceneId) ? this.downList0.find(i => i.id === item.sceneId).sceneName : ''
            item.processName = this.downList1.some(i => i.id === item.processId) ? this.downList1.find(i => i.id === item.processId).processName : ''
            item.formName = this.downList2.some(i => i.id === item.formId) ? this.downList2.find(i => i.id === item.formId).formName : ''
            item.type = !(item.sceneId !== 1 && item.sceneId !== 4)
            item.serialNumber = (this.page - 1) * 10 + index + 1
            return item
          })
          this.restaurants = res.list.map(item => ({ value: item.templateName }))
        })
    },
    queryDownList () {
      let reqdata = {}
      let num = 0
      let urlArray = ['/scene/querySceneList', '/process/queryProcessList', '/form/queryFormList']
      urlArray.forEach((item, index) => {
        this.$api
          .post(item, {
            reqdata,
            rows: 50
          })
          .then((res) => {
            num++
            this['downList' + index] = res.list
            console.log(this['downList' + index])
            num === 3 && this.queryData()
          })
      })
    },
    add () {
      this.open()
      this.form = {}
      this.state = 0
    },
    getDetails (row) {
      let reqdata = {
        id: row.id
      }
      this.$api
        .post('/template/queryTemplateDetail', {
          reqdata
        })
        .then((res) => {
          this.open()
          this.form = res.object
          this.form.sceneId = this.form.sceneId || null
          this.form.processId = this.form.processId || null
          this.form.formId = this.form.formId || null
          this.form.name = res.object.templateName
        })
    },
    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('/template/deleteTemplate', {
            reqdata
          })
          .then((res) => {
            this.queryData()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    determine () {
      let a
      this.$refs['form'].validate((valid) => {
        a = valid
      })
      if (!a) return
      let url = this.state
        ? '/template/updateTemplate'
        : '/template/saveTemplate'
      let { id, templateName, sceneId, processId, formId, templateIntroduce, companyId } = this.form
      let reqdata
      switch (sceneId) {
        case 1:
          reqdata = { id, templateName, sceneId, companyId, templateIntroduce, processId }
          break
        case 2:
          reqdata = { id, templateName, sceneId, companyId, formId }
          break
        case 3:
          reqdata = { id, templateName, sceneId, companyId, processId, formId }
          break
        case 4:
          reqdata = { id, templateName, sceneId, companyId, templateIntroduce }
          break
        default:
          reqdata = {}
          break
      }
      this.$api
        .post(url, {
          reqdata
        })
        .then((res) => {
          this.close()
          this.queryData()
        })
    },
    qrCode (row) {
      console.log(row)
      this.codeForm.templateId = row.id
      this.openDia()
      this.$api
        .post('/qrCode/checkQrCode', {
          reqdata: {
            templateId: row.id
          }
        })
        .then((res) => {
          this.$api
            .post('/qrCode/queryQrCodeDetail', {
              reqdata: {
                templateId: row.id
              }
            })
            .then((res) => {
              this.codeForm = res.object
              this.$set(this.codeForm, 'time', [res.object.startTime, res.object.endTime])
            })
        })
    },
    createQrCoed () {
      let a
      this.$refs['codeForm'].validate((valid) => {
        a = valid
      })
      if (!a) return
      let {
        templateId,
        time,
        qrcodeName,
        id,
        status
      } = this.codeForm
      let url = this.codeForm.qrcodePath ? '/qrCode/updateQrCodeInfo' : '/qrCode/createQrCodeByTemplate'
      this.$api
        .post(url, {
          reqdata: {
            status,
            qrcodeName,
            templateId,
            id: id,
            startTime: new Date(time[0]).valueOf(),
            endTime: new Date(time[1]).valueOf()
          }
        })
        .then((res) => {
          this.$api
            .post('/qrCode/queryQrCodeDetail', {
              reqdata: {
                templateId
              }
            })
            .then((res) => {
              this.codeForm = res.object
              this.$set(this.codeForm, 'time', [res.object.startTime, res.object.endTime])
            })
        })
    },
    downLoad () {
      this.codeForm.qrcodePath ? window.open(this.$img + this.codeForm.qrcodePath) : this.$message({
        message: '暂无二维码',
        type: 'error'
      })
    },
    help () {
      this.$alert(`
      <h4>面试成功通知：</h4><br/>
    感谢您的参与！<br/><br/>

    工作人员将通过电话或邮件与您联系后续相关安排，敬请留意！<br/><br/>


      <h4>邀约面试-“邀约岗位”一栏文字     （对应邮件主题）</h4><br/>
   收到您投递的简历，请完成视频初试<br/><br/>

    <h4>邀约面试-“邮件内容”一栏文字。  （对应邮件正文）</h4><br/>
      简历已通过初步筛选，邀请您参加视频初试环节，请注意：<br/><br/>

    1. 二维码扫描只可使用一次，有效期自2020年9月8日-9月9日24点止，请使用手机确保周围环境安静的前提下开始。<br/><br/>

    2. 请确保网络环境畅通，在录制面试视频时不要接打电话和网络语音。<br/><br/>

    3. 每个问题有一分钟的时间进行回答。<br/><br/>

    谢谢！
      `, '使用帮助', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        callback: action => {
        }
      })
    },
    handleSelect (val) {
      console.log(val)
    },
    open () {
      this.dialogFormVisible = true
    },
    close () {
      this.dialogFormVisible = false
      this.$nextTick(() => {
        this.form = {}
      })
    },
    openDia () {
      this.dialogVisible = true
    },
    closeDia () {
      this.dialogVisible = false
      this.$nextTick(() => {
        this.codeForm = {}
      })
    },
    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()
        }
      }
    }
    //     'form.sceneId' (val) {
    //       if (!this.form.id) {
    //         val === 1 && (this.form.templateIntroduce = `
    // 示例：

    // 简历已通过初步筛选，邀请您参加视频初试环节，请注意：

    // 1. 二维码扫描只可使用一次，有效期自2020年9月8日-9月9日24点止，请使用手机确保周围环境安静的前提下开始。

    // 2. 请确保网络环境畅通，在录制面试视频时不要接打电话和网络语音。

    // 3. 每个问题有一分钟的时间进行回答。

    // 谢谢！
    //       `)
    //         val === 4 && (this.form.templateIntroduce = `
    // 示例：

    // 感谢您的参与！

    // 工作人员将通过电话或邮件与您联系后续相关安排，敬请留意！
    //       `)
    //       }
    //     }
  }
}
</script>

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

.flex {
    display: flex;
    justify-content: center;
}

.img {
    width: 350px;
    height: 350px;
    margin-top: 30px;
    margin-left: 150px;
    margin-bottom: 10px;
}

</style>
<style lang="scss">
.templateManage {
  .el-message-box {
    width: 500px!important;
  }
}

</style>
