<template>
  <div id="device-management">
    <div class="device-management-body" v-loading.fullscreen.lock="fullscreenLoading">
      <div v-show="addVisible" class="order-management-body" style="margin-top:0">
        <!-- 全部 -->
        <div class="device-management_bottom" style="margin-top:0;padding:60px 20px;">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="主图" prop="imageTitles">
              <el-upload class="avatar-uploader" :headers="{token}" :action="uploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <div>
                  <img v-if="ruleForm.imageTitles" :src="ruleForm.imageTitles" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input v-model="ruleForm.description"></el-input>
            </el-form-item>
            <el-form-item label="富文本" prop='content'>
                <editor-bar ref="editorOne" v-model="ruleForm.content" @change="change"></editor-bar>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="viewData = !viewData">预 览</el-button>
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="asyncsubmit">确 定</el-button>
          </div>
          <div class="view" v-if="viewData">
            <div v-html="this.ruleForm.content"></div>
          </div>
        </div>
      </div>
      <div v-show="!addVisible" class="order-management-body">
        <div class="order-management-inner" style="height:120px">
          <div class="base-info">
            <el-button icon="el-icon-plus" type="primary" style="float: right;" @click="showadd" color='red'>新增</el-button>
          </div>
        </div>
        <!-- 全部 -->
        <div class="device-management_bottom">
          <div class="order-management-table">
            <el-table ref="order_table" class='e-table' :data="cameras" style="width: 100%">
              <el-table-column  label="序号" type="index" width="50" align="center">
                  <template slot-scope="scope">
                      <span>{{(currentPage - 1) * pagesize + scope.$index + 1}}</span>
                  </template>
              </el-table-column>
              <el-table-column prop="title" label="标题">
              </el-table-column>
              <!-- <el-table-column prop="description" label="描述">
              </el-table-column> -->
              <el-table-column width="300" prop="createTime" label="上传时间">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- <el-button type="text" @click="showDialog(scope.row)" class="edit_btn">编辑</el-button> -->
                  <el-button type="text" @click="setDel(scope.row)" class="delete_btn">修改</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="order-management-pagination">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pagesize" layout="total, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>
<script>
let tempForm = {
  title: '',
  description: '',
  content: '',
  imageTitles: '',
}
// import EditorBar from './EditorBar'
import EditorBar from './EditorBar5'
export default {
  data () {
    return {
      expands: [],
      accept: '.ipa, .apk',
      md5: null,
      complete: 0,
      completeshow: false,
      expandedArr: [],
      cameras: [],
      currentPage: 1,
      key_input: '',
      fullscreenLoading: false,
      searchKey: '',
      total: 0,
      uploadUrl: this.$server + '/article/uploadImage',
      token: sessionStorage.getItem('token'),
      // expressNum_input: "",
      searchDate: [],
      searchOrderNumber: '',
      searchPhone: '',
      searchExpressNum: '',
      hasClickSearch: false,
      tabIndex: 0,
      addVisible: false,
      ruleForm: tempForm,
      isClear: false,
      viewData:false,
      detail:"",
      rules: {
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' }
        ],
        description: [
          { required: false, message: '请输入新闻描述', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入新闻内容', trigger: 'blur' }
        ],
        imageTitles: [
          { required: true, message: '请选择主图', trigger: 'blur' }
        ],
      },
      cameraInfo: {
        wifi: '',
        type: '',
        address: '',
        initPoint: '',
        orderNum: ''
      },

      formLabelWidth: '30%',
      value2: true,
      currentChildName: '',
      currentDeviceId: '',
      currentBalance: '',
      pagesize: 10,
      clients: [],
      restaurants: []
    }
  },
  components: {
    EditorBar,
  },
  watch: {
    currentPage () {
      this._getCameraData()
    }
  },
  methods: {
    change(val){
      this.ruleForm.content = val
      console.log(val)
    },
    appTypeChange (val) {
      const list = {
        'Android': '.apk',
        'IOS': '.ipa'
      }
      this.accept = list[val] || '.ipa, .apk'
    },
    async getAgenetList () {
      let res = await this.$http.post('/manager/app/agenetList', {})
      let restaurants = []
      if (res.code === 0) {
        restaurants = res.data.map(ele => {
          return {value: ele}
        })
      }
      this.restaurants = restaurants
    },
    async setDel (row) {
        let {data} = await this.$http.post('/article/detail', {id:row.id})
        this.ruleForm = {
          ...data,
        }
        // this.$refs.editorOne.setHtml(this.ruleForm.content)
        this.addVisible = true
    },
    async _getCameraData () {
      
      this.fullscreenLoading = true
      if (!Number(this.currentPage)) this.currentPage = 1
      let res = await this.$http.post('/article/list', {})
      this.fullscreenLoading = false
      if (res.code === 0) {
        let temp = res.data.list
        this.cameras = temp
        this.total = res.data.total ? res.data.total : 0
      }
    },
    async chenkMd5 (value, callback) {
      console.log('value', value == 123456)
      if (value == this.md5) {
        callback()
      } else {
        callback(new Error('MD5错误!请重新输入'))
      }
      return true
    },
    uploadFile (file, fileList) {
      // this.ruleForm.fileList = fileList
      console.log('file, fileList)', file, fileList)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`只能选择一个文件上传`)
    },
    handleCurrentChange (val) {
      this.currentPage = val
    },
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isLt2M
    },
    removeDomain () {
      console.log()
      this.$refs['ruleForm'].validate('md5')
    },
    async savaCase(){
      let res = await this.$http.post('/article/save', {
        ...this.ruleForm,
      })
      this.fullscreenLoading = false
      if (res.code === 0) {
        this.$alert('上传成功', '添加成功', {
          confirmButtonText: '确定'
        })
        this.ruleForm = tempForm
        this.getAgenetList()
        this._getCameraData()
        this.cancel()
      } else {
        this.$alert(res.msg, '操作失败', {
          confirmButtonText: '确定'
        })
      }
    },
    async asyncsubmit () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
        // this.addVisible = true
          this.savaCase()
        } else {
          return false
        }
      })
      // this.$refs['ruleForm'].validate((valid) => {
      //   if (valid) {
      //   // this.addVisible = true
      //     this._editCompany()
      //   } else {
      //     return false
      //   }
      // })
    },
    cancel () {
      this.ruleForm = tempForm
      this.$refs['ruleForm'].resetFields()
      this.md5 = null
      this.addVisible = false
    },
    view (){
        console.log('view',this.ruleForm)
    },
    async _editCompany () {
      let {
        fileServerType,
        agent,
        appType,
        md5,
        name
      } = this.ruleForm

      this.fullscreenLoading = true
      let res = await this.$http.post('/manager/app/save', {
        fileServerType,
        agent,
        appType,
        md5,
        name
      })
      this.fullscreenLoading = false
      if (res.code === 0) {
        this.$alert('上传成功', '添加成功', {
          confirmButtonText: '确定'
        })
        this.getAgenetList()
        this._getCameraData()
        this.cancel()
      } else {
        this.$alert(res.msg, '操作失败', {
          confirmButtonText: '确定'
        })
      }
    },
    handleSelect (row) {
      this.$refs.ruleForm.validateField('agent')
    },
    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)
      }
    },
    showadd () {
      this.ruleForm = tempForm
      console.log('中山横栏港',this.ruleForm , tempForm)
      this.$refs.editorOne.intnt()
      this.addVisible = true
    },
    fileRemove () {
      this.ruleForm.fileList = []
      this.ruleForm.md5 = ''
      this.md5 = null
    },
    handleChange (file) {
      let fileType = file.type,
        isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件不能超过10M，请重新上传')
        return false
      }
      if (file.name !== 'version.json') {
        this.$message.error('请上传文件名称为version.json')
        return false
      }
      this.ruleForm.jsonFile = [file]
    },
    async uploadSectionFile (params) {
      const file = params.file,
        fileType = file.type,
        isImage = fileType.indexOf('image') != -1,
        isLt1G = file.size / 1024 / 1024 / 1024 < 1
      console.log('isLt1G', fileType, params)
      // 这里常规检验，看项目需求而定
      // if (!isImage) {
      //   this.$message.error("只能上传图片格式png、jpg、gif!");
      //   return;
      // }
      if (!isLt1G) {
        this.fileRemove()
        this.$message.error('上传文件过大，请重新上传')
        return
      }
      // 根据后台需求数据格式
      const form = new FormData()
      // 文件对象
      form.append('file', file)
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      console.log('isLt1G', form, file)
      this.completeshow = true
      let res = await this.$http({
        url: '/manager/app/upload',
        method: 'post',
        data: form,
        processData: false,
        contentType: false,
        onUploadProgress: (progressEvent) => {
          this.complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0
          console.log('上传 ' + this.complete)
        }
      })
      this.completeshow = false

      this.complete = 0
      if (res.code === 0) {
        this.ruleForm.fileList = [file]
        this.ruleForm.name = file.name
        this.md5 = res.data || '0'
      }
    },
    handleAvatarSuccess (res, file) {
      console.log('image',res, file)
      this.ruleForm.imageTitles = res.msg
    },
  },
  created () {
    this._getCameraData()
    this.getAgenetList()
  }
}
</script>
<style lang="css" scoped>
@import "./style.css";
</style>
<style type="text/css">
.inline-input{
  width:340px;
}
.device-management_bottom{

}
.el-table__expand-icon > i {
  display: none !important;
}
.dialog-footer{
  text-align: center;
}
.view{
  padding:50px 20px ;
}
.edit_btn span {
  color: #09e1c0;
}

.delete_btn span {
  color: #f56c6c;
}
</style>
