<template>
  <task-design-view
    :processIndex="3"
    :taskTemplateName="templateName"
    @saveData="handleTitleChange">
    <div
      class="flow-wrap content"
      ref="canvas"
      :class="isErro ? 'with-error' : 'with-diagram'"
      style="padding: 30px 60px;background: #f0f2f5;">
      <div class="canvas" id="canvas"></div>
      <!--      <div class="properties-panel-parent" id="js-properties-panel"></div>-->
      <!--            <button style="position: absolute;" id="save-button" @click="exportDiagram">打印</button>-->
      <a-button style="position: fixed;right: 20px;top: 18px;z-index: 101;" @click="submitDiagram">提交</a-button>
      <!--userTask 的 Panel-->
      <div class="custom-panel" v-show="showPanel">
        <div class="element-name">
          <mt-show-input
            v-model="currentElementName"
            :placeholder="'请输入节点名称'"
            @blur="setElementName">
            <div slot="icon">
              <a-icon type="edit"/>
            </div>
          </mt-show-input>
        </div>
        <a-tabs
          defaultActiveKey="1"
          class="custom-panel-tabs"
          style="width: 550px;background-color: #ffffff;height: calc(100% - 30px)">
          <!--<a-tab-pane v-if="showCreatorTab" tab="创建人设置" key="3" forceRender>-->
          <!--  <a-card class="custom-panel-field-list" :bodyStyle="fieldListCardStyle" :bordered="false">-->
          <!--    <a-form layout="vertical">-->
          <!--      <a-form-item-->
          <!--        label="谁可以创建这个任务？">-->
          <!--        <role-select-tree-input v-model="createRolesData"></role-select-tree-input>-->
          <!--      </a-form-item>-->
          <!--    </a-form>-->
          <!--    <div class="custom-panel-btn">-->
          <!--      <a-button>取消</a-button>-->
          <!--      <a-button type="primary" @click="submitCreator" style="margin-left: 30px">保存</a-button>-->
          <!--    </div>-->
          <!--  </a-card>-->
          <!--</a-tab-pane>-->
          <a-tab-pane v-if="showApproverTab" tab="审批人设置" key="2" forceRender>
            <a-card class="custom-panel-field-list" :bodyStyle="fieldListCardStyle" :bordered="false">
              <a-form layout="vertical">
                <a-form-item>
                  <!-- <a-radio-group
                    @change="approverTypeToggle"
                    name="approverType"
                    defaultValue="1"
                    v-model="approverType">
                    <a-radio value="1">用户</a-radio>
                    <a-radio value="2">角色</a-radio>
                  </a-radio-group>-->
                  <div>角色</div>
                  <!-- <div id="user-select-tree" v-if="approverType==='1'">
                    <user-select-tree-input v-model="approver"></user-select-tree-input>
                  </div>-->
                  <!--选择角色时展示-->
                  <!--<a-select-->
                  <!--  v-if="approverType==='2'"-->
                  <!--  mode="multiple"-->
                  <!--  style="width: 100%;margin-top: 8px;"-->
                  <!--  v-model="approver"-->
                  <!--  placeholder="请选择">-->
                  <!--  <a-select-option v-for="(item, index) in roleList" :key="item.id" :value="item.id">-->
                  <!--    {{ item.name }}-->
                  <!--  </a-select-option>-->
                  <!--</a-select>-->
                  <!--  <div id="role-select-tree" v-if="approverType==='2'">-->
                  <div id="role-select-tree">
                    <role-select-tree-input v-model="approver"></role-select-tree-input>
                  </div>
                </a-form-item>
                <!--  <a-form-item
                  label="是否是审批节点">
                  <a-radio-group
                    v-model="ifApproveNode">
                    <a-radio value="0">否</a-radio>
                    <a-radio value="1">是</a-radio>
                  </a-radio-group>-->
                <!-- </a-form-item>-->
                <!--<a-form-item
                  label="是否抄送">
                  <a-radio-group
                    v-model="ifCopy">
                    <a-radio value="0">否</a-radio>
                    <a-radio value="1">是</a-radio>
                  </a-radio-group>
                </a-form-item>-->
                <!-- <a-form-item
                  label="配置按钮项">
                  <a-checkbox-group v-model="buttons">
                    <a-checkbox value="stop">终止</a-checkbox>
                    <a-checkbox value="delay">延期</a-checkbox>
                    <a-checkbox value="transfer">转交</a-checkbox>
                  </a-checkbox-group>
                </a-form-item>-->
              </a-form>
              <div class="custom-panel-btn">
                <a-button type="primary" @click="submitApprover" style="margin-left: 30px">保存</a-button>
                <!--<a-button>取消</a-button>-->
              </div>
            </a-card>
          </a-tab-pane>
          <a-tab-pane v-if="showFormFieldTab" tab="工单权限设置" key="1" style="height: 100%">
            <a-card class="custom-panel-field-list" :bodyStyle="fieldListCardStyle" :bordered="false">
              <a-list
                itemLayout="horizontal"
                :dataSource="fieldList"
              >
                <div class="list-header list-item" slot="header">
                  <div class="item itemn">控件名称</div>
                  <div class="item">
                    <div class="item-value">可编辑</div>
                    <div class="item-value">显示</div>
                    <div class="item-value">隐藏</div>
                  </div>

                </div>
                <a-list-item slot="renderItem" slot-scope="item, index">
                  <div class="list-item">
                    <div class="fieldName item itemn">{{ item.fieldNm }}</div>
                    <div class="item">
                      <a-select defaultValue="1" style="width: 120px;flex: 1" v-model="item.ifWrite">
                        <a-select-option value="1">是</a-select-option>
                        <a-select-option value="0">否</a-select-option>
                      </a-select>
                      <a-radio-group :name="item.fieldId" v-model="item.permission" :defaultValue="1" style="display: flex;flex: 0 0 59%;">
                        <!--  <a-radio class="item-value" value="0"></a-radio>-->
                        <a-radio class="item-value" value="1"></a-radio>
                        <a-radio class="item-value" value="2" style="flex: 0 0 76%"></a-radio>
                      </a-radio-group>
                    </div>
                  </div>
                </a-list-item>
              </a-list>
              <div class="custom-panel-btn">
                <a-button type="primary" @click="submitFieldList" style="margin-left: 30px">保存</a-button>
                <!--<a-button>取消</a-button>-->
              </div>

            </a-card>
          </a-tab-pane>

        </a-tabs>

      </div>
      <!--line 的 Panel-->
      <div class="custom-panel" v-show="showPanel2">
        <a-card class="custom-panel-field-list" :bordered="false">
          <a-form layout="horizontal">
            <!--<a-form-item>-->
               <!--<a-radio-group name="conditionType" defaultValue="2" v-model="conditionType">-->
                <!--<a-radio value="1">审批</a-radio>-->
                <!--<a-radio value="2">表达式</a-radio>-->
                <!--<a-radio value="3">部门</a-radio>-->
              <!--</a-radio-group>-->
            <!--</a-form-item>-->
          <!--  <div v-if="conditionType==='1'">
              <a-form-item>
                <a-radio-group name="approvalType" defaultValue="1" v-model="approvalType">
                  <a-radio value="1">通过</a-radio>
                  <a-radio value="0">驳回</a-radio>
                </a-radio-group>
              </a-form-item>
            </div>
            <div v-if="conditionType==='2'">
              <a-button :disabled="formFieldModalShow" type="primary" icon="plus" @click="showFormFieldModal"> 添加条件
              </a-button>
              <a-form-item
                v-show="formFieldModalShow"
                :label="formFieldModal.fieldNm"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }"
              >
                <a-select
                  :style="formFieldOpStyle"
                  defaultValue="<"
                  v-model="formFieldCondition.operate"
                  @change="handleOpChange"
                >
                  <a-select-option value="<">小于</a-select-option>
                  <a-select-option value="=">等于</a-select-option>
                  <a-select-option value=">">大于</a-select-option>
                  <a-select-option value=">=">大于等于</a-select-option>
                  <a-select-option value="<=">小于等于</a-select-option>
                  <a-select-option value="between">两者之间</a-select-option>
                </a-select>

                <a-input
                  v-if="!showDoubleCondition"
                  name="formFieldCondition"
                  type="number"
                  v-model="formFieldCondition.condition"
                  style="width: 180px;margin-left: 20px;"/>

                <div v-if="showDoubleCondition">
                  <a-input
                    name="formFieldCondition2"
                    type="number"
                    v-model="formFieldCondition.condition1"
                    style="width: 70px;margin-left: 20px;"/>
                  <a-select
                    defaultValue="<"
                    v-model="formFieldCondition.operate1"
                    style="width: 70px;margin-left: 10px;"
                  >
                    <a-select-option value="<"> <</a-select-option>
                    <a-select-option value="<="> <=</a-select-option>
                  </a-select>

                  <span class="formfieldname">
                    {{ formFieldModal.fieldNm }}
                  </span>

                  <a-select
                    style="width: 70px;margin-left: 0px;"
                    defaultValue="<"
                    v-model="formFieldCondition.operate2"
                  >
                    <a-select-option value="<"> <</a-select-option>
                    <a-select-option value="<="> <=</a-select-option>
                  </a-select>
                  <a-input
                    name="formFieldCondition2"
                    type="number"
                    v-model="formFieldCondition.condition2"
                    style="width: 70px;margin-left: 10px;"/>

                </div>
              </a-form-item>
            </div>-->
            <!--<div v-if="conditionType==='3'">-->
              <a-form-item style="text-align: center">
                <template>
                  <a-input placeholder="请输入表达式"  v-model="deptCondition"  style="width: 300px"/>
                </template>
              </a-form-item>
            <!--</div>-->

          </a-form>
          <div class="custom-panel-btn">
            <a-button type="primary" @click="submitCondition" style="margin-left: 30px">保存</a-button>
            <!--<a-button>取消</a-button>-->
          </div>
        </a-card>
      </div>
      <a-modal
        title="选择表单项"
        v-model="formFieldModalVisitable"
        @ok="handleFormFieldModalOk"
      >
        <a-radio-group name="formFieldModal" :defaultValue="1" v-model="formFieldModal2">
          <a-radio v-for="(item, index) in formFieldModalData" :key="index" :value="item">{{ item.fieldNm }}</a-radio>
        </a-radio-group>
      </a-modal>
    </div>
  </task-design-view>
</template>

<script>
  import { TaskDesignView } from '@/layouts';
  import mtShowInput from '@comp/mt-show-input';
  import userSelectTreeInput from '@/views/taskTemplate/taskDesign/taskFlow/component/user-select-tree-input';
  import roleSelectTreeInput from '@/views/taskTemplate/taskDesign/taskFlow/component/role-select-tree-input';
  import BpmnModeler from 'bpmn-js/lib/Modeler';
  import { mapGetters, mapActions } from 'vuex';
  // 国际化
  import customTranslate from './customTranslate/customTranslate';
  // 自定义控件
  import customControlsModule from './customControls';
  import customMenuProvider from './customMenuProvider';
  // import propertiesPanelModule from 'bpmn-js-properties-panel'
  // import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
  // import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'
  // import mybpmn from '@/assets/diagram.bpmn'
  import {
    uploadWorkFlow,
    saveApprover,
    getWorkPermissionByTemplateId,
    saveWorkPermission,
    userTree,
    getWorkTempldateField
  } from '@/api/task';
  import AFormItem from 'ant-design-vue/es/form/FormItem';

  /**
   * 格式化数据为  a-tree 可用的数据
   * @param list
   * @returns {*}
   */
  function t(list) {
    const arr = list;
    for (var i = 0; i < arr.length; i++) {
      const obj = {
        slots: {
          icon: 'folder'
        }
      };
      if (arr[i].childDeptTreeResDTOS) {
        obj.children = t(arr[i].childDeptTreeResDTOS);
      }
      arr[i].deptName && (obj.title = arr[i].deptName);
      arr[i].deptId && (obj.key = arr[i].deptId);
      arr[i].deptId && (obj.value = arr[i].deptId);
      arr[i] = obj;
    }
    return arr;
  }

  const HIGH_PRIORITY = 1500;
  export default {
    name: 'taskFlow',
    components: {
      AFormItem,
      TaskDesignView,
      mtShowInput,
      userSelectTreeInput,
      roleSelectTreeInput
    },
    computed: {
      ...mapGetters(['getFieldData', 'bpmnXml', 'workApproveList', 'fieldCondition', 'createRoles']),
      showFormFieldTab() { // 是否展示 panel 的工单权限设置Tab
        const flag = /* this.currentElementType === 'bpmn:StartEvent' || */ this.currentElementType === 'bpmn:UserTask';
        return flag;
      },
      showApproverTab() { // 是否展示 panel 的审批人设置Tab
        const flag = this.currentElementType === 'bpmn:UserTask';
        return flag;
      },
      showCreatorTab() { // 是否展示 panel 的审批人设置Tab
        const flag = this.currentElementType === 'bpmn:StartEvent';
        return flag;
      },
      showPanel() { // 是否展示 userTask 的 Panel
        return this.showApproverTab || this.showFormFieldTab;
      },
      showPanel2() { // 是否展示 line 的 Panel
        const flag = this.currentElementType === 'bpmn:SequenceFlow';
        return flag;
      },
      formFieldModalData() { // 筛选number类型的输入框
        return this.defaultFieldListData.filter((item) => {
          let data;
          if (typeof item.expand === 'string') {
            item.expand = JSON.parse(item.expand);
          }
          if (item.expand && item.expand.type) {
            data = item.expand.type;
          } else {
            data = '';
          }
          // const data = item.type || ''
          return data.toLowerCase() === 'number';
        });
      },
      formFieldOpStyle() {
        let width = '180px';
        if (this.formFieldCondition.operate === 'between') {
          width = '380px';
        }
        return {
          width,
          'margin-left': '20px'
        };
      },
      showDoubleCondition() { // 介于两者之间时显示四个输入框
        return this.formFieldCondition.operate === 'between';
      },
      formFieldModalShow() {
        if (typeof this.formFieldModal === 'object') {
          return JSON.stringify(this.formFieldModal) !== '{}';
        } else {
          return this.formFieldModal;
        }
      }
    },
    data() {
      return {
        createRolesData: [],
        modeler: null,
        container: null,
        isErro: false,
        templateId: '',
        templateName: this.$route.query.templateName,
        isEditPermission: true, // 显示element编辑框
        fieldListData: {},
        fieldList: [],
        user: '',
        fieldListCardStyle: {
          'padding-top': '0px'
        },
        currentElement: null, // 当前选中的节点id
        currentElementType: null, // 当前选中节点的类型
        currentElementName: null, // 当前选中节点的名称
        currentElementObj: null,
        userList: [], // 用户列表，在 usertask Panel 中使用
        roleList: [], // 角色列表，在 usertask Panel 中使用
        approver: [], //  审批人，可能是 user 也可能是 role
        approverSelectData: [], // 弹出层绑定数据
        defaultFieldListData: [], // 上个页面传过来的数组（未进行处理）
        approverType: '2', // 审批人类型，在 usertask Panel 中使用 // 1指定人员 2指定角色 3创建人自选 4由上级人指定 5同上级一致
        conditionType: '3', // 1：审批 | 2：表达式， 在 line 上使用
        approverData: {}, // object 类型的审批人数据，包含所有节点的数据，key（节点ID），value（审批人数据）
        ifApproveNode: '0', // 是否是审批节点，在usertask Panel中使用
        ifCopy: '0', // 是否抄送，在usertask Panel中使用
        buttons: [], // 配置按钮项，在usertask Panel中使用
        formFieldModalVisitable: false,
        approvalType: '',
        formFieldModal: '', // linePanel -> 表达式 -> 添加条件弹框选中之后的信息
        formFieldModal2: '', // linePanel -> 表达式 -> 添加条件弹框选中之后的信息
        formFieldCondition: {}, // linePanel -> 表达式 的数据
        formFieldConditionData: {}, // Object 类型的 linePanel -> 表达式 的数据
        userSelectVisible: false, // 用户选择框展示
        deptTreeData: [],
        deptCondition: ''
      };
    },
    methods: {
      ...mapActions(['saveFlowElementFormField', 'saveBpmn', 'saveApprover', 'saveWorkTemplateCreateRole', 'saveFieldCondition', 'saveNewFlowElementFormField']),

      createNewDiagram() {
        var customTranslateModule = {
          translate: ['value', customTranslate]
        };
        this.container = this.$refs.canvas;
        this.modeler = new BpmnModeler({
          container: '#canvas',
          additionalModules: [
            customTranslateModule,
            customControlsModule
          ]
          // propertiesPanel: {
          //   parent: '#js-properties-panel'
          // },
          // additionalModules: [
          //   propertiesPanelModule,
          //   propertiesProviderModule
          // ],
          // moddleExtensions: {
          //   camunda: camundaModdleDescriptor
          // }
        });
        let defaultXml = `<?xml version="1.0" encoding="UTF-8"?>
          <bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd" id="sample-diagram" targetNamespace="http://bpmn.io/schema/bpmn">
            <bpmn2:process id="p${this.templateId}" isExecutable="true">
              <bpmn2:startEvent id="StartEvent_1"/>
            </bpmn2:process>
            <bpmndi:BPMNDiagram id="BPMNDiagram_1">
              <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
                <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1">
                  <dc:Bounds height="36.0" width="36.0" x="412.0" y="240.0"/>
                </bpmndi:BPMNShape>
              </bpmndi:BPMNPlane>
            </bpmndi:BPMNDiagram>
          </bpmn2:definitions>`;
        console.log('flag', !this.bpmnXml);
        if (this.bpmnXml) { // 有数据
          defaultXml = this.bpmnXml;
        }
        console.log('defaultXml', defaultXml);
        this.openDiagram(defaultXml);
      },
      openDiagram(xml, callback) {
        this.modeler.importXML(xml, (err) => {
          if (err) {
            this.isErro = true;
            // this.container
            //   .removeClass('with-diagram')
            //   .addClass('with-error')
            this.container.getElementsByClassName('error').getElementsByTagName('pre').innerText = err.message;
            console.error(err);
          } else {
            this.isErro = false;
            // 添加时间监听
            this.elementClickHandler();
            if (callback) {
              callback();
            }
            // this.container
            //   .removeClass('with-error')
            //   .addClass('with-diagram')
          }
        });
      },
      /**
       * 打印xml.
       */
      exportDiagram() {
        this.modeler.saveXML({ format: true }, function(err, xml) {
          if (err) {
            return console.error('could not save BPMN 2.0 diagram', err);
          }

          alert('Diagram exported. Check the developer tools!');

          console.log('DIAGRAM', xml);
        });
      },
      /**
       * 提交xml.
       */
      submitDiagram() {
        const self = this;
        this.modeler.saveXML({ format: true }, function(err, xml) {
          if (err) {
            return console.error('could not save BPMN 2.0 diagram', err);
          }
          const blob = new Blob([xml],
            { type: 'application/bpmn20-xml' });
          const formData = new FormData();
          formData.append('file', blob, self.templateId + '.bpmn');
          // formData.append('file', blob, 'a.bpmn')
          formData.append('tempId', self.templateId);
          uploadWorkFlow(formData)
            .then(res => {
              console.log(res);
              self.$router.push('/taskGrouping');
            })
            .catch(err => {
              console.log(err);
            });
        });
      },
      /**
       * 添加bpmn-element click 事件
       */
      elementClickHandler() {
        const self = this;
        this.modeler.on('element.click', HIGH_PRIORITY, (event) => {
          event.originalEvent.preventDefault();
          event.originalEvent.stopPropagation();
          // qualityAssuranceEl.classList.remove('hidden');

          // ({ element } = event);
          const { element } = event;
          // console.log('elementClickHandler', element, event)
          self.currentElement = element.id;
          self.currentElementType = element.type;
          self.currentElementName = element.businessObject.name;
          self.currentElementObj = element;
          let fieldList = self.fieldListData.find((item) => item.activityId === self.currentElement);
          // 开始结点首次点击时，赋值表单数据为 可编辑0
          if (self.currentElementType === 'bpmn:StartEvent' && !fieldList) {
            // this.elementSetValue('', '');
            this.fieldListData = this.getFieldData.workTemplateField;
            fieldList = self.fieldListData.find((item) => item.activityId === self.currentElement);
          }
          // 开始结点首次点击时，赋值表单数据为 只读
          if (self.currentElementType === 'bpmn:UserTask' && !fieldList) {
            this.elementSetValue('1', '1');
            this.fieldListData = this.getFieldData.workTemplateField;
            fieldList = self.fieldListData.find((item) => item.activityId === self.currentElement);
          } else if (self.currentElementType !== 'bpmn:SequenceFlow') {
            let newData = '';
            new Promise((resolve, reject) => {
               newData = this.defaultFieldListData.map(field => {
                const item = { ...field };
                return Object.assign(item, {
                  permission: '1',
                  ifWrite: '1'
                });
              });
              resolve();
            }).then(() => {
              this.saveNewFlowElementFormField(newData).then(() => {
                fieldList = self.fieldListData.find((item) => item.activityId === self.currentElement);
                const list = fieldList
                  ? fieldList.form
                  : self.defaultFieldListData;
                self.fieldList = JSON.parse(JSON.stringify(list));
              }
            );
            });
          }
          const list = fieldList
            ? fieldList.form
            : self.defaultFieldListData;
          self.fieldList = JSON.parse(JSON.stringify(list));
          // const data = self.approverData[self.currentElement]
          const data = self.approverData.find((item) => item.activityId === self.currentElement);
          if (data) {
            if (Array.isArray(data.personData)) {
              self.approver = data.personData;
            } else {
              self.approver = data.personData.split(',');
            }
          } else {
            self.approver = [];
          }
          self.approverType = data ? data.personType : '2';
          self.ifApproveNode = data ? data.ifApproveNode : '0';
          self.ifCopy = data ? data.ifCopy : '0';
          const buttons = data ? data.buttons.split(',') : [];
          self.buttons = buttons;
          //
          const data2 = self.formFieldConditionData.find((item) => item.activityId === self.currentElement);
          self.formFieldModal = data2 ? data2.formFieldModal : {};
          self.conditionType = data2 ? data2.conditionType : '3';
          if (self.conditionType === '1') {
            console.log('conditionType', data2);
            self.approvalType = data2 ? data2.approvalType : '';
          }
          if (self.conditionType === '2') {
            self.formFieldCondition = data2 ? data2.formFieldCondition : {};
          }
          if (self.conditionType === '3') {
            self.deptCondition = data2 ? data2.deptCondition : '';
          }
        });
      },
      /**
       * 保存工单权限
       */
      submitFieldList() {
        // console.log(this.fieldList)
        const data = {
          templateId: this.templateId,
          activityId: this.currentElement,
          form: [...this.fieldList]
        };
        this.saveFlowElementFormField(data)
          .then(() => {
            this.$notification['success']({
              message: '保存成功',
              duration: 1
            });
          });
      },
      /**
       * 保存审批人信息
       */
      submitApprover() {
        const data = {
          templateId: this.templateId,
          personType: this.approverType, // 1指定人员 2指定角色 3创建人自选 4由上级人指定 5同上级一致
          activityId: this.currentElement,
          personData: this.approver,
          ifApproveNode: this.ifApproveNode,
          ifCopy: this.ifCopy,
          buttons: this.buttons.toString(),
          activityNm: this.currentElementName
        };
        this.saveApprover(data)
          .then(res => {
            // 重新获取一次
            this.approverData = this.workApproveList;

            this.$notification['success']({
              message: '保存成功',
              duration: 1
            });
          });
      },
      /**
       * 保存创建人信息
       */
      submitCreator() {
        const data = this.createRolesData;
        this.saveWorkTemplateCreateRole(data)
          .then(res => {
            this.$notification['success']({
              message: '保存成功',
              duration: 1
            });
          });
      },
      emitEmpty() {
        // this.$refs.userNameInput.focus()
        // this.user = ''
        this.approver = '';
      },
      /**
       * 根据模板主键获取模板对应流程所有节点的表单配置权限
       */
      getWorkPermissionByTemplateId() {
        const data = {
          templateId: this.templateId
          // templateId: this.templateId
        };
        getWorkPermissionByTemplateId(data)
          .then((res) => {
            const listData = res.data;
            this.fieldListData = listData;
          })
          .catch((err) => {
            console.error(err);
          });
      },
      /**
       * 根据模板主键获取模板对应流程所有节点的表单默认配置权限
       */
      getDefaultWorkPermissionByTemplateId() {
        const data = {
          templateId: this.templateId
          // templateId: this.templateId
        };
        getWorkTempldateField(data)
          .then((res) => {
            const listData = res.data;
            this.defaultFieldListData = listData;
          })
          .catch((err) => {
            console.error(err);
          });
      },
      /**
       * 父组件的上方导航条回调
       * @param val
       * @param callback
       */
      handleTitleChange(val, callback) {
        const self = this;
        this.modeler.saveXML({ format: true }, function(err, xml) {
          if (err) {
            return console.error('could not save BPMN 2.0 diagram', err);
          }
          self.saveBpmn(xml)
            .then(res => {
              console.log('res', res);
              // 跳转页面
              callback();
            })
            .catch(err => {
              console.log('err', err);
            });
        });
      },
      /**
       * 获取用户
       */
      getUserList() {
        getAllUser()
          .then(res => {
            this.userList = res.data;
          });
      },
      /**
       * 获取角色
       */
      getRoleList() {
        getAllRole()
          .then(res => {
            this.roleList = res.data[0].roles;
          });
      },
      /**
       * 审批人类型切换
       */
      approverTypeToggle(e) {
        const self = this;
        const data = self.approverData.find((item) => item.activityId === self.currentElement);
        const approverType = data && data.personType;
        self.ifApproveNode = data ? data.ifApproveNode : '0';
        self.ifCopy = data ? data.ifCopy : '0';
        const buttons = data ? data.buttons.split(',') : [];
        self.buttons = buttons;
        if (e.target.value === approverType) {
          if (data) {
            if (Array.isArray(data.personData)) {
              self.approver = data.personData;
            } else {
              self.approver = data.personData.split(',');
            }
          } else {
            self.approver = [];
          }
        } else {
          this.approver = [];
        }
      },
      handleOpChange(val) {
        if (val === 'between') {

        }
      },
      /**
       * 打开条件设置 -> 添加条件的表单选择弹框
       */
      showFormFieldModal() {
        this.formFieldModalVisitable = true;
      },
      /**
       * 打开条件设置 -> 添加条件的表单选择弹框 确定事件
       */
      handleFormFieldModalOk() {
        this.formFieldModal = this.formFieldModal2;
        this.formFieldModal2 = '';
        this.formFieldModalVisitable = false;
      },
      /**
       * line Panel 提交事件
       */
      submitCondition() {
        const data = {
          templateId: this.templateId,
          activityId: this.currentElement,
          conditionType: this.conditionType
        };
        if (this.conditionType === '1') {
          data.approvalType = this.approvalType; // 审批类型时
        }
        if (this.conditionType === '2') {
          data.formFieldCondition = this.formFieldCondition; // 表达式时：表单输入框条件
          data.formFieldModal = this.formFieldModal;
        }
        if (this.conditionType === '3') {
          data.deptCondition = this.deptCondition; // 部门时
        }
        this.saveFieldCondition(data)
          .then(res => {
            // 重新获取一次
            this.formFieldConditionData = res;

            this.$notification['success']({
              message: '保存成功',
              duration: 1
            });
          });
      },
      /**
       * 结点设置formField
       */
      elementSetValue(value, write) {
        const initData = this.defaultFieldListData.map(field => {
          const item = { ...field };
          return Object.assign(item, {
            permission: value,
            ifWrite: write
          });
        });
        const data = {
          templateId: this.templateId,
          activityId: this.currentElement,
          form: initData
        };
        this.saveFlowElementFormField(data)
          .then(() => {
            // this.$notification['success']({
            //   message: '保存成功',
            //   duration: 1
            // });
          });
      },
      /**
       * 重载xml
       */
      reloadXml() {
        const self = this;
        this.modeler.saveXML({ format: true }, function(err, xml) {
          if (err) {
            return console.error('could not save BPMN 2.0 diagram', err);
          }
          self.openDiagram(xml, function() {
            const domlist = document
              .getElementsByTagName('svg')[0]
              .getElementsByClassName('djs-group');
            let dom = null;

            for (let i = 0; i < domlist.length; i++) {
              const ele = domlist[i].getElementsByClassName(' djs-element')[0];
              // console.log(domlist[i].getElementsByClassName(' djs-element')[0].getAttribute('data-element-id'));
              if (ele.getAttribute('data-element-id') === self.currentElement) {
                dom = ele;
                break;
              }
            }
            // 触发一次dom的点击事件
            const e = document.createEvent('MouseEvents');
            e.initMouseEvent('click', true, true);
            dom.dispatchEvent(e);
          });
        });

        // dom.click()
      },
      /**
       * 修改节点名
       * @param element
       * @param name
       */
      setElementName(element, name) {
        console.log('setElement', this.currentElementObj);
        this.currentElementObj.businessObject.name = this.currentElementName;
        // 重载xml
        setTimeout(this.reloadXml(), 300);
      },
      /**
       * 展示用户选择弹出框
       */
      showUserSelectModal() {
        this.approverSelectData = this.approver;
        this.userSelectVisible = true;
      },
      handleUserSelectOk(e) {
        console.log(e);
        this.approver = this.approverSelectData;
        this.userSelectVisible = false;
      },
      /**
       * 获取部门树状列表
       * @returns {Promise<T | never>}
       */
      getUserTreeData() {
        return userTree().then(res => {
          const list = [res.data];
          const treeData = list;
          this.deptTreeData = t(treeData);
        });
      }
    },
    mounted() {
      this.templateId = this.$route.query.templateId;
      this.createRolesData = this.createRoles;
      this.createNewDiagram();
      this.fieldListData = this.getFieldData.workTemplateField;
      console.log('fieldListData', this.fieldListData);
      this.defaultFieldListData = this.getFieldData.createformData;
      console.log('defaultFieldListData', this.defaultFieldListData);
      this.approverData = this.workApproveList;
      this.formFieldConditionData = this.fieldCondition;
      this.getUserTreeData();
      // this.getUserList();
      // this.getRoleList();
      // this.getWorkPermissionByTemplateId()
      // this.getDefaultWorkPermissionByTemplateId()
    }
  };
</script>
<style lang="less" scoped>
  @import "~bpmn-js/dist/assets/diagram-js.css";
  @import "~bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
  @import "~bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css";
  .flow-wrap {
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    overflow-x: hidden;
    overflow-y: auto;
    /*padding-bottom: 30px;*/
  }

  .flow-wrap > div {
    height: 98%;
  }

  * {
    box-sizing: border-box;
  }

  a:link {
    text-decoration: none;
  }

  .content {
    position: relative;
    width: 100%;
    height: calc(100% - 60px);

    > .message {
      width: 100%;
      height: 100%;
      text-align: center;
      display: table;

      font-size: 16px;
      color: #111;

      .note {
        vertical-align: middle;
        text-align: center;
        display: table-cell;
      }

      &.error {
        .details {
          max-width: 500px;
          font-size: 12px;
          margin: 20px auto;
          text-align: left;
          color: #BD2828;
        }

        pre {
          border: solid 1px #BD2828;
          background: #fefafa;
          padding: 10px;
          color: #BD2828;
        }
      }
    }

    &:not(.with-error) .error,
    &.with-error .intro,
    &.with-diagram .intro {
      display: none;
    }

    .canvas {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

    .canvas,
    .properties-panel-parent {
      display: none;
    }

    &.with-diagram {
      .canvas,
      .properties-panel-parent {
        display: block;
      }
    }
  }

  .buttons {
    position: fixed;
    bottom: 20px;
    left: 20px;

    padding: 0;
    margin: 0;
    list-style: none;

    > li {
      display: inline-block;
      margin-right: 10px;

      > a {
        background: #DDD;
        border: solid 1px #666;
        display: inline-block;
        padding: 5px;
      }
    }

    a {
      opacity: 0.3;
    }

    a.active {
      opacity: 1.0;
    }
  }

  .properties-panel-parent {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    width: 260px;
    z-index: 10;
    border-left: 1px solid #ccc;
    overflow: auto;

    &:empty {
      display: none;
    }

    > .djs-properties-panel {
      padding-bottom: 70px;
      min-height: 100%;
    }
  }

  .custom-panel {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    /*width: 260px;*/
    z-index: 101;
    border-left: 1px solid #ccc;
    height: 100%;

    .element-name {
      background-color: #fff;
      height: 30px;
      line-height: 22px;
      display: flex;
      align-items: center;
      padding: 20px 10px;
    }

    .custom-panel-btn {
     /* position: relative;
      bottom: 20px;*/
      width: calc(100% - 50px);
      text-align: center;
    }

    .custom-panel-tabs {
      /deep/ .ant-tabs-content {
        height: calc(100% - 60px);
      }
    }

    .custom-panel-field-list {
      overflow: auto;
      height: 100%;
      width: 550px;
    }

    .list-header, .list-item {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .item {
        flex: 0 0 60%;
        display: flex;
        justify-content: space-around;

        .item-value {
          flex: 0 0 33%;
          display: flex;
          justify-content: center;
          margin-right: 0px;
        }
      }

      .itemn {
        flex: 0 0 30%;
      }
    }
  }

  .input-presuffix {
    .anticon-close-circle {
      cursor: pointer;
      color: #ccc;
      transition: color 0.3s;
      font-size: 12px;
    }

    .anticon-close-circle:hover {
      color: #999;
    }

    .anticon-close-circle:active {
      color: #666;
    }
  }

  .formfieldname {
    width: 70px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  #user-select-tree, #role-select-tree {
    margin-top: 8px;
  }

  /*#canvas /deep/ .bjs-container .bpmn-icon-user-task:after{*/
  /*  content: "用户任务";*/
  /*  font-size: 12px;*/
  /*}*/

</style>
<style lang="less">
  .bjs-powered-by,.entry.bpmn-icon-text-annotation,.entry.bpmn-icon-gateway-or,.entry.bpmn-icon-gateway-eventbased,.entry.bpmn-icon-gateway-complex,.entry.bpmn-icon-intermediate-event-none,.entry.bpmn-icon-task,.entry.bpmn-icon-subprocess-expanded,.entry.bpmn-icon-service-task,.entry.bpmn-icon-data-object,.entry.bpmn-icon-data-store,.entry.bpmn-icon-participant{
    display: none;
  }
</style>
