<template>
  <div class="fullheight">
    <ht-table @load="loadData" :data="data" :pageResult="pageResult" :selection="true" quick-search-props="name,desc" :show-export="false" 
    :show-custom-column="false"  :defaultSorter="[{property:'UPDATE_TIME_',direction:'DESC'}]" ref="htTable">
      <template v-slot:toolbar>
        <el-button-group>
          <el-button size="small" @click="showDialog()" icon="el-icon-plus"  type="primary">添加</el-button>
        </el-button-group>
      </template>
      <template>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column prop="desc" label="描述" :sortable="true" :show-overflow-tooltip="true">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDialog(row.id)" title="查看详情">{{ row.desc }}</el-link>
          </template>
        </ht-table-column>
        <ht-table-column prop="name" label="名称" :sortable="true" :show-overflow-tooltip="true"> </ht-table-column>
        <ht-table-column width="120" prop="size" label="大小(KB)" :sortable="true"> </ht-table-column>
        <ht-table-column width="120" prop="status" label="状态" :sortable="true">
          <template v-slot="{ row }">
            <el-tag type="info" v-if="row.status == '1'">未发布</el-tag>
            <el-tag type="danger" v-if="row.status != '1'">已发布</el-tag>
          </template>
        </ht-table-column>
        <ht-table-column width="120" prop="type" label="类型" :sortable="true">
          <template v-slot="{ row }">
            <el-tag v-if="row.type == 0">script脚本扩展</el-tag>
            <el-tag v-else-if="row.type == 1">用户数据同步</el-tag>
            <el-tag v-else>其他</el-tag>
          </template>
        </ht-table-column>
        <ht-table-column width="200" prop="createName" label="上传人" :sortable="true"> </ht-table-column>
        <ht-table-column width="200" prop="createTime" label="上传时间" :sortable="true"> </ht-table-column>
        <ht-table-column width="200" prop="updateTime" label="最后发布时间" :sortable="true"> </ht-table-column>
        <ht-table-column width="170" label="操作" align="left">
          <template v-slot="{ row }">
            <el-button size="mini" type="text" @click="publishJar(row.id)">发布</el-button>
            <el-button type="text" @click="deleteJar(row.id)" size="mini">删除</el-button>
          </template>
        </ht-table-column>
      </template>
    </ht-table>
    <ht-sidebar-dialog width="28%" :title="(bpmExtendJar.id ? '编辑' : '新增') + '扩展jar包'" v-if="dialogVisible" class="sp-manager__dialog" :visible="dialogVisible" :before-close="beforeCloseDialog">
      <el-form v-form data-vv-scope="bpmExtendJarForm">
        <ht-form-item label="描述">
          <ht-input v-model="bpmExtendJar.desc" validate="required" :maxlength="100" show-word-limit/>
        </ht-form-item>

        <ht-form-item v-if="bpmExtendJar.id" label="名称">
          <ht-input v-model="bpmExtendJar.name" permission="r" validate="required" />
        </ht-form-item>

        <ht-form-item label="类型" >
          <ht-select
            v-model="bpmExtendJar.type"
            :options="typeList"
            :validate="{required: true}"
            placeholder="请选择扩展类型"
          />
        </ht-form-item>

        <ht-form-item label="Jar包">
          <el-upload
            style="display: inline-block"
            :action="imporCheckUrl"
            :on-success="handleUploadResult"
            :on-error="handleUploadResult"
            :headers="uploadHeaders"
            :on-exceed="onExceed"
            accept=".jar"
            :before-upload="beforeUpload"
            :on-remove="resetJar"
            :limit="1"
            :data="{ isCheck: true, type: bpmExtendJar.type }"
            ref="upload"
            :file-list="files"
          >
            <el-button size="small" icon="el-icon-upload">选择Jar包</el-button>
          </el-upload>
        </ht-form-item>

        <ht-form-item label="大小(KB)">
          <ht-input v-model="bpmExtendJar.size" permission="r" validate="required" />
        </ht-form-item>
      </el-form>

      <p>扩展类列表</p>
      <el-table :data="bpmExtendJar.classList" :show-export="false" :show-custom-column="false" ref="htTable1" border>
        <template>
          <el-table-column type="index" width="50" align="center" label="序号" />
          <el-table-column prop="path" label="类路径" :show-overflow-tooltip="true"> </el-table-column>
          <!-- <el-table-column width="90" prop="type" label="类型">
            <template v-slot="{ row }">
              <el-tag type="info" v-if="row.status == '1'">常用脚本</el-tag>
              <el-tag type="danger" v-if="row.status != '1'">人员脚本</el-tag>
            </template>
          </el-table-column> -->
        </template>
      </el-table>

      <div slot="footer" style="text-align:right">
        <el-button @click="beforeCloseDialog">{{ $t('eip.common.cancel') }}</el-button>
        <el-button type="primary" @click="save(false)">{{ $t('eip.common.save') }}</el-button>
      </div>
    </ht-sidebar-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex';

export default {
  data() {
    return {
      dialogVisible: false,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      bpmExtendJar: { name: '', jarBytes: '', desc: '', size: '', classList: [] },
      saveMethod: 'POST',
      typeList: [
        {key: 0, value: 'script脚本扩展'},
        {key: 1, value: '用户数据同步'},
        {key: 2, value: '其他'},
      ],
      files: [],
    };
  },
  computed: mapState({
    uploadHeaders: function (mapState) {
      return { Authorization: 'Bearer ' + mapState.login.currentUser.token };
    },
    imporCheckUrl: function () {
      return window.context.bpmRunTime + '/bpmExtendJar/v1/resolutionJar'
    },
    account: (state) => state.login.currentUser.account,
    token: (state) => state.login.currentUser.token,
  }),
  mounted() {
    this.$validator = this.$root.$validator;
  },
  methods: {
    publishJar(id, iscover) {
      let this_ = this;
      this.$http.get('${bpmRunTime}/bpmExtendJar/v1/publishJar?jarId=' + id + '&iscover=' + (iscover || false)).then(function (response) {
        let data = response.data;
        var height = (document.documentElement.clientHeight || document.body.clientHeight) * 0.85 + 'px'
        if (data.value) {
          this_
            .$confirm('<div style="overflow-x:hidden;overflow-y:auto;word-break: break-all;max-height:' + height + '">脚本类【' + data.value + '】已存在，是否确认覆盖?</div>', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warining',
            })
            .then(() => {
              this_.publishJar(id, true);
            });
        } else if (data.state) {
          this_.$message.success('发布成功');
          setTimeout(() => {
            this_.dialogVisible = false;
            this_.$refs.htTable.load();
          }, 1000);
        }
      });
    },
    deleteJar(id) {
      let this_ = this;
      this.$confirm('确定删除Jar包及其下的脚本类和人员脚本配置？', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        closeOnClickModal: false,
      }).then(() => {
        this.$http.remove('${bpmRunTime}/bpmExtendJar/v1/deleteById?id=' + id).then(function (response) {
          let data = response.data;
          if (data.state) {
            this_.$message.success('删除成功');
            setTimeout(() => {
              this_.dialogVisible = false;
              this_.$refs.htTable.load();
            }, 1000);
          }
        });
      });
    },
    save() {
      let this_ = this;
      this.$validator.validateAll('bpmExtendJarForm').then((result) => {
        if (result) {
          console.log("this_.bpmExtendJar", this_.bpmExtendJar)
          if (!this_.bpmExtendJar.name) {
            this.$message.error('请上传jar包');
            return;
          }
          this.$http.post('${bpmRunTime}/bpmExtendJar/v1/saveJar', this_.bpmExtendJar).then((resp) => {
            let response = resp.data;
            if (response.state) {
              this_.$message.success('操作成功');
              setTimeout(() => {
                this_.dialogVisible = false;
                this_.$refs.htTable.load();
              }, 1000);
            }
          });
        } else {
          this.$message.error('请填写必填项');
        }
      });
    },
    onExceed() {
      this.$message.warning('只能选择一个Jar文件!');
    },
    beforeUpload(file) {
      if (this.bpmExtendJar.type == undefined){
        this.$message.warning('请先选择类型!');
        return false;
      }
      if (!file.name.endsWith('.jar')) {
        this.$message.warning('只能导入Jar文件!');
        return false;
      }
      if (file.size > 1024 * 1024) {
        this.$message.warning('Jar文件不能大于1024KB!');
        return false;
      }
      this.imporActionUrl = this.imporCheckUrl;
      this.fullscreenLoading = true;
    },
    resetJar() {
      this.bpmExtendJar.jarBytes = '';
      this.bpmExtendJar.size = '';
      this.bpmExtendJar.name = '';
      this.bpmExtendJar.classList = [];
    },
    handleUploadResult(response) {
      if (response.state) {
        this.bpmExtendJar.jarBytes = response.value.jarBytes;
        this.bpmExtendJar.name = response.value.name;
        this.bpmExtendJar.size = response.value.size;
        this.bpmExtendJar.classList = response.value.classList;
      } else {
        this.resetJar();
        this.$message.error(JSON.parse(response.message).message);
      }
    },
    showDialog(id) {
      this.files = []
      if (id) {
        this.$http.get('${bpmRunTime}/bpmExtendJar/v1/getJarById?id=' + id).then((resp) => {
          this.bpmExtendJar = resp.data;
          const fileName = this.bpmExtendJar.name
          this.files.push({name: fileName})
        });
      } else {
        this.bpmExtendJar = { name: '', jarBytes: '', desc: '', size: '', classList: [] };
      }
      this.dialogVisible = true;
    },
    beforeCloseDialog() {
      this.bpmExtendJar = { name: '', jarBytes: '', desc: '', size: '', classList: [] };
      this.dialogVisible = false;
    },
    loadData(param, cb) {
      this.$http
        .post('${bpmRunTime}/bpmExtendJar/v1/query', param)
        .then(
          (resp) => {
            let response = resp.data;
            this.data = response.rows;
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            };
          },
          (error) => {
            reject(error);
          }
        )
        .finally(() => cb());
    },
    afterSaveData() {
      setTimeout(() => {
        this.beforeCloseDialog();
        this.$refs.htTable.load();
      }, 500);
    },
  },
};
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ > .el-dialog > .el-dialog__body {
  height: calc(100% - 190px);
}
</style>
