<template>
  <div>
    <div class="container-fluid">
      <div class="row m-row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <input
            v-model="taskQueryParam.condition"
            autocomplete="off"
            type="text"
            :placeholder="$t('lang.MyApplyWorkflow.describe1')"
            class="form-control"
          />
        </div>
      </div>

      <div
        v-if="taskQueryParam.advancedQuery"
        class="row m-row"
      >
        <div class="col-md-2 col-sm-2 col-xs-4">
          <label class="form-control-static">{{ $t("lang.MyApplyWorkflow.startTime") }}</label>
        </div>

        <div class="col-md-5 col-sm-5 col-xs-4">
          <DateTime
            v-model="startAfter"
          />
        </div>

        <div class="col-md-5 col-sm-5 col-xs-4">
          <DateTime
            v-model="startBefore"
          />
        </div>
      </div>

      <div
        v-if="taskQueryParam.advancedQuery"
        class="row m-row"
      >
        <div class="col-md-2 col-sm-2 col-xs-4">
          <label class="form-control-static">{{ $t("lang.MyApplyWorkflow.completionTime") }}</label>
        </div>

        <div class="col-md-5 col-sm-5 col-xs-4">
          <DateTime
            v-model="finishAfter"
          />
        </div>

        <div class="col-md-5 col-sm-5 col-xs-4">
          <DateTime
            v-model="finishBefore"
          />
        </div>
      </div>

      <div
        v-if="taskQueryParam.advancedQuery"
        class="row m-row"
      >
        <div class="col-md-2 col-sm-2 col-xs-4">
          <label class="form-control-static">{{ $t("lang.MyApplyWorkflow.approvalOriginator") }}</label>
        </div>
        <div class="col-md-10 col-sm-10 col-xs-8">
          <input
            id="applyUser"
            v-model="userName"
            autocomplete="off"
            type="text"
            class="form-control"
          />
        </div>
      </div>

      <div class="row m-row">
        <div class="col-md-2 col-sm-2 col-xs-4">
          <label class="form-control-static">{{ $t("lang.MyApplyWorkflow.subject") }}</label>
        </div>
        <div class="col-md-10 col-sm-10 col-xs-8">
          <select
            v-model="deploymentId"
            class="form-control"
          >
            <option value="">{{ $t("lang.MyApplyWorkflow.all") }}</option>
            <option
              v-for="item in approveType"
              :key="item.deploymentId"
              :value="item.deploymentId"
            >
              {{ item.name }}
            </option>
          </select>
        </div>
      </div>

      <div class="row m-row">
        <div class="col-md-12 col-sm-12 col-xs-10">
          <button
            role="button"
            target="_self"
            class="btn btn-primary"
            @click="searchMyApply()"
          >
            {{ $t("lang.MyApplyWorkflow.search") }}
          </button>
          <a
            class="form-label"
            @click="taskQueryParam.advancedQuery = !taskQueryParam.advancedQuery"
          >{{ (taskQueryParam.advancedQuery) ? $t("lang.MyApplyWorkflow.closeAdvancedSearch") : $t("lang.MyApplyWorkflow.advancedSearch") }}</a>
          <a
            id="clearSearchCondition"
            class="form-label"
            @click="clean()"
          >{{ $t("lang.MyApplyWorkflow.clearSearchCriteria") }}</a>
          <span id="choiceStatus">
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;ALL&quot;}"
              @click="choiceStatus('ALL')"
            >{{ $t("lang.MyApplyWorkflow.all") }}</button>
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;FINISH&quot;}"
              @click="choiceStatus('FINISH')"
            >{{ $t("lang.MyApplyWorkflow.done") }}</button>
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;RUNNING&quot;}"
              @click="choiceStatus('RUNNING')"
            >{{ $t("lang.MyApplyWorkflow.inProcess") }}</button>
          </span>
        </div>
      </div>
      <div class="row m-row">
        <div class="table-responsive">
          <table class="table  table-hover table-bordered">
            <thead>
              <tr>
                <td>{{ $t("lang.MyApplyWorkflow.documentCode") }}</td>
                <td>{{ $t("lang.MyApplyWorkflow.subject") }}</td>
                <td>{{ $t("lang.MyApplyWorkflow.approvalSummary") }}</td>
                <td>{{ $t("lang.MyApplyWorkflow.originatingTime") }}</td>
                <td>{{ $t("lang.MyApplyWorkflow.completionTime") }}</td>
                <td>{{ $t("lang.MyApplyWorkflow.status") }}</td>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="item in historicProcessInstanceInfos.historicProcessInstanceInfos"
                :key="item.id"
                class="m-tr"
                @click="selectTaskInfo(item)"
              >
                <td>
                  {{ item.no }}
                </td>
                <td>
                  {{ item.title }}
                </td>
                <td>
                  <span style="white-space: pre-line">{{ item.content }}</span>
                </td>
                <td>
                  {{ item.startDate }}
                </td>
                <td>
                  {{ item.endDate }}
                </td>
                <td>
                  {{ item.documentStatus }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <VueBootstrapPagination
        :pagination="pagination"
        :callback="changePage"
      />
    </div>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../common/Common.js';


import { Uuid} from 'pc-component-v3';
import * as dayjs from 'dayjs';



export default {

  components: {
  },
  data: function () {
    return {
      'defaultStartAfter': '',   //默认开始日期
      'defaultStartBefore': '',
      'defaultFinishAfter': '',   //默认结束日期
      'defaultFinishBefore': '',
      'startAfter': '',          //开始日期
      'startBefore': '',
      'finishAfter': '',          //结束日期
      'finishBefore': '',
      'taskQueryParam': { 'processStatusQuery': 'ALL' },    	//查询条件       
      'historicProcessInstanceInfos': '',
      'deploymentId': '',
      'userName': '',
      'approveType': [],
      pagination: {
        total: 0,
        per_page: 15,    // 每页的信息数
        current_page: 1, // required
        last_page: 0,    // required
      },
      loading: false,
    };
  },
  mounted: function () {
    this.init();
  },

  methods: {
    // 加载数据
    init: function () {
      var _self = this;
      _self.loading=true;
      _self.defaultStartAfter = dayjs().add(-1, 'month').format('YYYY-MM-DD HH:mm:ss');
      _self.defaultStartBefore = dayjs().format('YYYY-MM-DD HH:mm:ss');
      _self.defaultFinishAfter = dayjs().add(-1, 'month').format('YYYY-MM-DD HH:mm:ss');
      _self.defaultFinishBefore = dayjs().format('YYYY-MM-DD HH:mm:ss');
      _self.taskQueryParam = {
        'condition': '',         //查询条件(主题、文件编码、正文内容、审批意见).
        'startAfter': _self.defaultStartAfter,
        'startBefore': _self.defaultStartBefore,
        'advancedQuery': false,    //是否高级查询
        //"startUserId" : "",     //审批单发起人
        'deploymentId': '',      //工作流部署Id
        'processStatusQuery': 'ALL',  //审批状态
        'range': {               //查询区间
          'length': 100,
          'start': 0,
        },
      };
      console.log(JSON.stringify(_self.taskQueryParam));
      $.ajax({
        url: Common.getApiURL('WorkflowResource/ApproveType'),
        type: 'GET',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading=false;
          _self.approveType = data;
          _self.searchMyApply();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    getStartUserId: function () {
      var _self = this;
      if (_self.userName != null && _self.userName != '') {
        _self.loading=true;
        var infoQueryParam = {};
        infoQueryParam.infoWindowNo = 11531;
        infoQueryParam.start = 0;
        infoQueryParam.length = 1;
        infoQueryParam.sortClause = '';
        infoQueryParam.infoFilterFieldValues = [];
        infoQueryParam.infoFilterFieldValues[0] = {};
        infoQueryParam.infoFilterFieldValues[0].infoFilterFieldId = 11532;
        infoQueryParam.infoFilterFieldValues[0].value1 = _self.userName;
        $.ajax({
          url: Common.getApiURL('InfoWindowResource/QueryInfoWindowData2'),
          type: 'post',
          dataType: 'json',
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          contentType: 'application/json',
          data: JSON.stringify(infoQueryParam),
          async: false,
          success: function (data) {
            _self.loading=false;
            _self.taskQueryParam.startUserId = '';
            if (data.dataList[0].id != null) {
              _self.taskQueryParam.startUserId = data.dataList[0].id;
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading=false;
            _self.$refs.common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      }
    },
    searchMyApply: function () {
      var _self = this;
      _self.loading=true;
      _self.taskQueryParam.range.start = 0;
      _self.taskQueryParam.range.length = _self.pagination.per_page;
      _self.pagination.current_page = 1;
      _self.taskQueryParam.startAfter = _self.defaultStartAfter;
      _self.taskQueryParam.startBefore = _self.defaultStartBefore;
      _self.taskQueryParam.finishAfter = _self.defaultFinishAfter;
      _self.taskQueryParam.finishBefore = _self.defaultFinishBefore;
      _self.taskQueryParam.deploymentId = _self.deploymentId;
      if (_self.taskQueryParam.advancedQuery) {
        _self.getStartUserId();
        _self.taskQueryParam.startAfter = _self.startAfter;
        _self.taskQueryParam.startBefore = _self.startBefore;
        _self.taskQueryParam.finishAfter = _self.finishAfter;
        _self.taskQueryParam.finishBefore = _self.finishBefore;
      }
						
      $.ajax({
        url: Common.getApiURL('WorkflowResource/MyApply'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: JSON.stringify(_self.taskQueryParam),
        success: function (data) {
          _self.loading=false;
          _self.historicProcessInstanceInfos = data;
          _self.historicProcessInstanceInfos.historicProcessInstanceInfos.forEach(item => {
            
            try{
              var content = JSON.parse(item.content);
              var parentForm = '';
              content.parentForm.forEach(item => {
                parentForm =parentForm + item.title+':'+item.content+'，\n';
              });
              item.content = parentForm;
            // eslint-disable-next-line no-empty
            }catch(e){
              
            }
            
          });
          _self.pagination.total = data.totalCount;
          _self.pagination.last_page = Math.ceil(data.totalCount / _self.taskQueryParam.range.length);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          _self.$refs.common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //是否开启高级查询
    isAdvancedQuery: function (flag) {
      let _self = this;
      _self.taskQueryParam.advancedQuery = flag;
      if (!flag) {
        //初始化日期
        _self.taskQueryParam.startAfter = _self.defaultStartAfter;
        _self.taskQueryParam.startBefore = _self.defaultStartBefore;
      }
    },
    showTaskInfo: function (id) {
      var _self = this;
      _self.taskInfoId = id;
    },
    clean: function () {   //清空搜索条件
      var _self = this;
      _self.userName = '';
      _self.taskQueryParam.condition = '';
      _self.defaultStartAfter = dayjs().add(-1, 'month').format('YYYY-MM-DD HH:mm:ss');
      _self.defaultStartBefore = dayjs().format('YYYY-MM-DD HH:mm:ss');
      _self.defaultFinishAfter = dayjs().add(-1, 'month').format('YYYY-MM-DD HH:mm:ss');
      _self.defaultFinishBefore = dayjs().format('YYYY-MM-DD HH:mm:ss');
      _self.startAfter = '';
      _self.startBefore = '';
      _self.finishAfter = '';
      _self.finishBefore = '';
    },
    choiceStatus: function (status) {
      this.taskQueryParam.processStatusQuery = status;
      this.searchMyApply();
    },
    changePage: function () {
      var _self = this;
      _self.loading=true;
      _self.taskQueryParam.range.start = _self.pagination.per_page * (parseInt(_self.pagination.current_page) - 1);
      _self.taskQueryParam.startAfter = _self.defaultStartAfter;
      _self.taskQueryParam.startBefore = _self.defaultStartBefore;
      _self.taskQueryParam.finishAfter = _self.defaultFinishAfter;
      _self.taskQueryParam.finishBefore = _self.defaultFinishBefore;
      if (_self.taskQueryParam.advancedQuery) {
        _self.taskQueryParam.startAfter = _self.startAfter;
        _self.taskQueryParam.startBefore = _self.startBefore;
        _self.taskQueryParam.finishAfter = _self.finishAfter;
        _self.taskQueryParam.finishBefore = _self.finishBefore;
      }
      console.log(JSON.stringify(_self.taskQueryParam));
      $.ajax({
        url: Common.getApiURL('WorkflowResource/MyApply'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: JSON.stringify(_self.taskQueryParam),
        success: function (data) {
          _self.loading=false;
          _self.historicProcessInstanceInfos = data;
          _self.historicProcessInstanceInfos.historicProcessInstanceInfos.forEach(item => {
            
            try{

              var content = JSON.parse(item.content);
              var parentForm = '';
              content.parentForm.forEach(item => {
                parentForm =parentForm + item.title+':'+item.content+'，\n';
              });
              item.content = parentForm;
            // eslint-disable-next-line no-empty
            }catch(e){
              
            }
          });
          _self.pagination.total = data.totalCount;
          _self.pagination.last_page = Math.ceil(data.totalCount / _self.taskQueryParam.range.length);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          _self.$refs.common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
        
    // 选择了taskInfo
    selectTaskInfo: function (taskInfo) {
      var _self = this;
      var type = 'view';
      var windowNo = taskInfo.windowNo;
      var tabIndex = taskInfo.tabIndex;
      var recordId = taskInfo.recordId;
      var url = '/desktop/window/window-read/'
                + type + '/'
                + windowNo + '/'
                + tabIndex + '/'
                + recordId
                + '?workflowType=approve&taskInfoId=' + taskInfo.id
                + '&currIndex=1&totalCount=1&canGoBack=false&uuid=' + Uuid.createUUID();

      window.open(Common.getRedirectUrl('#' + url));
    },
  },
};
</script>

<style scoped>
.form-label {
    margin-left: 10px;
    cursor: pointer;
}

.m-tr {
    cursor: pointer;
}
</style>