<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="needApproveRequest.condition"
            autocomplete="off"
            type="text"
            :placeholder="$t('lang.NeedApproveWorkflow.describe1')"
            class="form-control"
          />
        </div>
      </div>

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

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

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

      <div
        v-if="needApproveRequest.advancedQuery"
        class="row m-row"
      >
        <div class="col-md-2 col-sm-2 col-xs-4">
          <label class="form-control-static">{{ $t("lang.NeedApproveWorkflow.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.NeedApproveWorkflow.subject") }}</label>
        </div>
        <div class="col-md-10 col-sm-10 col-xs-8">
          <WorkflowType v-model="needApproveRequest.windowNo" />
        </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="search()"
          >
            {{ $t("lang.NeedApproveWorkflow.search") }}
          </button>
          <a
            class="form-label"
            @click="needApproveRequest.advancedQuery = !needApproveRequest.advancedQuery"
          >{{ (needApproveRequest.advancedQuery) ? $t("lang.NeedApproveWorkflow.closeAdvancedSearch") : $t("lang.NeedApproveWorkflow.advancedSearch") }}</a>
          <a
            id="clearSearchCondition"
            class="form-label"
            @click="clean()"
          >{{ $t("lang.NeedApproveWorkflow.clearSearchCriteria") }}</a>
        </div>
      </div>

      <div class="row m-row">
        <div class="table-responsive">
          <table class="table table-bordered table-hover ">
            <thead>
              <tr>
                <td>{{ $t("lang.NeedApproveWorkflow.documentCode") }}</td>
                <td>{{ $t("lang.NeedApproveWorkflow.subject") }}</td>
                <td>{{ $t("lang.NeedApproveWorkflow.approvalSummary") }}</td>
                <td>{{ $t("lang.NeedApproveWorkflow.originatingTime") }}</td>
                <td>{{ $t("lang.NeedApproveWorkflow.endTime") }}</td>
                <td>{{ $t("lang.NeedApproveWorkflow.operation") }}</td>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="item in taskInfos.taskInfo"
                :key="item.id"
                class="m-tr"
              >
                <td>
                  {{ item.no }}
                </td>
                <td>
                  <span v-if="item.category != 'CurdWindow'">
                    {{ item.name }}
                  </span>
                  <span v-else>
                    {{ item.title }}
                  </span>
                </td>
                <td>
                  <span v-if="item.category != 'CurdWindow'" style="white-space: pre-line">{{ item.description }}</span>
                  <span v-else style="white-space: pre-line">{{ item.content }}</span>
                </td>
                <td>
                  {{ item.startDate }}
                </td>
                <td>
                  {{ item.dueDate }}
                </td>
                <td>
                  <button class="btn btn-link" @click="selectTaskInfo(item)">{{ $t("lang.NeedApproveWorkflow.viewTasks") }}</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <VueBootstrapPagination
        :pagination="pagination"
        :callback="changePage"
      />
    </div>
    <Loading v-if="loading" />
    <CustomerTask ref="customerTask" :task-id="selectedTaskId" @closed="search" />
  </div>
</template>

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

import WindowService from '../common/WindowService.js';



import WorkflowResource from '../api/workflow/WorkflowResource.js';
import CustomerTask from './CustomerTask.vue';
import { Notify, Uuid } from 'pc-component-v3';
import TaskOpenUtil from './TaskOpenUtil.js';
import * as dayjs from 'dayjs';
import WorkflowType from './WorkflowType.vue';

export default {

  components: {
    CustomerTask, WorkflowType,
  },
  data: function () {
    return {
      'defaultStartAfter': '',   //默认开始日期
      'defaultStartBefore': '',  //默认结束日期
      'startAfter': '',          //开始日期
      'startBefore': '',         //结束日期
      'needApproveRequest': { 
        'condition': null,
        'windowNo': null,
        'startUserId': null,
        'processInstanceStartAfter': null,
        'processInstanceStartBefore': null,
        'taskCreateTimeAfter': null,
        'taskCreateTimeBefore': null,
        'start': 0,
        'length': 10,
      },

      'taskInfos': [],
      'userName': '',
      'windowNo': '',
      'approveType': [],
      pagination: {
        total: 0,
        per_page: 20,    // required
        current_page: 1, // required
        last_page: 0,    // required
      },
      selectedTaskId: null,
      loading: false,
    };
  },

  mounted: function () {
    this.init();
  },

  methods: {
    // 加载数据
    init: function () {
      var _self = this;
      _self.defaultStartAfter = dayjs().add(-1, 'month').format('YYYY-MM-DD HH:mm:ss');
      _self.defaultStartBefore = dayjs().format('YYYY-MM-DD HH:mm:ss');
      _self.needApproveRequest = {
        'condition': '',         //查询条件(主题、文件编码、正文内容、审批意见).
        'startAfter': _self.defaultStartAfter,
        'startBefore': _self.defaultStartBefore,
        'advancedQuery': false,    //是否高级查询
        //"startUserId" : "",     //审批单发起人
        'windowNo': '',      //工作流部署Id
        'processStatusQuery': 'RUNNING',  //审批状态
        'range': {               //查询区间
          'length': 100,
          'start': 0,
        },
      };
      console.log(JSON.stringify(_self.needApproveRequest));

    },


    //搜索
    search: function () {
      var _self = this;
      _self.loading=true;

      _self.pagination.current_page = 1;
      _self.needApproveRequest.range.start = 0;
      _self.needApproveRequest.range.length = _self.pagination.per_page;
      if (_self.needApproveRequest.advancedQuery) {
        _self.getStartUserId();
        _self.needApproveRequest.startAfter = _self.startAfter;
        _self.needApproveRequest.startBefore = _self.startBefore;
      }
      _self.needApproveRequest.windowNo = _self.windowNo;
      $.ajax({
        url: Common.getApiURL('WorkflowResource/needApprove'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.needApproveRequest),
        success: function (data) {
          _self.loading=false;
          _self.taskInfos = data;
          _self.taskInfos.taskInfo.forEach(item => {
            try{
              var content = JSON.parse(item.content);
              var parentForm = '';
              if(content != null && content.parentForm != null){
                content.parentForm.forEach(item => {
                  parentForm = parentForm + item.title + ':' + item.content + '，\n';
                });
                item.content = parentForm;
              }else{
                item.content = null;
              }
            // eslint-disable-next-line no-empty
            }catch(e){
              
            }
          });
          _self.pagination.total = data.totalCount;
          _self.pagination.last_page = Math.ceil(data.totalCount / _self.needApproveRequest.range.length);
        },
        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.needApproveRequest.startUserId = '';
            if (data.dataList[0].id != null) {
              _self.needApproveRequest.startUserId = data.dataList[0].id;
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading=false;
            _self.$refs.common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      }
    },

    //是否开启高级查询
    isAdvancedQuery: function (flag) {
      let _self = this;
      _self.needApproveRequest.advancedQuery = flag;
      if (!flag) {
        //初始化日期
        _self.needApproveRequest.startAfter = _self.defaultStartAfter;
        _self.needApproveRequest.startBefore = _self.defaultStartBefore;

      }
    },

    clean: function () {   //清空搜索条件
      var _self = this;
      _self.userName = '';
      _self.needApproveRequest.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.startAfter = '';
      _self.startBefore = '';
    },
    changePage: function () {
      var _self = this;
      _self.loading=true;
      _self.needApproveRequest.range.start = (_self.pagination.current_page - 1) * _self.pagination.per_page;
      _self.needApproveRequest.range.length = _self.pagination.per_page;
      _self.needApproveRequest.startAfter = _self.defaultStartAfter;
      _self.needApproveRequest.startBefore = _self.defaultStartBefore;
      _self.needApproveRequest.finishAfter = _self.defaultFinishAfter;
      _self.needApproveRequest.finishBefore = _self.defaultFinishBefore;
      if (_self.needApproveRequest.advancedQuery) {
        _self.needApproveRequest.startAfter = _self.startAfter;
        _self.needApproveRequest.startBefore = _self.startBefore;
        _self.needApproveRequest.finishAfter = _self.finishAfter;
        _self.needApproveRequest.finishBefore = _self.finishBefore;
      }
      console.log(JSON.stringify(_self.needApproveRequest));
      $.ajax({
        url: Common.getApiURL('WorkflowResource/needApprove'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: JSON.stringify(_self.needApproveRequest),
        success: function (data) {
          _self.loading=false;
          _self.taskInfos = data;
          _self.taskInfos.taskInfo.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.needApproveRequest.range.length);
          console.log('totalCount=' + _self.pagination.total);
          console.log('totalPage=' + _self.pagination.last_page);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          _self.$refs.common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 选择了taskInfo
    selectTaskInfo: function (taskInfo) {
      let _self = this;
      TaskOpenUtil.openTask(taskInfo).then(successData => {
        if(successData.type === 'newWindow'){
          WindowService.open(successData.url, '待处理', function(){
            _self.$emit('refreshStasticCount');
            _self.search();
          });
        }else if(successData.type === 'customerTask'){
          // 打开自定义的界面
          _self.selectedTaskId = taskInfo.id;
          _self.$refs.customerTask.show();
          _self.$emit('refreshStasticCount');
          _self.search();
        }
      }, 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>