<template>
  <div>
    <el-card shadow="never">
      <div class="width-percentage-60" v-if="info.type === 0">
        <el-form ref="form" :model="form" label-width="150px">
          <el-form-item label="企业/部门">
            <el-select v-model="form.id" placeholder="请选择">
              <el-option v-for="item in zNodes" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备接入数量">
            <el-input v-model="form.number"></el-input>
          </el-form-item>
          <el-form-item label="设备接入授权时间">
            <el-col :span="11">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.endTime" value-format="timestamp"
                format="yyyy 年 MM 月 dd 日" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="授权文件">
            <el-upload action="" class="upload-demo" ref="upload" :on-change="handleChange" :auto-upload="false"
              :limit="1">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" style="background: #FA8E00; border: none;">确认</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="width-percentage-60" v-else>
        <el-form ref="form" :model="form" label-width="150px">
          <el-form-item label="设备接入数量">
            <el-input v-model="form.number" disabled></el-input>
          </el-form-item>
          <el-form-item label="设备接入授权时间">
            <el-col :span="11">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.endTime" disabled value-format="timestamp"
                format="yyyy 年 MM 月 dd 日" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="授权文件">
            <el-upload action="" class="upload-demo" ref="upload" :on-change="handleChange" :auto-upload="false"
              :limit="1"> 点击上传
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitOne">确认</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import moment from "moment";
import { httpGet, httpPost, setCode } from "../api";
import { ztreeToElementTree } from "../utils";

export default {
  inject: ['reload'],
  name: "systemConfiguration",
  data() {
    return {
      fileList: [],
      info: { type: '' },
      zNodes: [],
      form: {
        number: '',
        id: '',
        endTime: '',
        key: ''
      }
    }
  },
  mounted() {
    let info = JSON.parse(localStorage.getItem('info'))
    this.info = info
    this.getEnterprise()
  },
  methods: {
    getEnterprise() {
      httpGet("", this.$api.getEnterprise).then((res) => {
        res.data.list.map((li) => {
          if (li.id == this.info.enterpriseId) {
            let quota = JSON.parse(li.quota)
            if (quota) {
              this.form.number = quota.quota
              this.form.id = li.id
              this.form.endTime = quota.deadline
            }
          }
          li.pid = li.parentId;
          li.label = li.name
          li.value = li.id
        });
        let zNodes = []; let arr = []
        zNodes = ztreeToElementTree(res.data.list, {});
        if (zNodes.length > 0) {
          if (zNodes[0].children) {
            zNodes[0].children.map(li => {
              let obj = {
                name: li.name,
                id: li.id,
                label: li.name,
                value: li.id,
                parentId: li.parentId
              }
              arr.push(obj)
            })
            this.zNodes = arr
          }
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /*读取授权文件*/
    handleChange(file) {
      let _this = this
      let reader = new FileReader();   //先new 一个读文件的对象 FileReader
      if (typeof FileReader === "undefined") {  //用来判断你的浏览器是否支持 FileReader
        this.$message({
          type: "info",
          message: "您的浏览器不支持文件读取。"
        });
        return;
      }
      //  reader.readAsText(file.raw, "gb2312");  //读.txt文件
      reader.readAsArrayBuffer(file.raw); //读任意文件
      reader.onload = function (e) {
        var ints = new Uint8Array(e.target.result); //要使用读取的内容，所以将读取内容转化成Uint8Array
        // ints = ints.slice(0, 5000); //截取一段读取的内容
        let snippets = new TextDecoder('gb2312').decode(ints); //二进制缓存区内容转化成中文（即也就是读取到的内容）
        _this.form.key = snippets
      };
    },
    onSubmit() {
      let q = {
        "quota": this.form.number,
        "deadline": this.form.endTime
      }
      let code = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0DLoa5uX9MjFQJkwvsTb92xkJnwffrdcjKnuFcYN3z4GrGYt0voO22zl3ncNOCzsXZmL6iOK6ukjolajqnpKB/ipXI0/17nZbmY4zturM49EkVt4qw0BvFR7bN/qo7By2Z9dpHOswDEDrJZk+mmD3MCX+ZK5zuhDFVYjDvX9oTZEBdTY5qrgVp2p3fOQCOccGR8ael8lQ+uwewlEMJoJ+NwtF6YPm/SEkVlcnD04J84i7RSXHLoXCV549E8Qv0rDfgcAZhWJfDFmdpuUr42N7TwXl2QI7hNXjqdGbmZjjeZ5MYVWIhDAUGPXB3wlJhYjem7wfjJyeKQ8Zi8vhTtkkQIDAQAB'

      let data = {
        key: setCode(code, JSON.stringify(q)),
        id: this.form.id
      }
      httpPost(data, this.$api.editLincense).then(res => {
        if (res.success) {
          this.$message.success('设置成功')
          this.reload()
        } else {
          this.$message.error(`设置失败：${res.message}`)
        }
      })
    },
    onSubmitOne() {
      if (this.form.key == '') {
        this.$message.error("请上传授权文件")
      } else {
        let data = {
          key: this.form.key,
          id: this.form.id
        }
        httpPost(data, this.$api.editLincense).then(res => {
          if (res.success) {
            this.$message.success('设置成功')
            this.reload()
          } else {
            this.$message.error(`设置失败：${res.message}`)
          }
        })
      }
    }
  }
}
</script>

<style scoped></style>
