<!--
 * @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="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"
      @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="templateName">
          <el-input v-if="state !== 2" v-model="form.templateName" placeholder="请输入模板名称" autocomplete="off"></el-input>
          <div v-else>{{form.templateName}}</div>
        </el-form-item>
        <el-form-item label="模板内容" prop="templateIntroduce">
          <el-input
            v-if="state !== 2"
            type="textarea"
            :rows="4"
            resize="none"
            placeholder="请输入模板内容"
            v-model="form.templateIntroduce"
          ></el-input>
          <div v-else>{{form.templateIntroduce}}</div>
        </el-form-item>
        <el-form-item label="关联场景" prop="sceneId">
          <el-select v-if="state !== 2" 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="关联流程" prop="processId">
          <el-select v-if="state !== 2" 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 label="关联表单" prop="formId">
          <el-select v-if="state !== 2" 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>
      <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"></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 () {
    return {
      tableList: [],
      page: 1,
      totalrecords: 0,
      dialogVisible: false,
      dialogFormVisible: false,
      state: 0,
      form: {},
      url: '',
      codeForm: {},
      pickList: [],
      downList0: [],
      downList1: [],
      downList2: [],
      rule: {
        templateName: [{ 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: 'id'
          },
          {
            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: {
    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 => {
            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.processId && item.sceneId)
            return item
          })
        })
    },
    queryDownList () {
      let reqdata = {}
      let num = 0
      let urlArray = ['/scene/querySceneList', '/process/queryProcessList', '/form/queryFormList']
      urlArray.forEach((item, index) => {
        this.$api
          .post(item, {
            reqdata
          })
          .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
        })
    },
    details (row) {
      this.getDetails(row)
      this.state = 2
    },
    editor (row) {
      this.getDetails(row)
      this.state = 1
    },
    del (row) {
      let reqdata = { id: row.id }
      this.$api
        .post('/template/deleteTemplate', {
          reqdata
        })
        .then((res) => {
          this.queryData()
        })
    },
    determine () {
      let a
      this.$refs['form'].validate((valid) => {
        a = valid
      })
      if (!a) return
      let url = this.state
        ? '/template/updateTemplate'
        : '/template/saveTemplate'
      let reqdata = this.form
      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 } = this.codeForm
      let url = this.codeForm.qrcodePath ? '/qrCode/updateQrCodeInfo' : '/qrCode/createQrCodeByTemplate'
      this.$api
        .post(url, {
          reqdata: {
            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'
      })
    },
    open () {
      this.dialogFormVisible = true
    },
    close () {
      this.dialogFormVisible = false
      this.form = {}
    },
    openDia () {
      this.dialogVisible = true
    },
    closeDia () {
      this.dialogVisible = false
      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()
        }
      }
    }
  }
}
</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>
