<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <sd-worktree
        v-show="activeKey === 'todo'"
        ref="todoworktree"
        data-type="todo"
        @treeSelectd="treeSelectd"
        @foldFirstTime="foldFirstTime"
      ></sd-worktree>
      <sd-worktree
        v-show="activeKey === 'processed'"
        ref="processedworktree"
        data-type="processed"
        @treeSelectd="treeSelectd"
        @foldFirstTime="foldFirstTime"
      ></sd-worktree>
      <sd-worktree
        v-show="activeKey === 'completed'"
        ref="completedworktree"
        data-type="completed"
        @treeSelectd="treeSelectd"
        @foldFirstTime="foldFirstTime"
      ></sd-worktree>
      <div :class="$style.rightcard">
        <a-card>
          <a-tabs v-model="activeKey">
            <a-tab-pane key="todo" tab="待处理">
              <sd-data-table
                ref="todo"
                :key="treeId.todo"
                data-url="api/framework/v1/user-tasks/todo-with-trustor"
                :columns="todoColumns"
                :row-key="(record) => record.id || record.instId"
                :search-fields="['title']"
                :process-req="processReq"
                :show-selection="
                  (record) => {
                    // null是兼容之前的数据
                    return [null, 1].includes(record.pdReservesLong[0])
                  }
                "
                :filter-expressions="expressions.todo"
                :actions="actions"
                @rowClick="rowClick"
                @dataLoaded="tableDataLoaded"
              >
                <div slot="pjobtitle" slot-scope="text, record">
                  <a class="part-time">
                    <div class="title-box">
                      <span>
                        <a-spin v-if="pending.includes(record.id)">
                          <a-icon
                            slot="indicator"
                            type="loading"
                            :class="$style.submitStatus"
                            spin
                          />
                        </a-spin>
                        <a-icon
                          v-if="batchSubmitSucceed.includes(record.id)"
                          type="check-circle"
                          :class="[$style.submitStatus, $style.success]"
                        />
                        <a-tooltip
                          v-if="batchsubmitFailed.map((item) => item.id).includes(record.id)"
                          :title="batchsubmitFailed.find((item) => item.id === record.id).message"
                        >
                          <a-icon
                            type="close-circle"
                            :class="[$style.submitStatus, $style.error]"
                          />
                        </a-tooltip>
                      </span>
                      <span class="title-text" :class="record.seen ? '' : $style.unread">
                        <a-badge v-if="!record.seen" dot title="未查看" />{{ record.title }}</span
                      >
                      <a-tooltip
                        v-if="record.processState === 3"
                        title="上次处理异常待办，请重新处理"
                      >
                        <a-icon :class="$style.circleicon" type="question-circle" />
                      </a-tooltip>
                      <a-tag v-if="record.urgencyLevel !== 0 && record.urgencyLevelName" color="red"
                        >{{ record.urgencyLevelName }}
                      </a-tag>
                      <a-tag v-if="!!record.isCommunicate" color="blue">沟通</a-tag>
                      <a-tag v-if="record.reminder" color="orange">催</a-tag>
                      <a-tag v-if="record.trustor" color="blue">代{{ record.trustorName }}</a-tag>
                      <a-tooltip>
                        <template slot="title">{{ record.groupPath }}</template>
                        <a-tag v-show="record.srcTrustId" color="blue">
                          兼
                        </a-tag>
                      </a-tooltip>
                    </div>
                  </a>
                </div>
                <div slot="flowTimeToDeadLine" slot-scope="text, record">
                  <div
                    v-if="record.flowTimeToDeadline"
                    :class="{
                      [$style.limittime]: record.flowColor === 'blue',
                      [$style.expiretime]: record.flowColor === 'orange',
                      [$style.overtime]: record.flowColor === 'red',
                    }"
                  >
                    <a-icon type="sd-3-circle" title="全流程限时" :class="$style.remind" />{{
                      deadline(record.flowColor)
                    }}:
                    <div :class="$style.time" :title="record.flowTimeToDeadline"
                      >{{ record.flowTimeToDeadline }}
                    </div>
                  </div>
                </div>
                <div slot="stepTimeToDeadLine" slot-scope="text, record">
                  <div
                    v-if="record.stepTimeToDeadline"
                    :class="{
                      [$style.limittime]: record.stepColor === 'blue',
                      [$style.expiretime]: record.stepColor === 'orange',
                      [$style.overtime]: record.stepColor === 'red',
                    }"
                  >
                    <a-icon type="exclamation-circle" title="本环节限时" :class="$style.remind" />{{
                      deadline(record.stepColor)
                    }}:
                    <div :class="$style.time" :title="record.stepTimeToDeadline"
                      >{{ record.stepTimeToDeadline }}
                    </div>
                  </div>
                </div>
              </sd-data-table>
            </a-tab-pane>
            <a-tab-pane key="processed" tab="已处理">
              <sd-data-table
                ref="processed"
                :key="treeId.processed"
                data-url="api/framework/v1/user-tasks/processed-with-trustor"
                :columns="processedColumns"
                :row-key="(record) => record.id || record.instId"
                :search-fields="['title']"
                :filter-expressions="expressions.processed"
                @rowClick="rowClick"
                @dataLoaded="tableDataLoaded"
              >
              </sd-data-table>
            </a-tab-pane>
            <a-tab-pane key="completed" tab="已办结">
              <sd-data-table
                ref="completed"
                :key="treeId.completed"
                data-url="api/framework/v1/user-tasks/completed-with-trustor"
                :columns="completedColumns"
                :row-key="(record) => record.id || record.instId"
                :search-fields="['title']"
                :filter-expressions="expressions.completed"
                @rowClick="rowClick"
                @dataLoaded="tableDataLoaded"
              >
              </sd-data-table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
    <a-modal
      :destroy-on-close="true"
      title="填写意见"
      :body-style="{ overflow: 'auto' }"
      :width="600"
      :visible="showOpinionModal"
      :wrap-class-name="$style.opinionModel"
      @ok="handleOkSubmit"
      @cancel="handleCancelSubmit"
    >
      <sd-opinion-model
        ref="opinionModel"
        v-model="form.opinion"
        :group-id="form.groupId"
        :cyy-popup-container="cyyPopupContainer"
      />
    </a-modal>
  </div>
</template>

<script>
import TableActionTypes from '@/common/services/table-action-types'
import todoListService from '@/todo/todo-list-service'
import FlowService from '@/webflow/flow-service'
import { Message } from 'ant-design-vue'
import sdOpinionModel from '@/webflow/sd-opinion-model.vue'
import TableColumnTypes from '../common/services/table-column-types'
import flowcenter from './sd-flowcenter-mixins'
import components from './_import-components/sd-todo-import'
export default {
  name: 'SdTodo',
  metaInfo: {
    title: '我的办件',
  },
  components: {
    ...components,
    sdOpinionModel,
  },
  mixins: [flowcenter],
  data() {
    const todoColumns = [
      {
        title: '业务类型',
        dataIndex: 'appCat',
        sdCandidate: true,
        width: '140px',
      },
      {
        title: '标题',
        dataIndex: 'title',
        sdClickable: true,
        scopedSlots: { customRender: 'pjobtitle' },
      },
      {
        title: '发起人',
        dataIndex: 'creatorName',
        width: '200px',
      },
      {
        title: '发起部门',
        dataIndex: 'creatorDeptName',
        width: '200px',
      },
      {
        title: '创建时间',
        dataIndex: 'creationTime',
        // sorter: true,  后台不支持待处理按创建时间排序
        width: '160px',
        sdRender: TableColumnTypes.dateTime,
        sdCandidate: true,
      },
      {
        title: '发送时间',
        dataIndex: 'sentDate',
        sdRender: TableColumnTypes.dateTime,
        sorter: true,
        width: '160px',
      },
      {
        title: '全流程限时',
        dataIndex: 'flowTimeToDeadLine',
        sdCandidate: true,
        scopedSlots: { customRender: 'flowTimeToDeadLine' },
        width: '120px',
      },
      {
        title: '环节限时',
        dataIndex: 'stepTimeToDeadLine',
        scopedSlots: { customRender: 'stepTimeToDeadLine' },
        width: '120px',
      },
    ]
    const processedColumns = [
      {
        title: '业务类型',
        dataIndex: 'appCat',
        sdCandidate: true,
        width: '140px',
      },
      {
        title: '标题',
        dataIndex: 'title',
        sdClickable: true,
        customRender: this.pjobRender,
      },
      {
        title: '发起人',
        dataIndex: 'creatorName',
        sdCandidate: true,
        width: '200px',
      },
      {
        title: '发起部门',
        dataIndex: 'creatorDeptName',
        sdCandidate: true,
        width: '200px',
      },
      {
        title: '创建时间',
        dataIndex: 'startDate',
        sdRender: TableColumnTypes.dateTime,
        sorter: true,
        sdCandidate: true,
        width: '200px',
      },
      {
        title: '办理时间',
        dataIndex: 'processDate',
        sdRender: TableColumnTypes.dateTime,
        sorter: true,
        defaultSortOrder: 'desc',
        width: '200px',
      },
      {
        title: '当前状态',
        dataIndex: 'activeStepNames',
        width: '200px',
      },
      {
        title: '当前处理人',
        dataIndex: 'activeOperatorUsers',
        width: '200px',
      },
    ]

    const completedColumns = [
      {
        title: '业务类型',
        dataIndex: 'appCat',
        sdCandidate: true,
        width: '140px',
      },
      {
        title: '标题',
        dataIndex: 'title',
        sdClickable: true,
        customRender: this.pjobRender,
      },
      {
        title: '发起人',
        dataIndex: 'creatorName',
        width: '200px',
      },
      {
        title: '发起部门',
        dataIndex: 'creatorDeptName',
        width: '200px',
      },
      {
        title: '创建时间',
        dataIndex: 'startDate',
        sdRender: TableColumnTypes.dateTime,
        sorter: true,
        sdCandidate: true,
        width: '200px',
      },
      {
        title: '办结时间',
        dataIndex: 'finishDate',
        sdRender: TableColumnTypes.dateTime,
        sorter: true,
        defaultSortOrder: 'desc',
        width: '200px',
      },
    ]
    return {
      activeKey: 'todo',
      todoColumns,
      processedColumns,
      completedColumns,
      // 业务类型树筛选条件
      expressions: { todo: [], processed: [], completed: [] },
      treeId: { todo: '', processed: '', completed: '' },
      form: {
        opinion: '',
        groupId: '',
      },
      showOpinionModal: false,
      pending: [],
      batchSubmitSucceed: [],
      batchsubmitFailed: [],
      actions: [
        {
          label: '批量处理',
          id: 'batch',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          permission: null, // data-table 的权限，需要写完整的
          callback: (keys) => {
            this.showOpinionModal = true
            this.getGroupCode()
          },
        },
      ],
    }
  },
  computed: {
    deadline() {
      return function(type) {
        let deadline = ''
        switch (type) {
          case 'blue':
            deadline = '限时'
            break
          case 'orange':
            deadline = '快到期'
            break
          case 'red':
            deadline = '已超时'
            break
        }
        return deadline
      }
    },
  },
  methods: {
    cyyPopupContainer() {
      return document.body
    },
    // 为了让列表能返回发起部门新增的参数
    processReq(req) {
      req.data.creatorDeptLevel = 'GROUP'
      return req
    },
    handleOkSubmit() {
      this.showOpinionModal = false
      this.pending = []
      this.batchSubmitSucceed = []
      this.batchsubmitFailed = []
      const selectedRows = this.$refs.todo.getSelectedRows()
      selectedRows.forEach((record) => {
        const id = record.id
        this.pending.push(id)
        const params = {
          id,
          opinion: this.form.opinion,
          attachment: this.form.groupId,
        }
        const srcTrustId = record.srcTrustId
        todoListService.batchSubmit(params, srcTrustId).then((res) => {
          if (res.code === '1') {
            this.batchSubmitSucceed.push(id)
          } else {
            this.batchsubmitFailed.push({ id: id, ...res })
          }
          const index = this.pending.findIndex((item) => item === id)
          this.pending.splice(index, 1)

          // 所有的都处理完刷新列表
          if (
            this.batchSubmitSucceed.length + this.batchsubmitFailed.length ===
            selectedRows.length
          ) {
            this.$refs.todo.refresh()
            this.$refs.todo.clearSelection()
          }
        })
      })
    },
    handleCancelSubmit() {
      this.showOpinionModal = false
      this.form.opinion = ''
      this.form.groupId = ''
    },
    getGroupCode() {
      // 获取groupId
      FlowService.getGroupCode().then((res) => {
        if (res.status === 200) {
          if (res.data) {
            this.form.groupId = res.data.toString()
          } else {
            Message.error('获取groupId失败')
          }
        } else {
          Message.error(res.statusText)
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
      overflow-y: auto;
    }
  }
  .time {
    overflow: hidden;
    text-indent: 20px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .remind {
    margin-right: 4px;
  }

  /* 限时 */
  .limittime {
    color: $blue-6;
  }

  /* 快到期 */
  .expiretime {
    color: $yellow-6;
  }

  .overtime {
    color: $red-6;
  }
  .submit-status {
    margin-right: 2px;
    font-size: $font-size-base;
  }
  .success {
    color: $alert-success-icon-color;
  }
  .error {
    color: $alert-error-icon-color;
  }
  .circleicon {
    margin-left: 4px;
    color: $orange-5;
  }
  .unread {
    :global(.ant-badge) {
      margin-right: 6px;
      vertical-align: baseline;
    }

    font-weight: 600;
  }
}
</style>
