<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" :serviceId.sync="serviceId"
                  :parent-target="_self" @reload="$reloadHandle"></editView>
        <itemEditView
          v-if="showItemEdit"
          visible-key="showItemEdit"
          :_dataId.sync="itemEditId"
          :serviceId.sync="itemServiceId"
          :wfObjConfig.sync="pRow"
          :parent-target="_self"
          @reload="$reloadHandle"
        ></itemEditView>
      </el-tab-pane>
      <el-tab-pane :label="$t1('流程配置列表')" name="second">
        <div class="grid-height">
          <div style="height: 345px;">
            <vxe-grid
              ref="table-m1"
              :auto-resize="true"
              v-bind="vxeOption"
              @resizable-change="$vxeTableUtil.onColumnWitchChange"
              @custom="$vxeTableUtil.customHandle"
              @checkbox-change="chooseCellM1"
              class="is-pointer"
            >
              <template #form>
                <div style="margin-bottom: 8px;" class="clearfix">
                  <div class="fl">
                    <vxe-button status="primary" class="button-sty" icon="el-icon-plus" @click="openEditDialog">
                      {{ $t1('新增单据') }}
                    </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" :data-form="formData" title-width="92px" title-align="right"
                          @submit="searchEvent" @reset="searchEvent">
                  <vxe-form-item :title="$t1('单据类型名称')+':'" field="objTypeName">
                    <template v-slot="">
                      <el-input v-model="formData.objTypeName" size="small" clearable/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('单据类型编号')+':'" field="objTypeCode">
                    <template v-slot="">
                      <el-input v-model="formData.objTypeCode" size="small" clearable/>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-grid>
          </div>
          <label id="labBtn" class="transverse">
            <div class="icon">
              <i class="el-icon-more"></i>
              <i class="el-icon-more"></i>
            </div>
          </label>
          <div style="height: calc(100vh - 345px - 105px);">
            <vxe-grid ref="table-m2" v-bind="vxeOption1" @resizable-change="$vxeTableUtil.onColumnWitchChange"
                      @custom="$vxeTableUtil.customHandle">
              <template #row_edit>
                <a href="#" class="a-link"><i class="el-icon-edit"/></a>
              </template>
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t1('待办列表字段名扩展')" name="third">
        <wfParamEdit v-if="showParamEdit" visible-key="showParamEdit"
                     :parent-target="_self" @reload="$reloadHandle"></wfParamEdit>
      </el-tab-pane>
      <el-tab-pane :label="$t1('自定义流程操作属性')" name="fourth">
        <wfDiyAttributeEdit v-if="showWfDiyAttributeEdit" visible-key="showWfDiyAttributeEdit"
                            :parent-target="_self" @reload="$reloadHandle"></wfDiyAttributeEdit>
      </el-tab-pane>

    </el-tabs>

    <el-dialog
      :title="$t1('流程设计')"
      :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>

    <userDialog v-if="showUserDialog" :visiable.sync="showUserDialog" @confirm="confirmUser"
                :multi.sync="wfAssignMulti"/>
    <positionDialog v-if="showPositionDialog" :visiable.sync="showPositionDialog" :rows="wfAssignPositionData" @confirm="confirmPosition"/>
    <scriptDescriptionDialog path="static/readme/Wf.txt" v-if="showScriptDescriptionDialog"
                             :visiable.sync="showScriptDescriptionDialog"></scriptDescriptionDialog>
    <wfBizDataSettingDialog v-if="showWfBizDataSettingDialog" :visiable.sync="showWfBizDataSettingDialog"
                            @confirm="confirmWfBizDataSettingDialog"
                            :objConfigItem="objConfigItem" :serviceId="currentRow.serviceId"></wfBizDataSettingDialog>

    <importItemDialog v-if="showImportItemDialog" :visiable.sync="showImportItemDialog" @confirm="confirmImportItemDialog"/>
  </div>
</template>
<script>
import {treeScolly} from '@base/utils/global.js';
import editView from './edit.vue';
import itemEditView from './itemEdit.vue';

import userDialog from '../../../../views/user/user/dialog.vue';
import positionDialog from '../../../../views/user/position/dialog.vue';

import wfParamEdit from '../../../../views/user/wf/wf_param/edit'
import scriptDescriptionDialog from '@base/components/scriptDescription/dialog'
import wfDiyAttributeEdit from '../../../../views/user/wf/wf_diy_attribute/edit'
import wfBizDataSettingDialog from "./wfBizDataSettingDialog";

import importItemDialog from "./importItemDialog.vue";



export default {
  name: 'wf_obj_config:list',
  components: {
    editView,
    itemEditView,
    wfParamEdit,
    userDialog,
    positionDialog,
    scriptDescriptionDialog,
    wfDiyAttributeEdit,
    wfBizDataSettingDialog,
    importItemDialog
  },
  created() {
  },
  mounted() {
    treeScolly({target: this, type: 'default'});
    this.initTableList();
    this.initTableM2();

    this.ph = this.$root.$el.clientHeight;
    this.initWfWinParam();
  },
  data() {
    return {
      dataId: 0,
      showEdit: false,
      showItemEdit: false,
      showParamEdit: false,
      vxeOption: {},
      vxeOption1: {},
      formData: {},
      editId: '',
      itemEditId: '',
      pRow: null,
      activeName: 'second',
      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,

      objConfigItem: null,
      showWfBizDataSettingDialog: false,
      showImportItemDialog:false
    };
  },
  watch: {
    dialogActiveName(val) {
      if (val == 'second') {
        this.showFunctionScriptList = true;
      }
    },
    activeName(val) {
      if (val == 'third' && !this.showParamEdit) {
        this.showParamEdit = true;
      } else if (val == 'fourth' && !this.showWfDiyAttributeEdit) {
        this.showWfDiyAttributeEdit = true;
      }
    }
  },
  methods: {
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
      this.chooseCellM1({row: {}});
    },
    resetEvent() {
      this.formData = {};
      this.$refs['table-m1'].commitProxy('reload');
    },
    openEditDialog(id, serviceId) {
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      this.serviceId = serviceId || '';
      this.activeName = 'first';
      this.showItemEdit = false;
      this.$openEditView('showEdit');
    },
    openEditItemDialog(id, currentRow) {
      if (id) {
        this.pRow = null;
        this.itemEditId = id;
        this.itemServiceId = this.currentRow.serviceId;
        this.activeName = 'first';
        this.showEdit = false;
        this.$openEditView('showItemEdit');
      } else if (currentRow) {
        if (currentRow && currentRow.id) {
          this.pRow = currentRow;
          this.itemEditId = '';
          this.itemServiceId = currentRow.serviceId;
          this.activeName = 'first';
          this.showEdit = false;
          this.$openEditView('showItemEdit');
        }
      }
    },
    initTableList() {
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_wf_obj_config_list-m1',
        path: USER_PREFIX + '/wf_obj_config/listPage',
        param: () => {
          return this.formData;
        },
        config: {
          checkboxConfig: {
            checkStrictly: true,
            showHeader: false,
            trigger: 'row'
          },
          pagerConfig: {
            autoHidden: true
          }
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('单据类型名称'),
            field: 'objTypeName',
            width: 150,
            fixed: 'left'
          },
          {
            title: this.$t1('单据类型编号'),
            field: 'objTypeCode',
            width: 150
          },
          {
            title: this.$t1('跳转url'),
            field: 'url',
            width: 150
          },
          {
            title: this.$t1('移动端url'),
            field: 'mobileUrl',
            width: 150
          },
          {
            title: this.$t1('服务名'),
            field: 'serviceId',
            width: 150
          },
          {
            field: 'note',
            title: this.$t1('备注'),
            width: 150
          },

          {
            field: 'forms',
            title: this.$t1('是否表单'),
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.forms) {
                  return [<div class="txt-status">{this.$t1('是')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('否')}</div>];
                }
              }
            }
          },
          {
            field: 'createDate',
            title: this.$t1('创建时间'),
            width: 200
          },
          {
            width: 180,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: ({row}) => {
                return [
                  <div>
                    <a
                      class="a-link"
                      onclick={event => {
                        event.stopPropagation();
                        this.openEditItemDialog('', row);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={this.$t1('新增流程模板')} placement="top"
                                  popper-class="tooltip-skin">
                        <div>
                          <i class="el-icon-circle-plus-outline"/>
                          <span>{this.$t1('新增流程模板')}</span>
                        </div>
                      </el-tooltip>
                    </a>
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={event => {
                        event.stopPropagation();
                        this.openEditDialog(row.id, row.serviceId);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={this.$t1('查看')} placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-edit"/>
                      </el-tooltip>
                    </a>
                  </div>
                ];
              }
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    initTableM2() {
      let startModeMap = {
        1: this.$t1('节点无候选人，提示异常'),
        2: this.$t1('节点无候选人，提示警告'),
        3: this.$t1('节点无候选人，无提示'),
      }
      var that = this;
      let tableOption1 = {
        vue: that,
        tableRef: 'table-m2',
        tableName: 'user_wf_obj_config_item_list-m2',
        config: {
          maxHeight: ''
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('流程模版名称'),
            field: 'modelName',
            width: 150,
            fixed: 'left'
          },
          {
            title: this.$t1('序号'),
            field: 'orders',
            width: 150
          },
          {
            title: this.$t1('流程模版KEY'),
            field: 'modelKey',
            width: 150
          },
          {
            title: this.$t1('单据类型编码'),
            field: 'objTypeCode',
            width: 150
          },
          {
            field: 'enabled',
            title: this.$t1('是否启用'),
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.enabled) {
                  return [<div class="txt-status">{this.$t1('启用')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('禁用')}</div>];
                }
              }
            }
          },
          {
            title: this.$t1('跳过相邻任务'),
            field: 'skipAdjacentTask',
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.skipAdjacentTask) {
                  return [<div class="txt-status">{this.$t1('是')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('否')}</div>];
                }
              }
            }
          },
          {
            title: this.$t1('驳回后提交模式'),
            field: 'toRejectNode',
            width: 180,
            slots: {
              default: ({row}) => {
                if (row.toNextNode === 1) {
                  return [<div class="txt-status">{this.$t1('顺延下一步提交')}</div>];
                } else if (row.toRejectNode) {
                  return [<div class="txt-status">{this.$t1('由提交人确定节点提交')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('直接提交到驳回节点')}</div>];
                }
              }
            }
          },
          {
            title: this.$t1('流程启动处理'),
            field: 'startMode',
            width: 180,
            slots: {
              default: ({row}) => {
                return startModeMap[row.startMode] || '';
              }
            }
          },
          {
            title: this.$t1('跨任务跳过'),
            field: 'skipSameUserTask',
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.skipSameUserTask) {
                  return [<div class="txt-status">{this.$t1('是')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('否')}</div>];
                }
              }
            }
          },
          {
            title: this.$t1('是否允许流程启动更改候选人'),
            field: 'startNoSetCandidate',
            width: 230,
            slots: {
              default: ({row}) => {
                if (row.startNoSetCandidate) {
                  return [<div class="txt-status">{this.$t1('否')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('是')}</div>];
                }
              }
            }
          },
          {
            field: 'createDate',
            title: this.$t1('创建时间'),
            width: 200
          },
          {
            width: 200,
            fixed: 'right',
            sortable: false,
            title: '',
            slots: {
              default: ({row}) => {
                return [
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      this.openEditItemDialog(row.id);
                    }}
                  >
                    <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.wfEdit(row.modelId, this.currentRow.serviceId);
                    }}
                    class="a-link"
                  >
                    <el-tooltip enterable={false} effect="dark" content={this.$t1('流程设计')} placement="top"
                                popper-class="tooltip-skin">
                      <i class="iconfont icon-liuchengguanli-shejiqi_liucheng"/>
                    </el-tooltip>
                  </a>,
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      this.exportWfXml(row);
                    }}
                  >
                    <el-tooltip enterable={false} effect="dark" content={this.$t1('导出')} placement="top"
                                popper-class="tooltip-skin">
                      <i class="el-icon-upload2"/>
                    </el-tooltip>
                  </a>,
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      this.importWfXml(row);
                    }}
                  >
                    <el-tooltip enterable={false} effect="dark" content={this.$t1('导入')} placement="top"
                                popper-class="tooltip-skin">
                      <i class="el-icon-download"/>
                    </el-tooltip>
                  </a>,
                ];
              }
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption1).then(opts => {
        that.vxeOption1 = opts;
      });
    },
    chooseCellM1({row}) {
      if (row && row.id) {
        let $table1 = this.$refs['table-m1'];
        this.$nextTick(() => {
          $table1.clearCheckboxRow();
          $table1.setCheckboxRow(row, true);
        });
        this.currentRow = row;
        this.$http({
          method: 'post',
          url: '/' + row.serviceId + '/wf_obj_config_item/list',
          data: {objConfigId: row.id || ''},
          success: res => {
            let rows = res.objx || [];
            /* rows.forEach(function(item) {
							item.name = row.name;
						}); */
            this.$refs['table-m2'].loadData(rows);
          }
        });
      } else {
        this.$refs['table-m2'].loadData([]);
      }
    },

    wfEdit(actModelId, serviceId) {
      //wfType 0:单据流程，1：场景流程
      this.wfUrl = WEB_PREFIX + '/activiti-explorer/modeler.html?wfType=0&serviceId=' + serviceId + '&modelId=' + actModelId;
      this.dialogActiveName = 'first';
      this.showWfDialog = true;
    },
    closeDesignwinEvent(done) {
      this.$baseConfirm(this.$t1('请确认"已保存"流程模板，是否继续关闭？')).then(() => {
        this.showWfDialog = 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);
    },
    deleteItem(row) {
      this.$baseConfirm(this.$t1('您确定要删除吗？')).then(() => {
        this.$http({
          method: 'post',
          url: '/' + this.currentRow.serviceId + '/wf_obj_config_item/delete',
          data: {id: row.id},
          success: res => {
            this.$message({
              message: res.content,
              type: 'success',
              duration: 500,
            });
            this.$refs['table-m2'].remove(row);
          }
        });
      });
    },
    initWinFormTemplateDialog() {
      window.openAssignFormTemplateDialog = opts => {
        this.wfAssignFormTemplateCallback = opts.callback;
        this.showFormTemplateDialog = true;
      };
    },
    confirmFormTemplate(rows) {
      this.wfAssignFormTemplateCallback(rows);
    },
    initWinScriptDescriptionDialog() {
      window.openScriptDescriptionDialog = opts => {
        this.showScriptDescriptionDialog = true;
      };
    },
    openWfBizDataSettingDialog(row) {
      this.objConfigItem = row;
      this.showWfBizDataSettingDialog = true
    },
    confirmWfBizDataSettingDialog(rows) {

    },
     saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var link = document.createElement("a");
        var body = document.querySelector("body");

        link.href = window.URL.createObjectURL(blob);
        link.download = filename;

        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);

        link.click();
        body.removeChild(link);

        window.URL.revokeObjectURL(link.href);
      }
    },
    exportWfXml(row){
      this.$baseConfirm(this.$t1('您确定要导出吗？')).then(() => {
        this.$http({
          url: '/' + this.currentRow.serviceId + '/wf_obj_config_item/exportModelXml',
          method: `post`,
          data: {
            stringOne:row.modelId
          },
          isLoading: true,
          responseType: "blob",
          resultType: "other",
          callback: res => {
            let fileName = row.modelName + ".bpmn20.xml"
            this.saveAs(res,fileName)
          }
        });
      });
    },
    importWfXml(row){
      this.importXmlRow = row;
      this.showImportItemDialog = true;
    },
    confirmImportItemDialog(file){
      var form = new FormData();
      // 文件对象
      form.append("file", file);
      form.append("modelId", this.importXmlRow.modelId);
      this.$http({
        url: '/' + this.currentRow.serviceId + '/wf_obj_config_item/importProcess',
        method: `post`,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: form,
        isLoading: true,
        success: res => {
          this.$message({
            message: res.content,
            type: 'success',
            duration: 2000,
            onClose: t => {

            }
          });
        }
      });
    }
  }
};
</script>
