<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="filter-container">
        <el-checkbox v-model="latestVersion">最新版本</el-checkbox>
      </div>
      <model-search @search="reload" />
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        cache-key="systemRoleTable9"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="btnCreate"
            class="ele-btn-icon"
            >新增
          </el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="btnImport"
            class="ele-btn-icon"
            >导入
          </el-button>
          <el-button
            icon="el-icon-delete"
            size="small"
            type="danger"
            @click="btnDelete()"
            class="ele-btn-icon"
            >批量删除
          </el-button>
        </template>
        <template v-slot:category="{ row }">
          <span v-html="getDictValue('流程分类', row.category)"></span>
        </template>
        <template v-slot:deployed="{ row }">
          <span>{{ row.deployed ? '是' : '否' }}</span>
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-dropdown>
            <span class="el-dropdown-link"
              >操作<i class="el-icon-arrow-down el-icon--right"></i
            ></span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-view" @click.native="btnView(row)"
                >查看</el-dropdown-item
              >
              <!-- <el-dropdown-item
                icon="el-icon-edit"
                divided
                @click.native="btnUpdate(row)"
                >修改
              </el-dropdown-item> -->
              <el-dropdown-item
                icon="el-icon-edit"
                divided
                @click.native="btnCopy(row)"
                >复制
              </el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-edit"
                divided
                @click.native="btnUpdateModel(row)"
                >流程设计
              </el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-delete"
                divided
                @click.native="btnDelete(row.id)"
                >删除
              </el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-delete"
                divided
                @click.native="btnDelete(row.id, true)"
                >删除包含历史
              </el-dropdown-item>
              <el-dropdown-item
                v-if="!row.deployed"
                icon="el-icon-edit"
                divided
                @click.native="btnDeploy(row.id)"
                >部署
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </el-card>
    <ele-modal
      width="720px"
      :visible="dialogFormVisible"
      :append-to-body="true"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      title="流程模型"
      @update:visible="dialogFormVisible = false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        :disabled="dialogStatus === 'view'"
        label-position="right"
        label-width="110px"
      >
        <el-form-item label="模型key" prop="key">
          <el-input
            :disabled="dialogStatus === 'update'"
            v-model="temp.key"
            placeholder="不能为纯数字"
          />
        </el-form-item>
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="模型类别" prop="category">
          <DictSelection dictName="流程分类" clearable v-model="temp.category">
          </DictSelection>
        </el-form-item>
        <el-form-item label="模型描述" prop="description">
          <el-input v-model="temp.description" />
        </el-form-item>
        <!-- <el-form-item label="租户ID" prop="tenantId">
          <el-input v-model="temp.tenantId" />
        </el-form-item> -->
      </el-form>

      <template v-slot:footer>
        <el-button icon="el-icon-close" @click="dialogFormVisible = false"
          >取消</el-button
        >
        <el-button
          v-if="dialogStatus !== 'view'"
          icon="el-icon-check"
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确定
        </el-button>
      </template>
    </ele-modal>

    <el-dialog title="流程导入" :visible.sync="dialogImportVisible">
      <!--<div class="filter-container">
                <el-input v-model="importTenantId" placeholder="租户" clearable style="width: 200px;"/>
            </div>-->
      <el-upload
        class="upload-demo"
        drag
        action
        :show-file-list="false"
        :before-upload="beforeUpload"
        :http-request="doImport"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip"
          >只能上传.bpmn20.xml,.bpmn文件，且不超过512K</div
        >
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
  import {
    deleteAction,
    getAction,
    postAction,
    putAction
  } from '@/api/flowable/manage';
  import { Message } from 'element-ui';
  import dictMixins from '@/mixins/dictMixins';
  import modelSearch from './model-search.vue';

  export default {
    name: 'FlowableModel',
    components: { modelSearch },
    mixins: [dictMixins],
    data () {
      return {
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },

          {
            prop: 'key',
            label: '模型key',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '模型名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'category',
            label: '模型类别',
            align: 'center',
            slot: 'category',
            showOverflowTooltip: true
          },
          {
            prop: 'version',
            label: '版本',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'deployed',
            label: '是否发布',
            align: 'center',
            slot: 'deployed',
            showOverflowTooltip: true
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 230,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        selection: [],
        latestVersion: true,
        records: null,

        total: 0,
        listQuery: {
          current: 1,
          size: 10,
          modelKey: undefined,
          latestVersion: true,
          modelName: undefined,
          modelCategory: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          id: undefined,
          key: '',
          name: '',
          category: '',
          description: ''
        },
        rules: {
          id: [{ required: true, message: '该项不能为空', trigger: 'change' }],
          key: [{ required: true, message: '该项不能为空', trigger: 'change' }],
          name: [
            { required: true, message: '该项不能为空', trigger: 'change' }
          ],
          category: [
            { required: true, message: '该项不能为空', trigger: 'change' }
          ]
        },
        dialogImportVisible: false
      };
    },
    beforeCreate () {
      // this.getDicts('processCategory,taskCategory').then(({data}) => {
      //     this.dicts = data
      // })
    },
    created () {
      this.requestDict('流程分类');
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive () {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 表格数据源 */
      async datasource ({ page, limit, where, order }) {
        // return pageRoles({ pageNum: page, size: limit, ...where });
        const res = await getAction('/flowable/model/list', {
          current: page,
          size: limit,
          latestVersion: this.latestVersion,
          ...where
        });

        const { data } = res.data;
        return {
          list: data.records,
          count: data.total
        };
        // return data;
      },
      /* 刷新表格 */
      reload (where) {
        this.$refs.table.reload({ page: 1, where });
      },

      resetTemp () {
        this.temp = {
          id: undefined,
          key: '',
          name: '',
          category: '',
          description: '',
          tenantId: ''
        };
      },
      btnView (row) {
        this.temp = Object.assign({}, row);
        this.dialogStatus = 'view';
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        });
      },
      btnCreate () {
        this.resetTemp();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        });
      },
      btnImport () {
        this.dialogImportVisible = true;
      },
      beforeUpload (file) {
        // 上传前格式与大小校验
        const fileName = file.name;
        const isFileTypeOk =
          fileName.endsWith('.bpmn20.xml') ||
          fileName.endsWith('.bpmn') ||
          fileName.endsWith('.bar') ||
          fileName.endsWith('.zip');
        const isLt512 = file.size / 1024 / 512 < 1;
        if (!isFileTypeOk) {
          Message.error('上传文件格式不正确');
        }
        if (!isLt512) {
          Message.error('上传文件大小不能超过512K');
        }
        return isFileTypeOk && isLt512;
      },
      doImport (fileObj) {
        let formData = new FormData();
        formData.set('file', fileObj.file);
        // formData.set("tenantId", this.importTenantId);
        postAction('/flowable/model/import', formData).then(({ msg }) => {
          this.dialogImportVisible = false;
          Message.success(msg);
          this.reload();
        });
      },
      //验证字符串是否是数字
      checkNumber (theObj) {
        var reg = /^[0-9]+\.?[0-9]*$/;
        if (reg.test(theObj)) {
          return true;
        }
        return false;
      },
      createData () {
        if (this.checkNumber(this.temp.key)) {
          this.$message({
            message: 'KEY不能为纯数字',
            type: 'warning'
          });
          return;
        }

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            postAction('/flowable/model/save', this.temp).then(({ data }) => {
              this.dialogFormVisible = false;
              console.log(data);
              Message.success('添加' + data.message);
              this.reload();
            });
          }
        });
      },
      btnUpdate (row) {
        this.temp = Object.assign({}, row);
        this.dialogStatus = 'update';
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        });
      },
      btnCopy (row) {
        putAction('/flowable/model/copy', { id: row.id }).then((res) => {
          Message.success('复制' + res.data.message);
          this.reload();
        });
      },
      btnUpdateModel (row) {
        this.$router.push({
          path: '/flowable/model/edit',
          query: { id: row.id, isView: row.deployed }
          // query: { id: row.id, isView: false }
        });
      },
      updateData () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            putAction('/flowable/model/update', this.temp).then((res) => {
              this.dialogFormVisible = false;
              this.$message.success(res.data.message);
              this.reload();
            });
          }
        });
      },
      btnDelete (id, cascade) {
        let ids = id
          ? [id]
          : this.selection.map((record) => {
              return record.id;
            });
        if (ids.length == 0) {
          Message.error('请选择要删除的记录');
          return;
        }
        deleteAction('/flowable/model/delete', {
          ids: ids.toString(),
          cascade
        }).then((res) => {
          console.log('res', res);

          Message.success('删除' + res.data.message);
          this.reload();
        });
      },
      btnDeploy (id) {
        postAction('/flowable/model/deploy', { id })
          .then((res) => {
            Message.success('部署' + res.data.message);
            this.reload();
          })
          .catch((err) => {
            console.log(err);
          });
      },
      selectionChange (selection) {
        this.selection = selection;
      }
    }
  };
</script>
<style>
  .app-container {
    padding: 10px;
  }
  .filter-container .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 5px;
    margin-right: 4px;
  }
  .filter-container {
    padding-bottom: 5px;
  }
</style>
