<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.NotApproveWorkflow.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.NotApproveWorkflow.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.NotApproveWorkflow.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.NotApproveWorkflow.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.NotApproveWorkflow.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.NotApproveWorkflow.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="searchNotApproved()"
          >
            {{ $t("lang.NotApproveWorkflow.search") }}
          </button>
          <a
            class="form-label"
            @click="taskQueryParam.advancedQuery = !taskQueryParam.advancedQuery"
          >{{ (taskQueryParam.advancedQuery) ? $t("lang.NotApproveWorkflow.closeAdvancedSearch") : $t("lang.NotApproveWorkflow.advancedSearch") }}</a>
          <a
            id="clearSearchCondition"
            class="form-label"
            @click="clean()"
          >{{ $t("lang.NotApproveWorkflow.clearSearchCriteria") }}</a>
          <span id="choiceStatus">
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;ALL&quot;}"
              @click="choiceStatus('ALL')"
            >{{ $t("lang.NotApproveWorkflow.all") }}</button>
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;FINISH&quot;}"
              @click="choiceStatus('FINISH')"
            >{{ $t("lang.NotApproveWorkflow.done") }}</button>
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;RUNNING&quot;}"
              @click="choiceStatus('RUNNING')"
            >{{ $t("lang.NotApproveWorkflow.inProcess") }}</button>
          </span>
        </div>
      </div>

      <div class="row m-row">
        <div class="table-responsive">
          <table class="table table-bordered table-hover">
            <thead>
              <tr>
                <td>{{ $t("lang.NotApproveWorkflow.documentCode") }}</td>
                <td>{{ $t("lang.NotApproveWorkflow.subject") }}</td>
                <td>{{ $t("lang.NotApproveWorkflow.approvalSummary") }}</td>
                <td>{{ $t("lang.NotApproveWorkflow.originatingTime") }}</td>
                <td>{{ $t("lang.NotApproveWorkflow.completionTime") }}</td>
                <td>{{ $t("lang.NotApproveWorkflow.status") }}</td>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="item in historicTaskInfos.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 == '进行中' ? $t("lang.NotApproveWorkflow.inProcess"):$t("lang.NotApproveWorkflow.done") }}
                </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 WindowService from '../common/WindowService.js';
import { Notify } from 'pc-component-v3';
import TaskOpenUtil from './TaskOpenUtil.js';
import * as dayjs from 'dayjs';

export default {

  components: {
  },
  data: function () {
    return {
      'defaultStartAfter': '',   //默认开始日期
      'defaultStartBefore': '',
      'defaultFinishAfter': '',   //默认结束日期
      'defaultFinishBefore': '',
      'startAfter': '',          //开始日期
      'startBefore': '',
      'finishAfter': '',          //结束日期
      'finishBefore': '',
      'taskQueryParam': { 'processStatusQuery': 'FINISH' },    	//查询条件       
      'historicTaskInfos': [],
      'deploymentId': '',
      'userName': '',
      'approveType': [],
      pagination: {
        total: 0,
        per_page: 20,    // required
        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.searchNotApproved();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    getStartUserId: function () {
      var _self = this;
      _self.loading=true;
      if (_self.userName != null && _self.userName != '') {
        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;
            Common.processException(XMLHttpRequest);
          },
        });
      }
    },
    searchNotApproved: 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;
      }
      console.log(JSON.stringify(_self.taskQueryParam));
      $.ajax({
        url: Common.getApiURL('WorkflowResource/refuse'),
        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.historicTaskInfos = data;
          _self.historicTaskInfos.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;
          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.searchNotApproved();
    },
    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/refuse'),
        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.historicTaskInfos = data;
          _self.historicTaskInfos.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;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    // 选择了taskInfo
    selectTaskInfo: function (taskInfo) {
      let _self = this;
      TaskOpenUtil.openHistoryTask(taskInfo).then(successData => {
        if(successData.type === 'newWindow'){
          WindowService.open(successData.url, '已驳回的', function(){
            _self.$emit('refreshStasticCount');
            _self.searchNotApproved();
          });
        }else if(successData.type === 'customerTask'){
          // 打开自定义的界面
          _self.selectedTaskId = taskInfo.id;
          _self.$refs.customerTask.show();
          _self.$emit('refreshStasticCount');
          _self.searchNotApproved();
        }
      }, errorData => {
        if(errorData != null){
          Notify.error(errorData.title, errorData.message, false);
        }
      });
    },


  },
};
</script>

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

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