<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.CopyTaskWorkflow.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.CopyTaskWorkflow.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.CopyTaskWorkflow.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.CopyTaskWorkflow.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.CopyTaskWorkflow.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.CopyTaskWorkflow.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="searchCopyTask()"
          >
            {{ $t("lang.CopyTaskWorkflow.search") }}
          </button>
          <a
            class="form-label"
            @click="taskQueryParam.advancedQuery = !taskQueryParam.advancedQuery"
          >

            {{ (taskQueryParam.advancedQuery) ? $t("lang.CopyTaskWorkflow.closeAdvancedSearch") : $t("lang.CopyTaskWorkflow.advancedSearch") }}

          </a>
          <a
            id="clearSearchCondition"
            class="form-label"
            @click="clean()"
          >{{ $t("lang.CopyTaskWorkflow.clearSearchCriteria") }}</a>
          <span id="choiceStatus">
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;ALL&quot;}"
              @click="choiceStatus('ALL')"
            >{{ $t("lang.CopyTaskWorkflow.all") }}</button>
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;FINISH&quot;}"
              @click="choiceStatus('FINISH')"
            >{{ $t("lang.CopyTaskWorkflow.completed") }}</button>
            <button
              class="btn"
              :class="{&quot;btn-info active&quot;: taskQueryParam.processStatusQuery == &quot;RUNNING&quot;}"
              @click="choiceStatus('RUNNING')"
            >{{ $t("lang.CopyTaskWorkflow.haveInHand") }}</button>
            <a-button type="link" @click="completeApproval">全部完成审阅</a-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.CopyTaskWorkflow.documentCode") }}</td>
                <td>{{ $t("lang.CopyTaskWorkflow.subject") }}</td>
                <td>{{ $t("lang.CopyTaskWorkflow.approvalSummary") }}</td>
                <td>{{ $t("lang.CopyTaskWorkflow.originatingTime") }}</td>
                <td>{{ $t("lang.CopyTaskWorkflow.completionTime") }}</td>
                <td>{{ $t("lang.CopyTaskWorkflow.status") }}</td>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="item in copyTaskInfos.copyTaskInfo"
                :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 WindowService from '../common/WindowService.js';
import TaskOpenUtil from './TaskOpenUtil.js';
import { Notify, Uuid } from 'pc-component-v3';
import * as dayjs from 'dayjs';

export default {

  components: {
  },
  emits:['refreshStasticCount'],
  data: function () {
    return {
      defaultStartAfter: '', //默认开始日期
      defaultStartBefore: '',
      defaultFinishAfter: '', //默认结束日期
      defaultFinishBefore: '',
      startAfter: '', //开始日期
      startBefore: '',
      finishAfter: '', //结束日期
      finishBefore: '',
      taskQueryParam: { processStatusQuery: 'ALL' }, //查询条件
      copyTaskInfos: '',
      deploymentId: '',
      userName: '',
      approveType: [],
      pagination: {
        total: 0,
        per_page: 12, // 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: 'RUNNING', //审批状态
        range: {
          //查询区间
          length: 100,
          start: 0,
        },
      };

      $.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.searchCopyTask();
        },
        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, textStatus, errorThrown);
          },
        });
      }
    },

    searchCopyTask: 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/copyTask'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: JSON.stringify(_self.taskQueryParam),
        success: function (data) {
          console.log(JSON.stringify(data));
          _self.loading = false;
          _self.copyTaskInfos = data;
          _self.copyTaskInfos.copyTaskInfo.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 =
                        data.totalCount % _self.taskQueryParam.range.length == 0
                          ? data.totalCount / _self.taskQueryParam.range.length
                          : Math.floor(
                            data.totalCount / _self.taskQueryParam.range.length,
                          ) + 1;
        },
        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.searchCopyTask();
    },

    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/copyTask'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: JSON.stringify(_self.taskQueryParam),
        success: function (data) {
          _self.loading = false;
          //console.log(JSON.stringify(data));
          _self.copyTaskInfos = data;
          _self.copyTaskInfos.copyTaskInfo.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 =
                        data.totalCount % _self.taskQueryParam.range.length == 0
                          ? data.totalCount / _self.taskQueryParam.range.length
                          : Math.floor(
                            data.totalCount / _self.taskQueryParam.range.length,
                          ) + 1;
          console.log('totalCount=' + _self.pagination.total);
          console.log('totalPage=' + _self.pagination.last_page);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(
            XMLHttpRequest,
            textStatus,
            errorThrown,
          );
        },
      });
    },

    // 选择了taskInfo
    selectTaskInfo: function (taskInfo) {
      var _self = this;
      _self.loading = true;
      if (
        taskInfo.systemProcess == undefined ||
                taskInfo.systemProcess == false
      ) {
        $.ajax({
          url: Common.getApiURL('WorkflowResource/processTaskInfo'),
          type: 'get',
          dataType: 'json',
          contentType: 'application/json',
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          data: {
            taskInfoId: taskInfo.id,
          },
          success: function (data) {
            _self.loading = false;
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading = false;
            Common.processException(
              XMLHttpRequest,
              textStatus,
              errorThrown,
            );
          },
        });
      }


      TaskOpenUtil.openCopyTask(taskInfo).then(successData => {
        if (successData.type === 'newWindow') {
          WindowService.open(successData.url, '抄送我的', function () {
            _self.$emit('refreshStasticCount');
            _self.searchCopyTask();
          });
        } else if (successData.type === 'customerTask') {
          // 打开自定义的界面
          //_self.selectedTaskId = taskInfo.id;
          //_self.$refs.customerTask.show();
          //_self.$emit('refreshStasticCount');
          //_self.searchCopyTask();
        }
      }, errorData => {
        if (errorData != null) {
          Notify.error(errorData.title, errorData.message, false);
        }
      });
    },

    // 全部完成审阅
    completeApproval: function () {
      const _self = this;
      _self.loading = false;
      $.ajax({
        url: Common.getApiURL('WorkflowResource/completeCopyTasks'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          if(data.errorCode === 0){
            _self.$emit('refreshStasticCount');
            _self.searchCopyTask();
          } else {
            Notify.error('错误', data.errorMessage, false);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(
            XMLHttpRequest,
            textStatus,
            errorThrown,
          );
        },
      });
    },
  },
};
</script>

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

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