<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>
        <edithView v-if="showEdit2" visible-key="showEdit2" :_dataId.sync="dataId2" :serviceId.sync="serviceId2"
                   :parent-target="_self"
                   @reload="$reloadHandle"></edithView>

      </el-tab-pane>
      <el-tab-pane :label="$t1('待执行记录')" name="second">
        <div class="tree-box fl">
          <div class="tit"><b>{{ $t1('服务名') }}</b></div>
          <el-tree
            :props="defaultProps"
            :load="loadNode"
            node-key="uuid"
            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">
                    <base-table-export :option="{ title: $t1('流程待办导出'), targetRef: 'table-m1'}"
                                       :parent-target="_self"/>
                  </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="$t1('服务名')+':'">
                    <template v-slot>
                      <el-input v-model="checkNodeData.label" size="small" disabled/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('流程主题')+':'" field="name">
                    <template v-slot>
                      <el-input v-model="formData.name" size="small" clearable/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('单据类型')+':'" field="objTypeName">
                    <template v-slot>
                      <el-input
                        class="search-input"
                        max="200"
                        v-model="formData.objTypeName"
                        @clear="
                          formData.objTypeCode = null;
                          $forceUpdate();
                        "
                        v-el-readonly
                        clearable
                      >
                        <i slot="suffix" class="el-input__icon el-icon-search"
                           @click="showWfObjConfigDialog = true"></i>
                      </el-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('待执行时间')+':'">
                    <template v-slot>
                      <el-date-picker
                        v-model="formData.startToExeTime"
                        type="datetime"
                        placeholder=""
                        size="small"
                        clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="$baseStartPickerOptions(formData.endToExeTime)"
                      ></el-date-picker>
                      <span>-</span>
                      <el-date-picker
                        v-model="formData.endToExeTime"
                        type="datetime"
                        placeholder=""
                        size="small"
                        clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        default-time="23:59:59"
                        :picker-options="$baseEndPickerOptions(formData.startToExeTime)"
                      ></el-date-picker>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t1('历史记录')" name="third">
        <template v-if="showTabContent2">
          <div class="tree-box fl">
            <div class="tit"><b>{{ $t1('服务名') }}</b></div>
            <el-tree
              :props="defaultProps"
              :load="loadNode2"
              node-key="uuid"
              ref="tree2"
              highlight-current
              lazy
              :expand-on-click-node="false"
              @node-click="handleNodeClick2"
              class="tree-list"
              icon-class="el-icon-arrow-down"
            ></el-tree>
          </div>
          <label id="labBtn2" class="dilatory-box">
            <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-m2" v-bind="vxeOption2" @resizable-change="$vxeTableUtil.onColumnWitchChange"
                        @custom="$vxeTableUtil.customHandle">
                <template #form>
                  <div class="clearfix screen-btns">
                    <div class="fl">
                      <base-table-export :option="{ title: $t1('流程待办导出'), targetRef: 'table-m2'}"
                                         :parent-target="_self"/>
                    </div>
                    <div class="fr">
                      <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent2" type="text"
                                  status="primary"
                                  plain>{{ $t1('重置') }}
                      </vxe-button>
                      <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent2">
                        {{ $t1('搜索') }}
                      </vxe-button>
                    </div>
                  </div>
                  <vxe-form ref="form" class="screen-box" title-width="92px" title-align="right" :data="formData2"
                            @submit="searchEvent2" @reset="searchEvent2">
                    <vxe-form-item :title="$t1('服务名')+':'">
                      <template v-slot>
                        <el-input v-model="checkNodeData2.label" size="small" disabled/>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item :title="$t1('流程主题')+':'" field="name">
                      <template v-slot>
                        <el-input v-model="formData2.name" size="small" clearable/>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item :title="$t1('单据类型')+':'" field="objTypeName">
                      <template v-slot>
                        <el-input
                          class="search-input"
                          max="200"
                          v-model="formData2.objTypeName"
                          @clear="
                                    formData2.objTypeCode = null;
                                    $forceUpdate();
                                  "
                          v-el-readonly
                          clearable
                        >
                          <i slot="suffix" class="el-input__icon el-icon-search"
                             @click="showWfObjConfigDialog2 = true"></i>
                        </el-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item :title="$t1('处理结果')+':'" field="result">
                      <template v-slot>
                        <el-select v-model="formData2.result" clearable>
                          <el-option :value="0" :label="$t1('未处理')"></el-option>
                          <el-option :value="1" :label="$t1('处理成功')"></el-option>
                          <el-option :value="2" :label="$t1('处理失败异常')"></el-option>
                        </el-select>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item :title="$t1('待执行时间')+':'">
                      <template v-slot>
                        <el-date-picker
                          v-model="formData2.startToExeTime"
                          type="datetime"
                          placeholder=""
                          size="small"
                          clearable
                          value-format="yyyy-MM-dd HH:mm:ss"
                          :picker-options="$baseStartPickerOptions(formData2.endToExeTime)"
                        ></el-date-picker>
                        <span>-</span>
                        <el-date-picker
                          v-model="formData2.endToExeTime"
                          type="datetime"
                          placeholder=""
                          size="small"
                          clearable
                          value-format="yyyy-MM-dd HH:mm:ss"
                          default-time="23:59:59"
                          :picker-options="$baseEndPickerOptions(formData2.startToExeTime)"
                        ></el-date-picker>
                      </template>
                    </vxe-form-item>
                  </vxe-form>
                </template>
                <template #operate="{row}">
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    @click="() => {
                      openEditDialog2(row.id);
                    }"
                  >
                    <el-tooltip :enterable="false" effect="dark" :content="$t1('查看')" placement="top"
                                popper-class="tooltip-skin">
                      <i class="el-icon-edit"/>
                    </el-tooltip>
                  </a>
                </template>
              </vxe-grid>
            </div>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>
    <wfObjConfigDialog v-if="showWfObjConfigDialog" :visiable.sync="showWfObjConfigDialog" :type.sync="type"
                       @confirm="confirmInsertWfObjConfig" :multi="false"></wfObjConfigDialog>
    <wfObjConfigDialog v-if="showWfObjConfigDialog2" :visiable.sync="showWfObjConfigDialog2" :type="99"
                       @confirm="confirmInsertWfObjConfig2" :multi="false"></wfObjConfigDialog>
  </div>
</template>
<script>
import {treeScollx} from '@base/utils/global.js';
import wfObjConfigDialog from '../../../../views/user/wf/wf_obj_config/dialog.vue';
import editView from "./edit";
import edithView from "./edith";


export default {
  name: 'wf_auto_submit_data:list',
  components: {editView, edithView, wfObjConfigDialog},
  created() {
  },
  async mounted() {
    treeScollx({target: this, type: 'default'});
  },
  data() {
    return {
      activeName: 'second',
      dataId: 0,
      showEdit: false,
      dataId2: 0,
      showEdit2: false,
      vxeOption: {},
      formData: {},
      checkNode: {},
      checkNode2: {},
      defaultProps: {
        label: 'label', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      showWfObjConfigDialog: false,
      showWfObjConfigDialog2: false,
      vxeOption2: {},
      formData2: {},
      showTabContent2: false,
      serviceId: null,
      serviceId2: null,
    };
  },
  computed: {
    checkNodeData() {
      return this.checkNode && this.checkNode.data ? this.checkNode.data : {};
    },
    checkNodeData2() {
      return this.checkNode2 && this.checkNode2.data ? this.checkNode2.data : {};
    }
  },
  watch: {
    activeName(val) {
      if (val == "third" && !this.showTabContent2) {
        this.showTabContent2 = true;
        this.$nextTick(() => {
          treeScollx({target: this, type: 'default', dragBtn: '#labBtn2'});
        })
      }
    }
  },
  methods: {
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.$refs['table-m1'].commitProxy('reload');
    },

    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user-wf_auto_submit_data-m1',
        path: () => {
          let serviceId = this.serviceId;
          return "/" + serviceId + "/wf_auto_submit_data/listPage";
        },
        param: () => {
          return {
            ...this.formData
          };
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('流程名称'),
            field: 'name',
            width: 150,
            fixed: 'left'
          },
          {
            title: this.$t1('单据类型编码'),
            field: 'objTypeCode',
            width: 150
          },
          {
            title: this.$t1('启动人'),
            field: 'starterName',
            width: 150
          },
          {
            title: this.$t1('当前任务'),
            field: 'taskName',
            width: 150
          },
          {
            title: this.$t1('当前任务用户'),
            field: 'candidateNames',
            width: 150
          },
          {
            title: this.$t1('待执行时间'),
            field: 'toExeTime',
            width: 150
          },
          {
            title: this.$t1('启动时间'),
            field: 'createDate',
            width: 150
          },
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: ({row}) => {
                return [
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      this.openEditDialog(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>
                ];
              }
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    openEditDialog(id) {
      this.showEdit2 = false;
      this.$nextTick(() => {
        this.dataId = !id || typeof id == 'object' ? 0 : id;
        this.activeName = 'first';
        this.$openEditView('showEdit');
      })
    },
    openEditDialog2(id) {
      this.showEdit = false;
      this.$nextTick(() => {
        this.dataId2 = !id || typeof id == 'object' ? 0 : id;
        this.activeName = 'first';
        this.$openEditView('showEdit2');
      })
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    clearNodeClick() {

    },
    handleNodeClick(data, node, v) {
      this.formData.objTypeName = null;
      this.formData.objTypeCode = null;
      this.chooseNode(data.uuid);
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      this.$http({
        url: USER_PREFIX + `/wf_obj_config/wfServiceIds`,
        method: `post`,
        data: {},
        isLoading: true,
        modalStrictly: true,
        success: res => {
          let serviceIds = res.objx || [];
          let rows = serviceIds.map(serviceId => {
            return {
              leaf: true,
              serviceId: serviceId,
              label: serviceId,
              uuid: this.guid()
            };
          });
          resolve(rows);
          let firstUuid = rows.length > 0 ? rows[0].uuid : null;
          if (firstUuid) {
            this.$nextTick(() => {
              this.chooseNode(firstUuid)
              this.initTableList();
            })
          }
        }
      });
    },
    chooseNode(uuid) {
      if (uuid) {
        let node = this.$refs.tree.getNode(uuid);
        this.$refs.tree.setCurrentKey(node.data);
        this.checkNode = node
        this.serviceId = node.data.serviceId;
      } else {
        this.checkNode = null;
        this.serviceId = null;
      }
    },
    handleNodeClick2(data, node, v) {
      this.formData2.objTypeName = null;
      this.formData2.objTypeCode = null;
      this.chooseNode2(data.uuid);
      this.$forceUpdate();
      this.searchEvent2();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode2(node, resolve) {
      this.$http({
        url: USER_PREFIX + `/wf_obj_config/wfServiceIds`,
        method: `post`,
        data: {},
        isLoading: true,
        modalStrictly: true,
        success: res => {
          let serviceIds = res.objx || [];
          let rows = serviceIds.map(serviceId => {
            return {
              leaf: true,
              serviceId: serviceId,
              label: serviceId,
              uuid: this.guid()
            };
          });
          resolve(rows);
          let firstUuid = rows.length > 0 ? rows[0].uuid : null;
          if (firstUuid) {
            this.$nextTick(() => {
              this.chooseNode2(firstUuid)
              this.initTableList2();
            })
          }
        }
      });
    },
    chooseNode2(uuid) {
      if (uuid) {
        let node = this.$refs.tree2.getNode(uuid);
        this.$refs.tree2.setCurrentKey(node.data);
        this.checkNode2 = node
        this.serviceId2 = node.data.serviceId;
      } else {
        this.checkNode2 = null;
        this.serviceId2 = node.data.serviceId;
      }
    },
    confirmInsertWfObjConfig(rows) {
      if (rows.length) {
        let row = rows[0];
        this.$set(this.formData, 'objTypeName', row.objTypeName);
        this.$set(this.formData, 'objTypeCode', row.objTypeCode);
      }
    },
    //m2
    searchEvent2() {
      this.$refs['table-m2'].commitProxy('reload');
    },
    resetEvent2() {
      this.formData2 = {};
      this.$refs['table-m2'].commitProxy('reload');
    },
    initTableList2() {
      let that = this;
      let resultMap = {0: this.$t1('未处理'), 1: this.$t1('处理成功'), 2: this.$t1('处理失败异常')};
      let tableOption = {
        vue: this,
        tableRef: 'table-m2',
        tableName: 'user-wf_auto_submit_data-m2',
        path: () => {
          let serviceId = this.serviceId2;
          return "/" + serviceId + "/wf_auto_submit_datah/listPage";
        },
        param: () => {
          return {
            ...this.formData2
          };
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('流程名称'),
            field: 'name',
            width: 150,
            fixed: 'left'
          },
          {
            title: this.$t1('单据类型编码'),
            field: 'objTypeCode',
            width: 150
          },
          {
            title: this.$t1('启动人'),
            field: 'starterName',
            width: 150
          },
          {
            title: this.$t1('当前任务'),
            field: 'taskName',
            width: 150
          },
          {
            title: this.$t1('当前任务用户'),
            field: 'candidateNames',
            width: 150
          },
          {
            title: this.$t1('待执行时间'),
            field: 'toExeTime',
            width: 150
          },
          {
            title: this.$t1('处理结果'),
            field: 'result',
            width: 150,
            slots: {
              default: ({row}) => {
                return resultMap[row.result] || null;
              }
            }
          },
          {
            title: this.$t1('处理结果描述'),
            field: 'resultDesc',
            width: 150
          },
          {
            title: this.$t1('启动时间'),
            field: 'createDate',
            width: 150
          },
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: "operate"
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption2 = opts;
      });
    },
    confirmInsertWfObjConfig2(rows) {
      if (rows.length) {
        let row = rows[0];
        this.$set(this.formData2, 'objTypeName', row.objTypeName);
        this.$set(this.formData2, 'objTypeCode', row.objTypeCode);
      }
    },
    initWfServiceIds() {
      return this.$http({
        url: USER_PREFIX + `/wf_obj_config/wfServiceIds`,
        method: `post`,
        data: {},
        isLoading: true,
        modalStrictly: true,
        success: res => {
          this.serviceIds = res.objx || [];
        }
      });
    },
    resubmit(row) {
      this.$baseConfirm(this.$t1('您确定要重推吗？')).then(() => {
        var url = "/" + this.serviceId2 + `/wf_auto_submit_datah/resubmit`;
        this.$http({
          url: url,
          method: `post`,
          data: row,
          isLoading: true,
          success: res => {
            this.$message({
              message: res.content,
              type: 'success',
              duration: 2000
            });
            this.$nextTick(() => {
              this.searchEvent2()
            })
          }
        });
      });
    }
  }
};
</script>
