<template>
  <a-modal :visible="value"
           :mask="false"
           :title="false"
           :footer="false"
           :width="630"
           :bodyStyle="{padding:0}"
           @cancel="handleCancel">

    <div class="bg">
      <img :src="systeminfoImg">
    </div>

    <div v-if="systemInfo">

      <div class="list-wrapper">
        <div v-for="item of configList"
             :key="item.key"
             class="list-item">
          <div>{{item.label}}</div>
          <div v-if="item.customRender">{{item.customRender(systemInfo[item.key],systemInfo)||'-'}}</div>
          <div v-else>{{systemInfo[item.key]||'-'}}</div>
        </div>
        <div class="list-item">
          <div>产品信息</div>
          <div v-if="systemInfo&&systemInfo.productCode&&systemInfo.productName">
            <div>{{systemInfo.productCode || '-'}}</div>
            <div style="padding-top:5px;">{{systemInfo.productName || '-'}}</div>
          </div>
          <div v-else>-</div>
        </div>
        <div class="list-item">
          <div>扩展信息</div>
          <div v-if="systemInfo.applyNodeList"
               class="extend-list">
            <div v-for="t of systemInfo.applyNodeList"
                 :key="t.name">
              {{t.text}}: {{t.value}}
            </div>
          </div>
          <div v-else>-</div>
        </div>
      </div>

      <div class="btns">
        <a-button v-show="!isUpload"
                  type="primary"
                  @click="showUpload">
          更新许可
        </a-button>

        <input type="file"
               ref="file"
               accept=".lic"
               style="display:none;"
               @change="fileChange">
        <a-button v-show="isUpload"
                  :icon="fileData?'file':'upload'"
                  @click="toUpload">
          {{fileData ? fileData.name : '添加许可'}}
        </a-button>
        <a-button v-show="isUpload"
                  type="primary"
                  :loading="uploadLoading"
                  @click="handleOk">
          更新
        </a-button>

        <a-button :loading="deviceLoading"
                  @click="getDeviceInfo">
          获取设备信息
        </a-button>
        <input ref="deviceInfo"
               type="text"
               style="position:absolute;left:3000px;">
      </div>

    </div>
    <div v-else
         style="width:80%;margin:0 auto;">
      <a-skeleton active />
    </div>

  </a-modal>
</template>

<script>
import moment from "moment";
import request from '@/utils/request'
import systeminfoImg from '@/assets/admin/systeminfo.png'

export default {
  name: 'SystemInfoModal',

  props: {
    value: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      systeminfoImg: systeminfoImg,
      configList: [
        { label: '企业识别号', key: 'enterpriseUniqueCode' },
        { label: '企业名称', key: 'enterpriseName' },
        {//1-临时 2-正式 3-永久
          label: '许可类型', key: 'licenseType', customRender(text, record) {
            return text ? (text == '1' ? '临时' : (text == '2' ? '正式' : '永久')) : '';
          }
        },
        {//"有效期时间戳 -1 - 无期限" licenseType =3 时，有效时间显示为  0000-00-00
          label: '许可有效期', key: 'expiresTimeStamp', customRender(text, record) {
            if (!text) return '';
            if (record.licenseType == '3' || text == -1) return '0000-00-00';
            let t = moment(+text).format('YYYY-MM-DD');
            return t.indexOf('Invalid') >= 0 ? '' : t;
          }
        },
        // { label: '编号', key: 'productCode' },
        // { label: '名称', key: 'productName' },
        // {
        //   label: '产品信息', key: 'product', customRender(text, record) {
        //     // if (!record.productName || !record.productCode) return '';
        //     if (!record.productName || !record.productCode) return `名称 record.productName <br>编号 record.productCode`;
        //     return `名称 ${record.productName || ''} <br>编号 ${record.productCode || ''}`;
        //   }
        // },
        // { label: '扩展信息', key: 'applyNodeList' },
        // @ApiModelProperty("企业唯一识别码")  private String enterpriseUniqueCode;
        // @ApiModelProperty("企业名称")  private String enterpriseName;
        // @ApiModelProperty("产品名称")  private String productName;
        // @ApiModelProperty("产品编号")  private String productCode;
        // @ApiModelProperty("产品版本")  private String productVersion;
        // @ApiModelProperty("CPU序列号")  private String cpuSerial;
        // @ApiModelProperty("有效期时间戳 -1 - 无期限")  private Long expiresTimeStamp;
        // @ApiModelProperty("1-临时 2-正式 3-永久")  private String licenseType;
        // @ApiModelProperty("多维度节点控制")  private List<ApplyNodeInfoDTO> applyNodeList;
        // @ApiModelProperty("生成签名时间戳")  private Long signTimeStamp;
        // @ApiModelProperty("true-有效  false-失效")  private boolean invalid;
      ],
      isUpload: false,
      fileData: null,
      systemInfo: null,
      uploadLoading: false,
      deviceLoading: false,
      expiresTimeWarner: null,
    }
  },

  watch: {
    value(val) {
      if (val) {
        this.getSystemInfo();
      }
    }
  },

  created() {
    this.getSystemInfo();
  },

  methods: {

    getSystemInfo() {
      request({
        url: '/api/lic',
        method: 'get',
        params: {},
      }).then(res => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.systemInfo = res.data;
        this.handleExpiresTime();
        // this.systemInfo = {
        //   applyNodeList: null,
        //   cpuSerial: null,
        //   enterpriseName: null,
        //   enterpriseUniqueCode: null,
        //   expiresTimeStamp: null,
        //   invalid: null,
        //   licenseType: null,
        //   productCode: null,
        //   productName: null,
        //   productVersion: null,
        //   signTimeStamp: null,
        // };
      });
    },

    handleExpiresTime() {
      if (this.expiresTimeWarner) clearInterval(this.expiresTimeWarner);
      if (!this.systemInfo || !this.systemInfo.expiresTimeStamp || this.systemInfo.licenseType == '3' || this.systemInfo.expiresTimeStamp == '-1') return;
      let delta = new Date(+this.systemInfo.expiresTimeStamp) - new Date();
      if (delta > 3 * 24 * 3600 * 1000) return;
      let t = moment(+this.systemInfo.expiresTimeStamp).format('YYYY-MM-DD');
      t = t.indexOf('Invalid') >= 0 ? '' : t;
      this.expiresTimeWarner = setInterval(() => {
        this.$warning({
          title: '许可有效期警告',
          content: h => <div style="color:red;">您的系统许可将于{t}过期，请尽快更新!</div>,
        })
      }, 10 * 60 * 1000)
    },

    showUpload() {
      this.isUpload = true;
    },

    toUpload() {
      this.$refs.file.click();
    },

    fileChange(event) {
      console.log(event.target.files)
      this.fileData = event.target.files[0];
    },

    handleOk() {
      const formData = new FormData();
      formData.append('file', this.fileData);
      this.uploadLoading = true;
      request({
        url: '/api/lic',
        method: 'post',
        data: formData,
        // params: {},
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        timeout: 36000000,
      }).then(res => {
        this.uploadLoading = false;
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.getSystemInfo();
        this.$message.success('更新成功！');
        this.isUpload = false;
        this.fileData = null;
      });
    },

    handleCancel() {
      this.isUpload = false;
      this.fileData = null;
      this.systemInfo = null;
      this.$emit('input', false);
    },

    toCopy() {
      //选中input框的内容
      this.$refs.deviceInfo.select();
      // 执行浏览器复制命令
      document.execCommand("Copy");
      this.$message.success('复制成功!');
    },

    getDeviceInfo() {
      this.deviceLoading = true;
      request({
        url: '/api/lic/device',
        method: 'get',
      }).then(res => {
        this.deviceLoading = false;
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$refs.deviceInfo.value = res.data;
        this.$info({
          content: (<div>
            设备信息: <span style="padding-right:10px;">{res.data}</span>
            <a-icon type="copy" style="color:#2b80ff;" vOn:click={this.toCopy} />
          </div>),
          onOk() { },
        });
      });
    },

  }

}
</script>

<style scoped>
.bg {
  padding: 40px 0 5px;
  background-image: linear-gradient(0deg, #f0f2f5 0%, #ffffff 31%);
  text-align: center;
}
.list-wrapper {
}
.list-item {
  overflow: hidden;
  font-size: 14px;
  line-height: 20px;
}
.list-item > div {
  float: left;
  padding-top: 20px;
}
.list-item > div:first-child {
  width: 230px;
  text-align: right;
  color: #333333;
  font-weight: 600;
}
.list-item > div:last-child {
  width: 340px;
  text-indent: 20px;
  color: #797979;
}
.btns {
  text-align: center;
  padding: 20px 0;
}
.btns button {
  margin-left: 20px;
}
.btns button:first-child {
  margin-left: 0px;
}
.extend-list > div {
  max-height: 150px;
  overflow-y: auto;
  text-align: left;
}
</style>
