<template>
  <el-container>
    <div id="repositoryInfoUpfile" style="height: 500px;width: 100%;">
      <div v-if="havingWritePerm && !isPublish && !isStop && !isApproval" style="height: 40px;">
        <el-tooltip class="item" placement="bottom-start" :hide-after=5000>
          <div slot="content">附件格式支持:<br/>jpg, jpeg, gif, png, bmp, pdf, doc, docx, ppt, pptx, xls, xlsx, txt, mp3, mp4, avi, mpeg, flv, swf, wmv</div>
          <awsui-button style="width: 130px;" class="button-general-color" type="primary" @click="openFileSelect()" :disabled="isPublish || isStop || isApproval">上传附件</awsui-button>
        </el-tooltip>
        <PALUpload ref="orgUpload" style="width: 100%;"
                   class="upload-demo"
                   appId="com.actionsoft.apps.coe.pal"
                   :repositoryName=repositoryName
                   :multiple=true
                   :groupValue=groupValue
                   :fileValue=id
                   :show-file-list=false
                   :on-success="uploadSuccess"
                   :before-upload="beforeUpload"
                   accept=".jpg,.jpeg,.gif,.png,.bmp,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.mp3,.mp4,.avi,.mpeg,.flv,.swf,.wmv"
                   :file-list="fileList">
          <div style="display: none;">
            <awsui-button id="selectFileButton" style="width: 130px;" class="button-general-color" type="primary">Excel文件上传</awsui-button>
          </div>
        </PALUpload>
      </div>
      <div style="height: 460px;width: 100%;overflow: auto;">
        <div>
          <el-table
            :show-header=false
            :data="fileTable"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="名称"
              min-width="300">
            </el-table-column>
            <el-table-column v-if="isHighSecurity"
              prop="securityLevel"
              label="文件密级"
              min-width="50">
            </el-table-column>
            <el-table-column
              prop="operate"
              label="操作"
              align="center"
              width="150">
              <template slot-scope="scope">
                <el-tooltip v-if="onlineDoc" content="预览" placement="bottom" :hide-after=2000>
                  <i class="iconfont operate-icon-display" style="cursor: pointer;" @click="readFile(scope.row.id)">&#xe8b5;</i>
                </el-tooltip>
                <el-tooltip content="下载" placement="bottom" :hide-after=2000>
                  <i class="iconfont operate-icon-display" style="cursor: pointer;padding-left: 15px;" @click="downloadFile(scope.row.url)">&#xe63b;</i>
                </el-tooltip>
                <el-tooltip v-if="havingRemovePerm && !isPublish && !isStop && !isApproval" content="删除" placement="bottom" :hide-after=2000>
                  <i class="iconfont icon-lajitong1 operate-icon-display" style="cursor: pointer;padding-left: 15px;" @click="deleteFile(scope.row.name, scope.row.id)"></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="height: 25px;line-height: 25px;vertical-align: center;margin: 30px 30px 15px 0px;border-left: 3px solid #4E7FF9;"><p style="padding-left: 5px;"><b>关联附件</b></p></div>
        <div>
          <el-table
            :show-header=false
            :data="relationFileTable"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="名称"
              min-width="300">
            </el-table-column>
            <el-table-column v-if="isHighSecurity"
              prop="securityLevel"
              label="文件密级"
              min-width="50">
            </el-table-column>
            <el-table-column
              prop="operate"
              label="操作"
              align="center"
              width="150">
              <template slot-scope="scope">
                <el-tooltip content="预览" placement="bottom" :hide-after=2000>
                  <i class="iconfont operate-icon-display" style="cursor: pointer;" @click="readFile(scope.row.id)">&#xe8b5;</i>
                </el-tooltip>
                <el-tooltip content="下载" placement="bottom" :hide-after=2000>
                  <i class="iconfont operate-icon-display" style="cursor: pointer;padding-left: 15px;" @click="downloadFile(scope.row.url)">&#xe63b;</i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div >
      <awsui-dialog
            title="密级标定"
            :visible.sync="securityVisible"
            :border="false"
            append-to-body
            width="500px">
          <div style="max-height:500px;overflow-y: auto">
            <awsui-form :ref="file.uid" label-width="200px" id="securityDialog" :rules="securityRules" v-for="file in securityFileList" :key="file.uid" :model="file">
              <awsui-form-item :label="file.name"  prop="securityLevel">
                  <awsui-select v-model="file.securityLevel" :options="securityOptions" style="width:70%"></awsui-select>
              </awsui-form-item>
            </awsui-form>
          </div>
        <div slot="footer" class="dialog-footer">
            <awsui-button type="primary" @click="uploadServer">确定</awsui-button>
            <awsui-button @click="securityVisible = false">取 消</awsui-button>
        </div>
      </awsui-dialog>
    </div>
  </el-container>
  
</template>

<script>
  import PALUpload from "@/components/common/upload/index.vue";
  import awsuiAxios from "../../awsuiAxios";
    export default {
      name: "RepositoryInfoUpfile",
      components: {PALUpload},
      props: ['id', 'versionId', 'isUse', 'isPublish', 'isStop', 'isApproval'],
      data() {
          var securityValidate = (rule, value, callback) => {
            if (value === undefined ) {
              callback(new Error('请选择文件密级'));
            } else {
              callback();
            }
          };
          return {
            fileTable: [],
            relationFileTable: [],
            fileList: [],
            groupValue: 'file',
            onlineDoc: true,
            havingWritePerm: false,
            havingRemovePerm: false,
            havingVersionManagePerm: false,
            isHighSecurity: false,
            isFileSecurity: false,
            securityList: {},
            repositoryName: 'COE_Upfile',
            securityVisible: false,
            securityFileList: [],
            securityOptions:[],
            securityRules: {
              securityLevel: [{ required: true, trigger: "change", validator: securityValidate ,type: "number"}],
            },
            validateFlag: true,
          }
      },
      created() {
        this.initData();
        this.initRelationData();
      },
      watch: {
        //密级选择dialogVisible 变为false，清空securityFileList
        securityVisible(newval, oldval){
            if(!newval){
              this.securityFileList.splice(0,this.securityFileList.length);
            }
        },
      },
      methods: {
        initData() {
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_processlevel_upfile_load',
              pl_uuid: that.id,
              type: 'file',
              wsId: that.$store.getters.getWsIdFn,
              teamId: that.$store.getters.getTeamIdFn
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if(ro.result == 'ok') {
              that.havingWritePerm = ro.data.havingWritePerm;
              that.havingRemovePerm = ro.data.havingRemovePerm;
              that.havingVersionManagePerm = ro.data.havingVersionManagePerm;
              //三员管理
              that.isHighSecurity = ro.data.isHighSecurity;
              that.isFileSecurity = ro.data.isFileSecurity;
              that.securityList = ro.data.securityList;
              if(ro.data.isHighSecurity){
                that.repositoryName = 'tmp';
              }
              const list = ro.data.list;
              let fileTable = [];
              for (let i = 0; i < list.length; i++) {
                const curr = list[i];
                const tableRow = {
                  id: curr.uuid,
                  name: curr.fileName,
                  url: curr.url,
                  securityLevel: that.isHighSecurity ? ro.data.securityList[curr.securityLevel]: "",
                };
                fileTable.push(tableRow);
              }
              that.fileTable = fileTable;
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        initRelationData() {
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_processlevel_relation_upfile_load',
              pl_uuid: that.id,
              type: 'file'
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if(ro.result == 'ok') {
              //三员管理
              that.isHighSecurity = ro.data.isHighSecurity;
              that.securityList = ro.data.securityList;
              if(ro.data.isHighSecurity){
                that.repositoryName = 'tmp';
              }
              const list = ro.data.list;
              let relationFileTable = [];
              for (let i = 0; i < list.length; i++) {
                const curr = list[i];
                const tableRow = {
                  id: curr.uuid,
                  name: curr.fileName,
                  url: curr.url,
                  securityLevel: that.isHighSecurity ? that.securityList[curr.securityLevel] : "",
                };
                relationFileTable.push(tableRow);
              }
              that.relationFileTable = relationFileTable;
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        openFileSelect() {
          let that = this;
          // 文件访问权限控制
          if(that.isHighSecurity && that.isFileSecurity){
            const data = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_pl_file_permission_query',
                uuid: that.id,
              }
            };
            awsuiAxios.post(data).then(function (ro) {
              if(ro.result == 'ok') {
                document.getElementById("selectFileButton").click();
              }else{
                that.$message.error(ro.msg);
              }
            }).catch(error=>{
              console.log(error);
              that.$message.error(error.msg);
            })
          }else{
            document.getElementById("selectFileButton").click();
          }
        },
        uploadSuccess(response, file, fileList) {// 上传完成后保存
          //开启三员管理
          if(this.isHighSecurity){
            //开启密级标定dialog
            if(!this.securityVisible){
              this.securityVisible = true;
            }
            //设置密级options
            if(this.securityOptions.length == 0){
               Object.keys(this.securityList).map(key =>{
                   let option= {
                   value: key,
                   label: this.securityList[key]
                 }
                 this.securityOptions.push(option);
               })
            }
            this.securityFileList.push(file);       
          }else{
            const that = this;
            const data = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_processlevel_upfile_add',
                pl_uuid: that.id,
                shape_uuid: "",
                type: 'file',
                fileName: file.name,
                download: 1 // 全部可下载
              }
            };
            // 查询数据
            awsuiAxios.post(data).then(function (ro) {
              if(ro.result == 'ok') {
                that.$message({
                  message: '['+ file.name +']上传成功',
                  type: 'success'
                });
                that.initData();
              } else {
                that.$message.error('['+ file.name +']上传失败');
              }
            }).catch(error=>{
              console.log(error);
            })
          }
        },
        uploadServer(){ //三员管理下附件上传
          this.validateFlag = true;
          //规则校验
          for(let i=0;i<this.securityFileList.length;i++){
            let file = this.securityFileList[i];
            this.$refs[file.uid][0].validate(valid =>{
              if(!valid){
                this.validateFlag = false;
                return false;
              }
            });
          }
          //文件上传
          if(this.validateFlag){
            for(let i=0;i<this.securityFileList.length;i++){
              let file = this.securityFileList[i];
              const that = this;
              const data = {
                url:'jd',
                data:{
                  cmd: 'com.actionsoft.apps.coe.pal_processlevel_upfile_add',
                  pl_uuid: that.id,
                  shape_uuid: "",
                  type: 'file',
                  fileName: file.name,
                  download: 1 ,// 全部可下载，
                  securityLevel: file.securityLevel == undefined ? "" : file.securityLevel,
                }
              };
                  
              // 查询数据
              awsuiAxios.post(data).then(function (ro) {
                if(ro.result == 'ok') {
                  that.$message({
                    message: '['+ file.name +']上传成功',
                    type: 'success'
                  });
                  that.initData();
                } else {
                  that.$message.error('['+ file.name +']上传失败');
                }
              }).catch(error=>{
                console.log(error);
              })
            }
            this.securityVisible = false;
          }
          
        },
        beforeUpload(file) {// 单个文件校验，返回false不影响其他文件上传
          if (file.size > 256 * 1024 * 1024) {
            this.$message({message: '文件[' + file.name + ']不允许大于256M，上传失败',type: 'warning'});
            return false;
          }
          // 校验上传名称是否存在相同，相同则提示上传失败
          for (let i = 0; i < this.fileTable.length; i++) {
            const currFile = this.fileTable[i];
            if (currFile.name == file.name) {
              this.$message({message: '文件[' + file.name + ']已存在，不允许重复上传',type: 'warning'});
              return false;
            }
          }
        },
        readFile(id) {// 在线预览
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_processlevel_upfile_read',
              uuid: id
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if(ro.result == 'ok') {
              window.open(ro.data.url);
            } else {
              that.$message.error(ro.msg);
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        downloadFile(url) {
          window.open(url);
        },
        deleteFile(name, id) {
          this.$confirm('确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            confirmButtonClass: 'button-general-color',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const that = this;
            const data = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_processlevel_upfile_del',
                uuid: id,
              }
            };
            // 查询数据
            awsuiAxios.post(data).then(function (ro) {
              if(ro.result == 'ok') {
                that.$message({
                  message: '删除成功',
                  type: 'success'
                });
                that.initData();
              } else {
                that.$message.error('删除失败');
              }
            }).catch(error=>{
              console.log(error);
            })
          }).catch(() => {
          });
        }
      }
    }
</script>

<style scoped>
  #repositoryInfoUpfile >>> .el-table__row .operate-icon-display{
    display: none;
  }
  #repositoryInfoUpfile >>> .el-table__row:hover .operate-icon-display{
    display: inline-block;
  }
</style>
