<template>
  <div class="my-right-content border-box">
    <nav-bread :menuData="menuData"></nav-bread>
    <div class="detail-content">
      <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="110px">
        <el-form-item label="版本号" prop="version">
          <limitInput :inputWidth="325" :inputValue.sync="formData.version" :holder="'请输入版本号(如: 1.0.1)'" :getByType="'word'" :maxLength="15"></limitInput>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <limitInput :inputWidth="325" :inputValue.sync="formData.title" :holder="'请输入标题'" :getByType="'word'" :maxLength="15"></limitInput>
        </el-form-item>
        <el-form-item label="版本内容" prop="content">
          <limit-textarea :inputWidth="325" :inputValue.sync="formData.content" :holder="'请输入版本内容'" :getByType="'word'" :maxLength="150"> </limit-textarea>
        </el-form-item>
        <el-form-item label="安装包上传" prop="url" v-if="$route.query.activeTab == 'android'">
          <el-upload class="avatar-uploader" accept=".apk" :show-file-list="false" :http-request="uploadFile" :before-upload="beforeAvatarUpload">
            <el-button size="small" :disabled="upload.disable" type="primary" :loading="upload.loading"><i class="el-icon-upload p-r-6"></i>上 传</el-button><span class="p-l-10">{{ apkName }}</span>
            <div slot="tip" class="el-upload__tip">仅支持 apk 格式</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="强制更新" prop="forcedUpdating">
          <el-select v-model="formData.forcedUpdating" placeholder="请选择">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择">
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelSubmit">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">新增配置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import navBread from '@/components/haoban/nav-bread.vue';
import limitInput from '@/components/haoban/limit-input.vue';
import limitTextarea from '@/components/haoban/limit-textarea.vue';
import { getRequest, putRequest, putUpload } from '@/api/api';
export default {
  name: 'tableList',
  components: {
    navBread,
    limitInput,
    limitTextarea
  },
  data() {
    let validateVersion = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入版本号'));
      } else {
        let reg = /^\d+(\.\d+){2}\w*$/;
        if (!reg.test(value)) {
          callback(new Error('版本号格式不正确!'));
        }
        callback();
      }
    };
    return {
      requestProject: 'gic-bizdict',
      menuData: [
        {
          name: this.$route.query.activeTab == 'android' ? '安卓配置' : 'iOS配置',
          path: `/versionList?activeTab=${this.$route.query.activeTab}&name=${this.$route.query.name}&icon=${this.$route.query.icon}&code=${this.$route.query.code}&tabId=${this.$route.query.tabId}`
        },
        {
          name: this.$route.query.activeTab == 'android' ? '新增安卓配置' : '新增iOS配置',
          path: ''
        }
      ],
      apkName: '',
      formData: {
        version: '',
        title: '',
        content: '',
        forcedUpdating: '0', // 默认否
        status: '2', // 默认否
        url: ''
      },
      rules: {
        version: [
          {
            validator: validateVersion,
            trigger: 'blur'
          }
        ],
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入版本内容',
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: true,
            message: '请上传安装包',
            trigger: 'change'
          }
        ],
        forcedUpdating: [
          {
            required: true,
            message: '请选择强制更新',
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ]
      },
      loading: false,
      upload: {
        loading: false,
        disable: false
      }
    };
  },

  mounted() {
    let that = this;
    that.formData.packageId = that.$route.query.packageId;
    if (that.$route.query.activeTab == 'android') {
      if (that.formData.packageId) {
        that.getData();
      }
    } else {
      if (that.formData.packageId) {
        that.getData();
      }
    }
  },
  methods: {
    /**
     * 路由跳转
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    /**
     * 上传
     *
     */
    handleAvatarSuccess(res, file) {
      console.log(res, file);
    },
    beforeAvatarUpload(file) {
      let that = this;
      that.apkName = file.name;
      const isApk = file.type === 'application/vnd.android.package-archive';
      const isLt1G = file.size / 1024 / 1024 <= 1024;
      if (!isApk) {
        that.$message.error('上传文件必须是 apk 格式!');
      }
      if (!isLt1G) {
        that.$message.error('上传文件大小不能超过 1GB!');
      }
      return isApk && isLt1G;
    },

    async uploadFile(params) {
      let that = this;
      that.upload.loading = true;
      that.upload.disable = true;
      // 通过 FormData 对象上传文件
      var formData = new FormData();
      const fileObj = params.file;
      formData.append('file', fileObj);
      that.putUpload(formData);
    },

    putUpload(formData) {
      let that = this;
      putUpload('/gic-platform-operation/app-package/upload', formData)
        .then(res => {
          let data = res.data;
          that.upload.loading = false;
          that.upload.disable = false;
          if (data.errorCode == 0) {
            that.$message({
              message: '上传成功!',
              type: 'success'
            });
            that.formData.url = '//' + data.result;
          } else {
            that.$message.error(data.message);
          }
        })
        .catch(function(error) {
          that.upload.loading = false;
          that.upload.disable = false;
          that.$message.error(error);
        });
    },

    /**
     * 取消提交
     *
     */
    cancelSubmit() {
      let that = this;
      that
        .$confirm('确认取消？取消后，当前页面信息将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.changeRoute(that.menuData[0].path);
        })
        .catch(() => {});
    },

    /**
     * 提交
     */
    submitForm(formName) {
      let that = this;
      that.$refs[formName].validate(valid => {
        console.log(valid);
        if (valid) {
          that.postAdd();
        } else {
          return false;
        }
      });
    },

    postAdd() {
      let that = this;
      let para = {
        requestProject: that.requestProject,
        title: that.formData.title,
        content: that.formData.content,
        version: that.formData.version,
        forcedUpdating: that.formData.forcedUpdating,
        status: that.formData.status,
        platform: that.$route.query.activeTab == 'android' ? '0' : '1',
        url: that.formData.url,
        packageId: that.formData.packageId
      };
      putRequest('/gic-platform-operation/app-package/save', para)
        .then(res => {
          let data = res.data;
          that.loading = false;
          if (data.errorCode == 0) {
            that.$message({
              message: '保存成功!',
              type: 'success'
            });
            that.changeRoute(that.menuData[0].path);
          } else {
            that.$message.error(data.message);
          }
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error(error);
        });
    },

    /**
     * 获取数据
     *
     */
    getData() {
      let that = this;
      that.loading = true;
      let para = {
        requestProject: that.requestProject,
        packageId: that.formData.packageId
      };
      getRequest(`/gic-platform-operation/app-package/${that.formData.packageId}`, para)
        .then(res => {
          let data = res.data;
          that.loading = false;
          if (data.errorCode == 0) {
            data.result.forcedUpdating = String(data.result.forcedUpdating);
            data.result.status = String(data.result.status);
            that.formData = data.result ? data.result : [];
            if (!!data.result.url) {
              let urlArr = data.result.url.split('/');
              that.apkName = urlArr[urlArr.length - 1];
            }
          } else {
            that.$message.error(data.message);
          }
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error(error);
        });
    }
  }
};
</script>
<style lang="less" scoped>
.detail-content {
  padding: 24px;
}
</style>
