<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="filter-container">
        <el-checkbox v-model="listQuery.latestVersion">最新版本</el-checkbox>
        <el-checkbox v-model="listQuery.suspended">挂起的</el-checkbox>
        <el-checkbox v-model="listQuery.active">激活的</el-checkbox>
      </div>
      <div class="filter-container">
        <el-form
          label-width="100px"
          class="ele-form-search"
          @keyup.enter.native="search"
          @submit.native.prevent
        >
          <el-row :gutter="15">
            <el-col v-bind="styleResponsive ? { lg: 5, md: 12 } : { span: 6 }">
              <el-form-item label="流程定义名称:">
                <el-input
                  clearable
                  v-model="listQuery.processDefinitionName"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col v-bind="styleResponsive ? { lg: 5, md: 12 } : { span: 6 }">
              <el-form-item label="流程定义KEY:">
                <el-input
                  clearable
                  v-model="listQuery.processDefinitionKey"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col v-bind="styleResponsive ? { lg: 5, md: 12 } : { span: 6 }">
              <el-form-item label="流程定义分类:">
                <DictSelection
                  dictName="流程分类"
                  clearable
                  v-model="listQuery.processDefinitionCategory"
                >
                </DictSelection>
              </el-form-item>
            </el-col>

            <el-col v-bind="styleResponsive ? { lg: 9, md: 12 } : { span: 6 }">
              <div class="ele-form-actions">
                <el-button @click="btnReset">重置</el-button>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  class="ele-btn-icon"
                  @click="btnQuery"
                >
                  查询
                </el-button>

                <!-- <el-button
                  icon="el-icon-plus"
                  type="primary"
                  @click="btnImport"
                  class="filter-item"
                  >导入
                </el-button> -->
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="systemRoleTable5"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="btnImport"
            class="ele-btn-icon"
            >导入
          </el-button>
        </template>
        <template v-slot:category="{ row }">
          <span v-html="getDictValue('流程分类', row.category)"></span>
        </template>
        <template v-slot:suspended="{ row }">
          <span>{{ row.suspended ? '挂起' : '激活' }}</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-view"
                divided
                @click.native="btnImage(row.id)"
                >流程图
              </el-dropdown-item>
              <!-- <el-dropdown-item
                icon="el-icon-edit"
                divided
                @click.native="btnProcessDefinitionIdentityLink(row)"
                >流程授权
              </el-dropdown-item> -->
              <el-dropdown-item
                icon="el-icon-edit"
                divided
                @click.native="btnExport(row)"
                >导出
              </el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-edit"
                divided
                @click.native="btnSuspendOrActivate(row.id, row.suspended)"
              >
                {{ row.suspended ? '激活' : '挂起' }}
              </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
                icon="el-icon-view"
                divided
                @click.native="btnViewProcessInstanceList(row)"
                >实例列表
              </el-dropdown-item>
              <!--<el-dropdown-item icon="el-icon-edit" divided @click.native="btnStartInstance(row)">发起流程
                            </el-dropdown-item>-->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </el-card>

    <el-dialog title="流程定义" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        disabled
        label-position="right"
        label-width="110px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="流程定义ID" prop="id">
              <el-input v-model="temp.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流程定义名称" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="流程定义KEY" prop="key">
              <el-input v-model="temp.key" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流程定义分类" prop="category">
              <el-input v-model="temp.category" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="流程定义描述" prop="description">
              <el-input v-model="temp.description" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="temp.version" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="suspended">
              <el-input v-model="temp.suspended ? '挂起' : '激活'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表单key" prop="formKey">
              <el-input v-model="temp.formKey" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogFormVisible = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
    <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,.bar,.zip文件，且不超过512K</div
        >
      </el-upload>
    </el-dialog>

    <process-image
      v-if="dialogProcessImageVisible"
      :visible.sync="dialogProcessImageVisible"
      :processDefinitionId="selectedProcessDefinitionId"
    ></process-image>

    <process-definition-identity-link
      v-if="dialogProcessDefinitionIdentityLinkVisible"
      :visible.sync="dialogProcessDefinitionIdentityLinkVisible"
      :processDefinitionId="selectedProcessDefinitionId"
      :processDefinitionName="selectedProcessDefinitionName"
    ></process-definition-identity-link>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination';
  import {
    deleteAction,
    downloadAction,
    getAction,
    postAction,
    putAction
  } from '@/api/flowable/manage';
  import dictMixins from '@/mixins/dictMixins';
  import { Message } from 'element-ui';

  import ProcessImage from './components/ProcessImage';
  import ProcessDefinitionIdentityLink from './ProcessDefinitionIdentityLink';

  export default {
    mixins: [dictMixins],

    name: 'FlowableProcessDefinition',
    components: { ProcessImage, ProcessDefinitionIdentityLink, Pagination },
    data () {
      return {
        columns: [
          {
            type: 'index',
            label: '序号',
            width: 50,
            align: 'center',
            fixed: 'left'
          },

          {
            prop: 'name',
            label: '流程定义名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'key',
            label: '流程定义KEY',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'category',
            label: '流程定义分类',
            align: 'center',
            slot: 'category',
            showOverflowTooltip: true
          },
          {
            prop: 'version',
            label: '版本',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'suspended',
            label: '状态',
            align: 'center',
            slot: 'suspended',
            showOverflowTooltip: true
          },

          {
            prop: 'formKey',
            label: '表单key',
            align: 'center',
            showOverflowTooltip: true
          },

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

        records: null,

        total: 0,
        listQuery: {
          processDefinitionId: undefined,

          processDefinitionName: undefined,
          processDefinitionKey: undefined,
          latestVersion: true,
          suspended: false,
          active: false
        },
        dialogFormVisible: false,
        dialogImportVisible: false,
        // importTenantId: '',
        dialogProcessImageVisible: false,

        // formJson: {"list":[{"type":"input","icon":"icon-input","options":{"width":"100%","defaultValue":"","required":false,"dataType":"string","pattern":"","placeholder":"","customClass":"","disabled":false,"labelWidth":100,"isLabelWidth":false,"hidden":false,"dataBind":true,"showPassword":false,"remoteFunc":"func_1575897887618","remoteOption":"option_1575897887618"},"name":"名称","key":"1575897887618","model":"name","rules":[{"type":"string","message":"名称格式不正确"}]}],"config":{"labelWidth":100,"labelPosition":"right","size":"small","customClass":""}},
        formJson: undefined,
        temp: {
          id: undefined,
          name: '',
          key: '',
          category: '',
          description: '',
          version: '',
          latestVersion: '',
          suspended: '',
          formKey: '',
          tenantId: ''
        },
        dialogProcessDefinitionIdentityLinkVisible: false,
        selectedProcessDefinitionId: '',
        selectedProcessDefinitionName: ''
      };
    },
    created () {
      this.requestDict('流程分类');
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive () {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 表格数据源 */
      async datasource ({ page, limit }) {
        // return pageRoles({ pageNum: page, size: limit, ...where });
        const res = await getAction('/flowable/processDefinition/list', {
          current: page,
          size: limit,
          ...this.listQuery
        });

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

      btnQuery () {
        this.reload();
      },
      btnReset () {
        this.listQuery = {
          current: 1,
          size: 10,
          processDefinitionId: undefined,
          processDefinitionCategory: undefined,
          processDefinitionName: undefined,
          processDefinitionKey: undefined,
          latestVersion: true,
          suspended: false,
          active: false
        };
        this.reload();
      },
      btnView (row) {
        this.temp = Object.assign({}, row);
        this.dialogFormVisible = true;
      },
      btnViewProcessInstanceList (row) {
        this.$router.push({
          path: '/flowable/processInstance',
          query: { processDefinitionId: row.id }
        });
      },
      btnDelete (id, cascade) {
        let ids = id
          ? [id]
          : this.selectedRecords.map((record) => {
              return record.id;
            });
        if (ids.length == 0) {
          Message.error('请选择要删除的记录');
          return;
        }
        // if (ids.length > 1) {
        //   Message.error('只能选择一条记录');
        //   return;
        // }
        deleteAction('/flowable/processDefinition/delete', {
          processDefinitionId: ids.toString(),
          cascade: cascade
        }).then(({ data }) => {
          Message.success('删除' + data.message);
          this.reload();
        });
      },
      btnSuspendOrActivate (processDefinitionId, suspend) {
        let suspendOrActivate = suspend ? 'activate' : 'suspend';
        putAction('/flowable/processDefinition/' + suspendOrActivate, {
          processDefinitionId
        }).then((res) => {
          Message.success((suspend ? '激活' : '挂起') + res.data.message);
          this.reload();
        });
      },
      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/processDefinition/import', formData).then(
          ({ msg }) => {
            this.dialogImportVisible = false;
            Message.success(msg);
            this.reload();
          }
        );
      },
      btnExport (row) {
        downloadAction(
          '/flowable/processDefinition/xml',
          'get',
          { processDefinitionId: row.id },
          row.name + '-v' + row.version + '.bpmn20.xml'
        );
      },
      btnImage (processDefinitionId) {
        this.selectedProcessDefinitionId = processDefinitionId;
        this.dialogProcessImageVisible = true;
      },
      btnProcessDefinitionIdentityLink (row) {
        this.selectedProcessDefinitionId = row.id;
        this.selectedProcessDefinitionName = row.name;
        this.dialogProcessDefinitionIdentityLinkVisible = true;
      }
    }
  };
</script>
<style scoped>
  .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>
