<template>
  <el-container>
    <div v-if="category!='org'" key="dialog2" class="repository-import">
      <el-dialog
        title="导入模型"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal=false
        :before-close="handleClose">
        <div style="height: 250px;" v-loading="loading" element-loading-text="请稍等">
          <div style="text-align: center;padding-top: 10px;">
            <awsui-button style="width: 130px;" class="button-general-color" type="primary" @click="openFileSelect('file')">本地文件上传</awsui-button>
          </div>
          <div class="text-second-color" style="font-size: 12px;margin-top: 10px;margin-left: 15px;">请上传export文件，支持多个文件同时导入</div>
          <div style="height: 180px;margin: 10px 10px;overflow:auto;">
            <PALUpload ref="palUpload" style="width: 100%;"
               class="upload-demo"
               appId="com.actionsoft.apps.coe.pal"
               repositoryName="tmp"
               groupValue="_import"
               fileValue="Normal"
               :multiple=true
               :on-preview="handlePreview"
               :on-success="handleSuccess"
               :on-remove="handleRemove"
               :on-error="handleError"
               :before-remove="beforeRemove"
               :before-upload="beforeUpload"
               :on-exceed="handleExceed"
               :on-progress="handleProgress"
               accept=".export"
               :file-list="fileList">
              <div style="display: none;">
                <awsui-button name="selectFileButton" style="width: 130px;" class="button-general-color" type="primary">本地文件上传</awsui-button>
              </div>
            </PALUpload>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <awsui-button class="button-general-color" :disabled="buttonDisabled" type="primary"  @click="importSave">确定</awsui-button>
          <awsui-button @click="cancel">取消</awsui-button>
        </span>
      </el-dialog>
    </div>
    <div v-else="category=='org'" key="dialog1" class="repository-import">
      <el-dialog
        title="导入组织模型"
        :visible.sync="dialogVisible"
        :close-on-click-modal=false
        width="500px"
        :before-close="handleClose">
        <div v-show="step1" id="step1" style="height: 250px;text-align: center;" v-loading="loading" element-loading-text="请稍等">
          <div style="position: relative;top:35%;">
            <div style="margin-bottom: 25px;">
              <awsui-button style="width: 130px;" class="button-general-color" type="primary" @click="openFileSelect('file')">直接导入</awsui-button>
            </div>
            <div>
              <awsui-button style="width: 130px;" class="button-general-color-reverse" @click="openFileSelect('excel')">模板导入</awsui-button>
            </div>
          </div>
        </div>
        <div v-show="step2" id="step2" style="height: 250px;" v-loading="loading" element-loading-text="请稍等">
          <div style="text-align: center;padding-top: 10px;">
            <awsui-button style="width: 130px;" :class="{'button-general-color': type == 'file', 'button-general-color-reverse': type == 'excel'}" :type="type == 'file' ? 'primary' : ''" @click="openFileSelect('file')">直接导入</awsui-button>
            <awsui-button style="width: 130px;" :class="{'button-general-color': type == 'excel', 'button-general-color-reverse': type == 'file'}" :type="type == 'excel' ? 'primary' : ''" @click="openFileSelect('excel')">模板导入</awsui-button>
          </div>
          <div v-if="type == 'file'">
            <div class="text-second-color" style="font-size: 12px;margin-top: 10px;margin-left: 15px;">请点击"直接导入"按钮上传export文件，支持多个文件同时导入</div>
            <div style="height: 180px;margin: 10px 10px;overflow:auto;">
              <PALUpload ref="palUpload" style="width: 100%;"
                 class="upload-demo"
                 appId="com.actionsoft.apps.coe.pal"
                 repositoryName="tmp"
                 groupValue="_import"
                 fileValue="Normal"
                 :multiple=true
                 :on-preview="handlePreview"
                 :on-success="handleSuccess"
                 :on-remove="handleRemove"
                 :on-error="handleError"
                 :before-remove="beforeRemove"
                 :before-upload="beforeUpload"
                 :on-exceed="handleExceed"
                 :on-progress="handleProgress"
                 accept=".export"
                 :file-list="fileList">
                <div style="display: none;">
                  <awsui-button name="selectFileButton" style="width: 130px;" class="button-general-color" type="primary">本地文件上传</awsui-button>
                </div>
              </PALUpload>
            </div>
          </div>
          <div v-if="type == 'excel'">
            <div style="height: 200px;margin: 25px 10px 10px;overflow:auto;">
              <div style="width: 438px;height: 80px;border: 1px solid #F2F2F2;">
                <div style="float: left;height: 100%;width: 80px;display: inline-block;background-color: #F5F7FA;text-align: center;line-height: 85px;vertical-align: middle;">
                  <i style="font-size: 40px;" class="iconfont text-second-color">&#xe61d;</i>
                </div>
                <div style="float: left;height: 100%;">
                  <div style="display: inline-block;height: 100%;margin-left: 15px;margin-top: 9px;">
                    <p class="text-general-color">填写导入组织信息</p>
                    <p class="text-second-color" style="font-size: 12px;padding-top: 4px;padding-bottom: 4px;">请按照说明格式正确填写Excel文件</p>
                    <p style="font-size: 12px;cursor: pointer;" class="text-linker-color" @click="downloadOrgTemplate()">下载模板</p>
                  </div>
                </div>
              </div>
              <div style="height: 20px;"></div>
              <div style="width: 438px;height: 80px;border: 1px solid #F2F2F2;">
                <div style="float: left;height: 100%;width: 80px;display: inline-block;background-color: #F5F7FA;text-align: center;line-height: 85px;vertical-align: middle;">
                  <i style="font-size: 40px;" class="iconfont text-second-color">&#xe612;</i>
                </div>
                <div style="float: left;height: 100%;">
                  <div style="display: inline-block;height: 100%;margin-left: 15px;margin-top: 9px;">
                    <p class="text-general-color">上传填好的组织信息文件</p>
                    <p class="text-second-color" style="font-size: 12px;padding-top: 4px;padding-bottom: 4px;">文件后缀必须为xls或xlsx（即Excel格式）</p>
                    <p v-if="!isOrgUploaded" style="font-size: 12px;cursor: pointer;" class="text-linker-color" @click="uploadOrgExcel">上传文件</p>
                    <p v-else style="font-size: 12px;cursor: pointer;" class="text-linker-color"><label style="display: inline-block;max-width: 300px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{{orgUploadFileName}}</label>&nbsp;<i class="iconfont text-important-color" style="font-size: 12px;position: relative;top: -3px;" @click="removeOrgUpload">&#xe626;</i></p>
                  </div>
                </div>
              </div>
            </div>
            <PALUpload ref="orgUpload" style="width: 100%;"
               class="upload-demo"
               appId="com.actionsoft.apps.coe.pal"
               repositoryName="tmp"
               groupValue="_import"
               fileValue="Normal"
               :limit="1"
               :show-file-list=false
               :on-success="handleOrgUploadSuccess"
               accept=".xls,.xlsx"
               :file-list="orgFileList">
              <div style="display: none;">
                <awsui-button name="selectOrgFileButton" style="width: 130px;" class="button-general-color" type="primary">Excel文件上传</awsui-button>
              </div>
            </PALUpload>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <awsui-button class="button-general-color" :disabled="buttonDisabled" type="primary"  @click="importSave">确定</awsui-button>
          <awsui-button @click="cancel">取消</awsui-button>
        </span>
      </el-dialog>
    </div>
  </el-container>
</template>

<script>
  import PALUpload from "@/components/common/upload/index.vue";
  import awsuiAxios from "../../awsuiAxios";
    export default {
      name: "RepositoryImport",
      components: {PALUpload},
      data() {
        return {
          dialogVisible: false,
          buttonDisabled: false,
          category: '',
          obj: null,
          fileList: [],
          step1: true,
          step2: false,
          type: 'file',
          orgFileList: [],
          isOrgUploaded: false,
          orgUploadFileName: '',
          parentId: '',
          loading: false
        }
      },
      inject: ['getIsHighSecurity','setSecurityVisible','securityFileList','setSecurityType'],
      computed:{
        isHighSecurity(){
          return this.getIsHighSecurity();
        },
      },
      methods: {
        clearParam() {
          this.category = '';
          this.obj = null;
          this.fileList = [];
          this.orgFileList = [];
          this.buttonDisabled = false;
          this.dialogVisible = false;
          this.step1 = true;
          this.step2 = false;
          this.type = '';
          this.isOrgUploaded = false;
          this.orgUploadFileName = '';
          this.parentId = '';
          this.loading = false;
          if (this.$refs.palUpload) {
            this.$refs.palUpload.clearFiles();
          }
          if (this.$refs.orgUpload) {
            this.$refs.orgUpload.clearFiles();
          }
        },
        openImportRepositoryDlg(obj, category, parentId) {
          const that = this;
          that.category = category;
          that.obj = obj;
          that.parentId = parentId;
          setTimeout(() => {
            that.dialogVisible = true;
            that.$nextTick(() => {
              if (that.category != 'org') {
                that.openFileSelect('file');
              }
            });
          }, 300);
        },
        cancel() {
          this.clearParam();
        },
        importSave() {
          const that = this;
          const wsId = that.$store.getters.getWsIdFn;
          const teamId = that.$store.getters.getTeamIdFn;
          let fileName = '';
          if (that.type == 'file') {
            if (that.fileList.length == 0) {
              that.$message({message: '请上传需要导入的文件',type: 'warning'});
              return;
            }
            const fileList = [];
            for (let i = 0; i < that.fileList.length; i++) {
              fileList.push(that.fileList[i].name);
            }
            that.buttonDisabled = true;
            that.loading = true;
            const data = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_pl_import',
                fileList: JSON.stringify(fileList),
                wsId: wsId,
                teamId: teamId,
                plCategory: that.category,
                parentId: that.parentId
              }
            };
            // 查询数据
            awsuiAxios.post(data).then(function (ro) {
              if(ro.result == 'ok') {
                //三员管理，密级标定
                if(that.isHighSecurity){
                  let securityBindList = ro.data.data.securityBindList;
                  if(undefined !=securityBindList && securityBindList.length>0){
                    for(let i=0;i<securityBindList.length;i++){
                      let securityBind = securityBindList[i];
                      that.securityFileList.push(securityBind);
                    }
                    that.setSecurityType("import")
                    that.setSecurityVisible(true);
                  }
                }else{
                  that.$message({
                    message: '导入成功',
                    type: 'success'
                  });
                }
                // 刷新节点，重新打开
                that.obj.refreshNode();
                that.obj.openRepositoryList(that.parentId);
                that.cancel();
              } else {
                that.$message.error(ro.msg);
                that.buttonDisabled = false;
                that.loading = false;
              }
            }).catch(error=>{
              console.log(error);
            })
          } else if (that.category == 'org' && that.type == 'excel') {// 组织Excel导入
            if (that.orgFileList.length == 0) {
              that.$message({message: '请上传需要导入的组织文件',type: 'warning'});
              return;
            }
            fileName = that.orgFileList[0].name;// 组织文件
            that.loading = true;

            const data = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_repository_import_org',
                fileName: fileName,
                wsId: wsId,
                teamId: teamId,
                parentId: that.parentId
              }
            };
            // 查询数据
            awsuiAxios.post(data).then(function (ro) {
              if(ro.result == 'ok') {
                //三员管理，密级标定
                if(that.isHighSecurity){
                  let securityBindList = ro.data.securityBindList;
                  if(undefined !=securityBindList && securityBindList.length>0){
                    for(let i=0;i<securityBindList.length;i++){
                      let securityBind = securityBindList[i];
                      that.securityFileList.push(securityBind);
                    }
                    that.setSecurityType("import")
                    that.setSecurityVisible(true);
                  }
                }else{
                  that.$message({
                    message: '导入成功',
                    type: 'success'
                  });
                } 
                // 刷新节点，重新打开
                that.obj.refreshNode();
                that.obj.openRepositoryList(that.parentId);
                that.cancel();
              } else {
                that.$message.error(ro.msg);
                that.buttonDisabled = false;
                that.loading = false;
              }
            }).catch(error=>{
              console.log(error);
            })
          }
        },
        handleClose(done) {
          this.clearParam();
          done();
        },
        handleRemove(file, fileList) {
          this.fileList = fileList;
        },
        handlePreview(file) {
          console.log(file);
        },

        handleExceed(files, fileList) {

        },
        handleError(err, file, fileList) {
        },
        beforeUpload(file) {
        },
        handleProgress(event, file, fileList) {
        },
        handleSuccess(response, file, fileList) {
          const that = this;
          that.fileList = [];
          let hash = {};
          for (let i = fileList.length-1; i >= 0; i--) {
            let currFile = fileList[i];
            if (!hash[currFile.name]) {
              that.fileList.unshift(currFile);
              hash[currFile.name] = true;
            }
          }
        },
        beforeRemove(file, fileList) {
          if (file.status == 'success') {
            // 删除之前，进行服务器文件删除
          }
        },
        openFileSelect(type) {
          this.type = type;
          if (this.category != 'org') {
            this.$nextTick(()=>{
              document.getElementsByName("selectFileButton")[0].click();
            });
          } else {
            if (type == 'file') {
              this.step1 = false;
              this.step2 = true;
              this.$nextTick(()=>{
                document.getElementsByName("selectFileButton")[0].click();
              });
            } else {
              this.type = type;
              this.step1 = false;
              this.step2 = true;
            }
          }
        },
        downloadOrgTemplate() {// 下载组织模板
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_repository_import_org_template',
              category: that.category
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            window.open(ro.url);
          }).catch(error=>{
            console.log(error);
          })
        },
        uploadOrgExcel() {// 上传组织文件
          if (this.$refs.orgUpload) {
            this.$refs.orgUpload.clearFiles();
          }
          document.getElementsByName("selectOrgFileButton")[0].click();
        },
        handleOrgUploadSuccess(response, file, fileList) {
          this.orgFileList = [];
          this.orgFileList.push(file);
          // 赋值
          this.orgUploadFileName = file.name;
          this.isOrgUploaded = true;
        },
        removeOrgUpload() {
          this.isOrgUploaded = false;
          this.orgFileList = [];
          this.orgUploadFileName = '';
        }
      }
    }
</script>

<style scoped>
  .repository-import >>> .el-dialog__body {
    padding: 10px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }
  .repository-import >>> .el-upload-list__item:first-child {
    margin-top: 0px;
  }
  .repository-import >>> .el-upload {
    display: none;
  }
</style>
