<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane :label="$t1('常规')" name="first">
        <editView v-if="showEdit" visible-key="showEdit" :_dataId.sync="dataId" :parent-target="_self"
                  @reload="$reloadHandle"></editView>
      </el-tab-pane>
      <el-tab-pane :label="$t1('列表')" name="second">
        <div class="tree-box fl">
          <div class="tit" @click="clearNodeClick"><b>表单类型</b></div>
          <div class="tree-btns" style="margin-top: 10px;">
            <el-button type="primary" plain icon="el-icon-circle-plus-outline" class="btn" @click="addFormType()">{{ $t1('新增') }}
            </el-button>
            <el-button type="primary" plain icon="el-icon-edit-outline" class="btn" @click="editFormType()"
                       :disabled="!currentFormType">编辑
            </el-button>
          </div>
          <el-tree
            :props="defaultProps"
            :load="loadNode"
            node-key="id"
            ref="tree"
            highlight-current
            lazy
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            class="tree-list"
            icon-class="el-icon-arrow-down"
          ></el-tree>
        </div>
        <label id="labBtn">
          <div class="icon">
            <i class="el-icon-more"></i>
            <i class="el-icon-more"></i>
          </div>
        </label>
        <div class="main-right fr" style="padding-left:6px;">
          <div class="grid-height">
            <vxe-grid
              ref="table-m1"
              v-bind="vxeOption"
              @resizable-change="$vxeTableUtil.onColumnWitchChange"
              @custom="$vxeTableUtil.customHandle"
            >
              <template #form>
                <div class="clearfix screen-btns">
                  <div class="fl">
                    <vxe-button status="primary" class="button-sty" icon="el-icon-plus" @click="openEditDialog">{{ $t1('新增') }}
                    </vxe-button>
                    <base-table-export :option="{ title: '报表模板导出', targetRef: 'table-m1'}"
                                       :parent-target="_self"/>
                    <!-- <vxe-button status="primary" class="button-sty" icon="el-icon-download" @click="importExcel">导入</vxe-button> -->
                  </div>
                  <div class="fr">
                    <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent" type="text" status="primary"
                                plain>{{$t1('重置')}}
                    </vxe-button>
                    <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent">{{ $t1('搜索') }}
                    </vxe-button>
                  </div>
                </div>
                <vxe-form ref="form" class="screen-box" title-width="92px" title-align="right" :data="formData"
                          @submit="searchEvent" @reset="searchEvent">
                  <vxe-form-item title="表单类型:" field="formTypeCode">
                    <template v-slot>
                      <el-input v-model="formData.formTypeName" size="small" disabled/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="模板名称:" field="formName">
                    <template v-slot>
                      <el-input v-model="formData.formName" size="small" clearable/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="模板编码:" field="formCode">
                    <template v-slot>
                      <el-input v-model="formData.formCode" size="small" clearable/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="模板版本:" field="formVersion">
                    <template v-slot>
                      <base-input-number v-model="formData.formVersion"/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="是否启用:" field="enabled">
                    <template v-slot>
                      <el-select v-model="formData.enabled" clearable>
                        <el-option :value="true" label="启用"></el-option>
                        <el-option :value="false" label="禁用"></el-option>
                      </el-select>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-grid>
            <el-drawer title="流程模板" :visible.sync="showItemView" :modal="false" :wrapperClosable="false"
                       :destroy-on-close="true" size="90%" direction="btt">
              <itemList v-if="showItemView" :formTemplate="currentRow" :formCode="currentRow.formCode"
                        :formName="currentRow.formName" @openWfDesignDialog="openWfDesignDialog"></itemList>
            </el-drawer>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      title="流程设计"
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      v-if="showWfDialog"
      :visible.sync="showWfDialog"
      :modal="false"
      custom-class="dialog-style designer-dialog"
      width="100%"
      height="100%"
      top="0px"
      bottom="0px"
      :before-close="closeDesignwinEvent"
      :destroy-on-close="true"
      v-el-drag-dialog
    >
      <iframe :src="wfUrl" :style="'width:100%;height:' + ($root.$el.clientHeight - 30 - 12) + 'px'"></iframe>
    </el-dialog>

    <el-dialog
      title="表单设计"
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      v-if="showDesingerDialog"
      :visible.sync="showDesingerDialog"
      :modal="false"
      custom-class="dialog-style designer-dialog"
      width="100%"
      height="100%"
      top="0px"
      bottom="0px"
      :before-close="closeFormDesignwinEvent"
      :destroy-on-close="true"
      v-el-drag-dialog
    >
      <designer ref="designer" :formCode.sync="formCode"></designer>
    </el-dialog>

    <userDialog v-if="showUserDialog" :visiable.sync="showUserDialog" @confirm="confirmUser"
                :multi.sync="wfAssignMulti"/>
    <positionDialog v-if="showPositionDialog" :visiable.sync="showPositionDialog" @confirm="confirmPosition"/>
    <scriptDescriptionDialog path="static/readme/Wf.txt" v-if="showScriptDescriptionDialog"
                             :visiable.sync="showScriptDescriptionDialog"></scriptDescriptionDialog>

    <formTypeEditDialog v-if="showFormTypeDialog" :visiable.sync="showFormTypeDialog" :_dataId.sync="editFormTypeId"
                        @confirm="confirmFormTypeEditDialog"></formTypeEditDialog>
  </div>
</template>

<script>
import {treeScollx} from '@base/utils/global.js';
import editView from './edit.vue';

import userDialog from '../../../../views/user/user/dialog.vue';
import positionDialog from '../../../../views/user/position/dialog.vue';
import scriptDescriptionDialog from '@base/components/scriptDescription/dialog'

// import designer from '../../../../views/user/form/vform/designer.vue';
import itemList from "./itemList";
import formTypeEditDialog from "../../../../views/user/form/form_type/editDialog";

export default {
  name: 'form_template:list',
  components: {
    editView,
    userDialog,
    positionDialog,
    scriptDescriptionDialog,
    itemList,
    formTypeEditDialog,
    designer: () => import('../../../../views/user/form/vform/designer.vue')
  },
  data() {
    return {
      activeName: 'second',
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {},
      showDesingerDialog: false,
      formCode: null,
      templateId: null,

      showItemEdit: false,
      showParamEdit: false,
      vxeOption1: {},
      editId: '',
      itemEditId: '',
      pRow: null,
      currentRow: {},
      serviceId: null,
      itemServiceId: null,

      showWfDialog: false,
      wfUrl: '',
      ph: '',
      dialogActiveName: 'first',
      showFunctionScriptList: false,
      showUserDialog: false,
      wfAssignData: [],
      wfAssignCallback: null,
      wfAssignMulti: true,

      showPositionDialog: false,
      wfAssignPositionData: [],
      wfAssignPositionCallback: null,

      showFormTemplateDialog: false,
      wfAssignFormTemplateCallback: null,

      showScriptDescriptionDialog: false,
      showWfDiyAttributeEdit: false,

      defaultProps: {
        label: 'formTypeName', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      showItemView: false,

      currentFormType: null,
      editFormTypeId: null,
      showFormTypeDialog: false
    };
  },
  mounted() {
    treeScollx({target: this, type: 'default'});
    this.initTableList();
    this.initWfWinParam();
  },
  methods: {
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.currentFormType = null;
      this.$refs.tree.setCurrentKey();
      this.$refs['table-m1'].commitProxy('reload');
    },
    openEditDialog(id) {
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      this.activeName = 'first';
      this.showItemEdit = false;
      this.$openEditView('showEdit');
    },
    openDesingerDialog(row) {
      this.formCode = row.formCode;
      this.showDesingerDialog = true;
    },
    closeFormDesignwinEvent(done) {
      this.$baseConfirm('请确认"已保存"报表模板，是否继续关闭？').then(() => {
        done && done();
      });
    },
    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_form_template_list-m1',
        path: USER_PREFIX + '/form_template/listPage',
        param: () => {
          return {
            ...this.formData,
            history: false
          };
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: '模板名称',
            field: 'formName',
            width: 150,
            fixed: 'left'
          },
          {
            title: '模板编码',
            field: 'formCode',
            width: 150
          },
          {
            title: '模板版本',
            field: 'formVersion',
            width: 150
          },
          {
            title: '表单类型',
            field: 'formTypeName',
            width: 150,
          },
          {
            title: this.$t1('是否启用'),
            field: 'enabled',
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.enabled) {
                  return [
                    <div class="txt-status">
                      <span>启用</span>
                    </div>
                  ];
                } else {
                  return [
                    <div class="txt-status disable">
                      <span>禁用</span>
                    </div>
                  ];
                }
              }
            }
          },
          {
            title: this.$t1('备注'),
            field: 'remark',
            width: 150
          },
          {
            title: this.$t1('创建时间'),
            field: 'createDate',
            width: 150
          },
          {
            width: 300,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: ({row}) => {
                return [
                  <div>
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={() => {
                        this.openEditDialog(row.formCode);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={ this.$t1('查看') } placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-edit"/>
                      </el-tooltip>
                    </a>
                    <a
                      href="javascript:void(0);"
                      onClick={() => {
                        this.openDesingerDialog(row);
                      }}
                      class="a-link"
                    >
                      <el-tooltip enterable={false} effect="dark" content="表单设计" placement="top"
                                  popper-class="tooltip-skin">
                        <i class="iconfont icon-liuchengguanli-shejiqi_liucheng"/>
                      </el-tooltip>
                    </a>
                    <a
                      href="javascript:void(0);"
                      onClick={() => {
                        this.chooseCellM1(row);
                      }}
                      class="a-link"
                    >
                      <el-tooltip enterable={false} effect="dark" content="查看流程模板" placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-edit"/>
                        <span>查看流程模板</span>
                      </el-tooltip>
                    </a>
                  </div>
                ];
              }
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    chooseCellM1(row) {
      this.currentRow = row;
      this.showItemView = true;
    },
    openWfDesignDialog(actModelId) {
      //wfType 0:单据流程，1：场景流程
      let serviceId = this.currentRow.serviceId;
      this.wfUrl = WEB_PREFIX + '/activiti-explorer/modeler.html?wfType=0&serviceId=' + 'user' + '&modelId=' + actModelId;
      this.dialogActiveName = 'first';
      this.showWfDialog = true;
    },
    closeDesignwinEvent(done) {
      this.$baseConfirm('请确认"已保存"流程模板，是否继续关闭？').then(() => {
        this.showWfDialog = false;
        // this.showDesingerDialog = false;
      });
    },
    initWfWinParam() {
      this.initCloseWfDesignWin();
      this.initWinUserDialog();
      this.initWinPositionDialog();
      this.initSysParamForWf();
      this.initWinFormTemplateDialog();
      this.initWinScriptDescriptionDialog();
    },
    initCloseWfDesignWin() {
      window.closeWfDesignWin = () => {
        this.showWfDialog = false;
      };
    },
    initWinUserDialog() {
      window.openAssignUserDialog = opts => {
        this.wfAssignMulti = opts.multi;
        this.wfAssignData = opts.data || [];
        this.wfAssignCallback = opts.callback;
        this.showUserDialog = true;
      };
    },
    confirmUser(rows) {
      this.wfAssignCallback(rows);
    },
    initWinPositionDialog() {
      window.openAssignPositionDialog = opts => {
        this.wfAssignPositionData = opts.data || [];
        this.wfAssignPositionCallback = opts.callback;
        this.showPositionDialog = true;
      };
    },
    initSysParamForWf() {
      let webPrefix = WEB_PREFIX;
      let baseApi = process.env.VUE_APP_BASE_API;
      window.sysParamForWf = {
        webPrefix,
        baseApi
      }
    },
    confirmPosition(rows) {
      this.wfAssignPositionCallback(rows);
    },
    initWinFormTemplateDialog() {
      window.openAssignFormTemplateDialog = opts => {
        this.wfAssignFormTemplateCallback = opts.callback;
        this.showFormTemplateDialog = true;
      };
    },
    confirmFormTemplate(rows) {
      this.wfAssignFormTemplateCallback(rows);
    },
    initWinScriptDescriptionDialog() {
      window.openScriptDescriptionDialog = opts => {
        this.showScriptDescriptionDialog = true;
      };
    },
    clearNodeClick() {
      this.formData.formTypeCode = null;
      this.formData.formTypeName = null;
      this.currentFormType = null;
      this.$refs.tree.setCurrentKey();
      this.searchEvent();
    },
    handleNodeClick(data, node, v) {
      this.$set(this.formData, 'formTypeCode', data.formTypeCode);
      this.$set(this.formData, 'formTypeName', data.formTypeName);
      this.currentFormType = data;
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      let url = USER_PREFIX + '/form_type/listPage';
      this.$http({
        url: url,
        method: 'post',
        data: {},
        success: res => {
          let records = res.objx && res.objx.records ? res.objx.records : [];
          records.forEach(value => {
            value.leaf = true;
          });
          resolve(records);
        }
      });
    },
    addFormType() {
      this.editFormTypeId = null;
      this.currentFormType = null;
      this.showFormTypeDialog = true;
    },
    editFormType() {
      let row = this.currentFormType;
      this.editFormTypeId = row.id;
      this.showFormTypeDialog = true;
    },
    confirmFormTypeEditDialog(row) {
      row.leaf = true;
      let editFormTypeId = this.editFormTypeId;
      if (!editFormTypeId) {
        this.$refs.tree.append(row);
      } else {
        let node = this.$refs.tree.getNode(row.id + "");
        node.data = row;
      }
    }
  }
};
</script>
