<template>
  <!-- 抽屉 -->
  <a-drawer
    :visible="visible"
    width="95vw"
    title="流程详情"
    @close="onClose"
    class="modern-workflow-drawer"
    :bodyStyle="{ padding: '0', background: '#f5f7fa', flex: 1 }"
    :headerStyle="{ borderBottom: '1px solid #eaedf2', padding: '16px 24px' }"
  >
    <div class="workflow-container">
      <!-- 基础信息卡片 -->
      <div class="info-section">
        <workflow-base-information
          v-if="details"
          ref="baseInformation"
          :workflow-id="workflowId"
          :details="details"
          :visible="visible"
          class="base-info-card"
        />
      </div>

      <!-- 内容区域 -->
      <div class="content-section">
        <a-card class="content-card" :bordered="false">
          <a-tabs
            :activeKey="activeKey"
            @change="changeTab"
            class="modern-tabs"
            :tabBarStyle="{ marginBottom: '5px', borderBottom: '1px solid #eaedf2' }"
          >
            <!-- 查看/编辑进度标签页 -->
            <a-tab-pane key="1" tab="开始工作">
              <WorkFlowHandle
                v-if="isWorkflowDataReady"
                ref="workflowHandle"
                :workflow-id="workflowId"
                :workflowState="details.f_state === 1"
                :complete-time="details.f_complete_time"
                :stepsForChild="steps"
                :visible="visible"
                :taskName="details.f_task_name"
                :details="details"
                :renderCurrentNode="renderCurrentNode"
                :initStepId="initStepId"
                @refresh="stepChanged"
                @success="success"
                @nextClick="nextClick"
                @preClick="preClick"
                @x-form-item-emit-func="handleFormItemEvent"
                class="handle-content"
              />
              <div v-else-if="activeKey === '1'" class="loading-placeholder">
                <a-spin size="large" tip="正在加载工作流数据..."/>
              </div>
            </a-tab-pane>

            <!-- 任务流转记录标签页 -->
            <a-tab-pane key="2" tab="流转记录">
              <workflow-log
                v-if="activeKey === '2'"
                :workflow-id="workflowId"
                class="log-content"
              />
            </a-tab-pane>

            <!-- 任务留言标签页 -->
            <a-tab-pane key="4">
              <span slot="tab" class="message-tab">
                <span>任务留言</span>
                <a-badge
                  :count="messageList.length"
                  :offset="[8, -4]"
                  :numberStyle="{ backgroundColor: '#5B6B8F', fontSize: '12px', padding: '0 6px', height: '18px', lineHeight: '18px', borderRadius: '9px' }"
                />
              </span>
              <div class="message-content">
                <template v-if="activeKey === '4' && details">
                  <leave-message
                    :workflowId="workflowId"
                    :projectName="details.f_task_name"
                    :data="messageList"
                    :loading="messageLoading"
                    @success="success"
                    class="leave-message-component"
                  />
                </template>
              </div>
            </a-tab-pane>

            <!-- 查看附件标签页 -->
            <a-tab-pane key="5" tab="查看附件">
              <template v-if="activeKey === '5' && details">
                <file-item-group :workflow-id="workflowId" @search="getWorkFlowFiles"/>
              </template>
            </a-tab-pane>

            <!-- 任务流转记录标签页 -->
            <a-tab-pane key="6" tab="工作日志">
              <worklog
                v-if="activeKey === '6'"
                :workflow-id="workflowId"
                :details="details"
                class="log-content"
              />
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
  </a-drawer>
</template>

<script>
import { mapState } from 'vuex'
import workflowBaseInformation from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkFlowBaseInformation.vue'
import WorkFlowHandle from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkFlowHandle.vue'
import XFormTable from '@vue2-client/base-client/components/common/XFormTable/XFormTable'
import { postByServiceName } from '@vue2-client/services/api/restTools'
import { workFlowViewApi } from '@vue2-client/services/api/workFlow'
import WorkflowLog from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/WorkflowLog.vue'
import LeaveMessage from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/LeaveMessage.vue'
import XUploadFilesView from '@vue2-client/base-client/components/common/XUploadFilesView/index.vue'
import FileItemGroup from '@vue2-client/components/FileImageItem/FileItemGroup.vue'
import worklog from '@vue2-client/pages/WorkflowDetail/WorkflowPageDetail/worklog.vue'

export default {
  name: 'WorkflowDetail',
  components: {
    FileItemGroup,
    workflowBaseInformation,
    WorkFlowHandle,
    XFormTable,
    WorkflowLog,
    LeaveMessage,
    XUploadFilesView,
    worklog
  },
  props: {},
  data () {
    return {
      // 页面宽度
      screenWidth: document.documentElement.clientWidth,
      // 页面高度
      screenHeight: document.documentElement.clientHeight,
      // 控制当前标签页
      activeKey: '1',
      // 保存流程和留言信息
      steps: undefined,
      // 基础信息
      details: undefined,
      // 给XFormTable增加额外查询条件
      fixedAddForm: {},
      fixedQueryForm: {},
      // 留言数据
      messageList: [],
      messageLoading: true,
      workflowId: '',
      initStepId: null,
      visible: false,
      // 控制流程是否可操作
      renderCurrentNode: true
    }
  },
  expose: ['setFormValue'],
  computed: {
    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', ['isMobile']),
    // 检查 WorkFlowHandle 组件渲染所需的数据是否都已准备好
    isWorkflowDataReady () {
      return this.activeKey === '1' &&
             this.details &&
             this.details.f_state !== undefined &&
             this.steps !== undefined
    }
  },
  mounted () {
    // this.init()
  },
  methods: {
    // 内部组件更新了当前步骤后的回调
    stepChanged () {
      this.initStepId = null
      this.loading = true
      this.reload()
    },
    // 获取所有步骤
    getSteps () {
      return postByServiceName(workFlowViewApi.getStepNoteAndHandler, {
        workflowId: this.workflowId,
        curUserId: String(this.currUser.id)
      })
        .then(res => {
          this.steps = res
        }, err => {
          console.log(err)
        })
    },
    // 关闭抽屉的回调
    onClose () {
      if (this.$refs.workflowHandle !== undefined) {
        this.$refs.workflowHandle.onClose()
      }
      this.visible = false
      this.activeKey = '1'
      this.details = undefined
      this.fixedAddForm = {}
      this.fixedQueryForm = {}
      this.steps = undefined
      this.messageList = []
      this.currStepId = null
      this.$emit('drawerOnClose')
    },
    // 获取基础信息
    getBaseInfo () {
      this.loading = true
      return postByServiceName(workFlowViewApi.getWorkFlowBasicInfo, {
        workflowId: this.workflowId
      })
        .then(res => {
          // 主动传入得优先级较高
          if (this.currStepId) {
            res.f_sub_state = this.steps.find(item => item.id === this.currStepId)?.name
          } else {
            res.f_sub_state = this.steps.find(item => item.id === res.f_step_id)?.name
          }
          this.details = res
        }, err => {
          console.log(err)
        })
    },
    // 获取附件列表
    getWorkFlowFiles (date, callback, errorCallback) {
      postByServiceName(workFlowViewApi.getWorkFlowAttachments, {
        workflowId: this.workflowId,
        uploadDate: date
      })
        .then(res => {
           res.files = [
            ...(res.images || []),
            ...(res.files || []),
          ]
          callback(res)
        })
        .catch((e) => errorCallback(e))
    },
    async reload () {
      await this.getSteps()
      await this.getBaseInfo()
      this.fixedQueryForm.a_f_workflow_id = this.workflowId
      this.fixedAddForm.a_f_workflow_id = this.workflowId
    },
    // 初始化两张固定表
    async init ({ workflowId, stepId, renderCurrentNode = true, visible = true }) {
      this.workflowId = workflowId
      if (stepId) {
        this.initStepId = stepId
      }
      this.visible = visible
      this.renderCurrentNode = renderCurrentNode
      await this.reload()
    },
    // 切换标签页
    changeTab (id) {
      this.activeKey = id
    },
    // 提交完成后事件
    success (res) {
      this.onClose()
      this.$emit('success', res)
    },
    // 提交完成后事件
    nextClick (res) {
      this.$emit('nextClick', res)
    },
    // 退回后事件
    preClick (res) {
      this.$emit('preClick', res)
    },
    handleFormItemEvent (func, data, value) {
      this.$emit('x-form-item-emit-func', func, data, value)
    },
    // 给地址选择表单项赋值
    setFormValue (record) {
      this.$refs.workflowHandle.$refs.xAddForm.setForm(record)
    }
  }
}
</script>

<style lang="less" scoped>
.workflow-container {
  height: 100%;
  display: flex;
  flex-direction: column;

  .info-section {
    padding: 16px 24px;
    background-color: #fff;
    border-bottom: 1px solid #eaedf2;
  }

  .content-section {
    flex: 1;
    padding: 16px 24px;

    .content-card {
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      min-height: 100%;

      /deep/ .ant-card-body {
        padding: 12px 24px 24px;
      }
    }
  }
}

.modern-tabs {
  /deep/ .ant-tabs-nav {
    margin-bottom: 0;
  }

  /deep/ .ant-tabs-tab {
    padding: 12px 0;
    margin-right: 48px;
    font-size: 15px;
  }

  /deep/ .ant-tabs-tab-active {
    font-weight: 500;
  }

  /deep/ .ant-tabs-ink-bar {
    height: 3px;
    border-radius: 3px 3px 0 0;
  }
}

.message-tab {
  display: flex;
  align-items: center;
  gap: 6px;
}

.message-content {

  .leave-message-component {
    width: 100%;
  }
}

.log-content {
  margin-top: 16px;
}

/deep/ .step-label {
  &:not(:first-child) {
    margin-left: 16px;
  }

  .step-icon {
    position: relative;
    top: 1px;
    display: inline-block;
    width: 12px;
    height: 12px;
    background: #ffffff;
    border-radius: 50%;
    margin-right: 8px;

    &.blue {
      border: 3px solid #5B6B8F;
    }

    &.green {
      border: 3px solid #4CAF50;
    }

    &.gray {
      border: 3px solid #cfd8e3;
    }
  }
}

:deep(.ant-drawer-wrapper-body) {
  display: flex;
  flex-direction: column;
}

.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;

  /deep/ .ant-spin-text {
    color: #666;
    margin-top: 16px;
  }
}
</style>
