<template>
  <div class="obpm-sofetware-list">
    <div class="obpm-title">
      <div class="d-inline-block">
        <i class="el-icon-folder title-icon"></i>
        <div class="title-name d-inline-block ml-2">{{$t("basicInfo.title")}}</div>
      </div>
      <div class="bar d-inline-block float-right">
        <el-button type="primary" size="small" @click="oveorview" v-if="params.type==0">{{$t("btns.overview")}}</el-button>
        <el-button type="primary" size="small" @click="btnSave('params')">{{$t("btns.save")}}</el-button>
        <el-button size="small" @click="goBack">{{$t("btns.exit")}}</el-button>
      </div>
    </div>
    <div class="mt-3">
      <el-form :model="params" ref="params" :rules="rules" label-position="top" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('basicInfo.name')" prop="name" class="padding0Label">
              <el-input v-model="params.name" :placeholder="$t('placeholder.name')" size="small" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8"  :offset="4">
            <el-form-item :label="$t('basicInfo.datasource')" class="padding0Label">
              <el-input v-model="params.datasourceName" readonly size="small" clearable></el-input>
              <el-button size="small" @click="openDataSourceDialog">{{$t('btns.select_datasource')}}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('basicInfo.ordernumber')" class="padding0Label">
               <el-input-number v-model="params.orderNo" :min="0" :max="10000000" :label="$t('label.description_font')" size="small" :precision="0" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('basicInfo.description')" prop="description" class="padding0Label">
              <el-input v-model="params.description" type="textarea" :placeholder="$t('placeholder.description')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('basicInfo.state')" class="padding0Label">
              <el-switch v-model="params.activated"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-dialog width="80%" :title="$t('report.datasourcename')" :visible.sync="outerVisible" top='8vh' :destroy-on-close='true'>
        <DataSourceList :nowDataSourceName="params.datasourceName" :type='datasourceType' @checkDataSourceOk='onRowClick' @closeDatasource="closeDatasource" @cleanDatasource="cleanDatasource"></DataSourceList>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { newApplication, updateApplication, getApplications, oveorview } from "@/service/CommonApi.js";
import DataSourceList from "@/components/AdvancedTool/DataSourceList.vue";
import { nameCheck } from "@/utils/utils.js";

export default {
  name: "baseicinformation",
  components:{
    DataSourceList
  },
  data(){
    
    return{
      params: {
        id: "",
        name: "",
        description: "",
        type: "",
        activated: true,
        orderNo: 0,
        datasourceId: "",
        datasourceName: ""
      },
      rules: {
        name: [
          { required: true, message: this.$t('placeholder.software_name'), trigger: 'blur' },
          { validator: nameCheck, trigger: "blur" },
        ],
        description: [
          { required: true, message: this.$t('placeholder.description'), trigger: 'blur' }
        ]
      },
      outerVisible: false,
      data: {},
      datasourceType:'dialog',

    }
  },

  mounted(){
    //判断是否是新建，edit:true为编辑
    if(this.$route.query.edit && this.$route.query.edit!='false'){
      let appId = sessionStorage.getItem("appId");
      let params = {
        ...this.params,
        id: appId,
      }
      this.params = params;
      this.getApplications()
    }else{
      let urlObj = JSON.parse(this.$route.query.params)
      let type = urlObj.type;
      let params = {
        ...this.params,
        type: Number(type),
      }
      this.params = params;
    }
  },

  methods:{
    //关闭数据源弹窗
    closeDatasource(){
      this.outerVisible=false;
    },
    // 清除选中的数据源
    cleanDatasource(){
      this.params.datasourceName = ""
      this.params.datasourceId = ""
      this.outerVisible=false;
    },
    /**
     * 获取软件详细-基本信息
     */
    getApplications(){
      getApplications(this.params, {
        onSucess: response => {
          if (response.data.errcode == 0) {
            let data = response.data.data;
            let params = {
              ...this.params,
              id: data.id,
              name: data.name,
              description: data.description,
              type: data.type,
              activated: data.activated,
              orderNo: data.orderNo,
              datasourceId: data.datasourceId,
              datasourceName: data.datasourceName
            }
            this.params = params;
            // 将数据来源id放到vuex中用作表单判断
            this.$store.commit('setDataSourceId', data.datasourceId)
          }
        }
      });
    },

    /**
     * 返回
     */
    goBack(){
      this.$router.push({path: '/home/softwarelist'});
    },

    /**
     * 生成概览
     */
    oveorview(){
      let params = this.params;
      if(!params.datasourceId){
        this.$message.error(this.$t('placeholder.save_soft_setdbsource'))
        return false
      }
      oveorview(params.id, {
        onSucess: response => {
          let filename='';
          // let type = response.headers["content-type"];
          if(response.headers['content-disposition']){
            filename=decodeURIComponent(
              response.headers['content-disposition'].split("=")[response.headers['content-disposition'].split("=").length-1].replace(/"/g,"")
            );
          }else{
            filename=this.$('placeholder.download');
          }
          const blob = response.data;
          const href = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = href;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          
        }
      });
    },

    /**
     * 保存软件
     */
    btnSave(params){
      if(this.params.id != ""){
        this.$refs[params].validate((valid) => {
          if (valid) {
            updateApplication(this.params, {
              onSucess: response => {
                if (response.data.errcode == 0) {
                  this.$message({
                    message: this.$t('msg.ss'),
                    type: 'success'
                  });
                  // 将数据来源id放到vuex中用作表单判断
                  this.$store.commit('setDataSourceId', this.params.datasourceId)
                }
              }
            });
          } else {
            return false;
          }
        });
      }else{
        this.$refs[params].validate(async (valid) => {
          if (valid) {
            const response = await newApplication(this.params);
            if (response.data.errcode == 0) {
              let params = {
                ...this.params,
                id: response.data.data.id
              };
              this.params = params;
              this.$message.success(this.$t('msg.ss'));
              // 将数据来源id放到vuex中用作表单判断
              this.$store.commit('setDataSourceId', this.params.datasourceId)
            }
          } else {
            return false;
          }
        });
      }
    },

    /**
     * 打开数据源列表对话框
     */
    openDataSourceDialog(){
      let params = this.params;
      if(params.id == ""){
        this.$message({
          message: this.$t('placeholder.save_software'),
          type: 'info'
        });
      }else{
        this.outerVisible = true;
      }
    },
    /**
     * 选中数据源回显
     */
    onRowClick(row){
      let params = {
        ...this.params,
        datasourceId: row.id,
        datasourceName: row.name
      }
      this.params = params;
      this.outerVisible = false;
    },

  }
}
</script>