<template>
  <div class="main-content market problem detail">
    <DetailHead result="问题详情信息" style="border-top:0;border-left:0;border-right:0" />
    <div class="main-form" style="width:60%">
      <!-- <div class="main-title">
        问题详细信息
      </div> -->
      <div class="main-body">
        <el-row>
          <el-col :span="4">问题主题</el-col>
          <el-col :span="20">
            <el-input v-model="detailInfo.problemTitle" readonly />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">问题描述</el-col>
          <el-col :span="20">
            <el-input v-model="detailInfo.problemDesc" readonly />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">发起单位</el-col>
          <el-col :span="8">
            <el-input v-model="detailInfo.reportOrgName" readonly />
          </el-col>
          <el-col :span="4" style="border-left:1px solid #c5e1fd">发起人</el-col>
          <el-col :span="8">
            <el-input v-model="detailInfo.reporterName" readonly />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">发起时间</el-col>
          <el-col :span="8">
            <el-date-picker v-model="detailInfo.reportTime" type="datetime" readonly style="width:100%" />
          </el-col>
          <el-col :span="4" style="border-left:1px solid #c5e1fd">最终处理时间</el-col>
          <el-col :span="8">
            <el-date-picker v-model="detailInfo.lauptime" type="datetime" readonly style="width:100%" />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">流转状态</el-col>
          <el-col :span="8">
            <el-select v-model="detailInfo.state" disabled style="width:100%">
              <el-option v-for="each in stateOptions" :key="'searchForm1State'+each.value" :label="each.label" :value="each.value" />
            </el-select>
          </el-col>
          <el-col :span="4">紧急程度</el-col>
          <el-col :span="8">
            <el-select v-model="detailInfo.urgency" disabled style="width:100%">
              <el-option value="0" label="普通" />
              <el-option value="1" label="紧急" />
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            最终反馈信息
          </el-col>
          <el-col :span="20">
            <el-input v-model="detailInfo.feedbackResult" type="textarea" readonly :autosize="{minRows:6, maxRows:12}" />
          </el-col>
        </el-row>
        <el-row v-if="fileList.length > 0">
          <el-col :span="4">附件</el-col>
          <el-col :span="10">
            <el-upload action="/" :file-list="fileList" :on-preview="previewFile" disabled />
          </el-col>
        </el-row>
      </div>
    </div>

    <el-button v-if="showCreateTask" v-loading="submitLoading" type="primary" @click="createTask">发起反馈流程</el-button>

    <div v-if="showNextProcess" class="main-form">
      <div class="main-title">
        经办审核审批
      </div>
      <div class="main-body table">
        <el-form ref="submitForm" label-width="140px" label-position="left" :model="submitForm" :rules="submitFormRules">
          <el-form-item label="是否通过" prop="nextNodeId">
            <el-radio-group v-model="submitForm.nextNodeId">
              <el-radio :label="nextNodeId" border>通过</el-radio>
              <el-radio :label="prevNodeId" border>退回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="nextNodeId == 'handleFeedback'" label="最终反馈信息" prop="feedbackResult">
            <el-input v-model="submitForm.feedbackResult" type="textarea" :autosize="{minRows:6, maxRows:12}" />
          </el-form-item>
          <el-form-item label="处理意见" prop="opinioncontent">
            <el-input v-model="submitForm.opinioncontent" type="textarea" :autosize="{minRows:6, maxRows:12}" />
          </el-form-item>
          <el-form-item v-if="submitForm.nextNodeId != prevNodeId && nextNodeId != 'endFeedback'" label="下一个审核人" prop="nextUserId">
            <el-select v-model="submitForm.nextUserId" placeholder="请选择审核人" class="custom">
              <el-option
                v-for="item in reviewer"
                :key="'reviewer'+item.primaryKey"
                :label="item.name"
                :value="item.primaryKey"
              />
            </el-select>
          </el-form-item>
          <el-button v-loading="submitLoading" type="primary" @click="submitProcess">提交</el-button>
        </el-form>
      </div>
    </div>
    <div class="main-form">
      <div class="main-title">
        处理流程
      </div>
      <div class="main-body table">
        <el-table
          :data="tableData"
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        >
          <el-table-column label="处理人" prop="handler" />
          <el-table-column label="发起单位" prop="handleOrg" />
          <el-table-column label="处理部门" prop="handleDept" />
          <el-table-column label="处理意见" prop="opinioncontent" />
          <el-table-column label="处理时间" prop="lauptime" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import DetailHead from '@/components/DetailHead'
import { getProblemDetail, createFeedbackTask, nextFeedbackProcess } from '@/api/problem'
import { getUsersWithPermission } from '@/api/user'
import { taskOpinion } from '@/api/task'
export default {
  components: {
    DetailHead
  },
  data() {
    return {
      tableData: [],
      detailInfo: {},
      fileList: [],
      id: this.$route.query.id,
      stateOptions: [
        { value: '0', label: '暂存' },
        { value: '1', label: '上报' },
        { value: '2', label: '办理中' },
        { value: '3', label: '办结' },
        { value: '4', label: '退回' }
      ],
      handleForm: '',
      submitLoading: false,
      showCreateTask: false,
      showNextProcess: false,
      reviewer: [],
      submitForm: {
        nextNodeId: '',
        feedbackResult: '',
        opinioncontent: '',
        nextUserId: ''
      },
      submitFormRules: {
        nextNodeId: [
          { required: true, message: '请选择是否通过', trigger: 'blur' }
        ],
        feedbackResult: [
          { required: true, message: '请填写最终反馈信息', trigger: 'blur' }
        ],
        opinioncontent: [
          { required: true, message: '请填写处理意见', trigger: 'blur' }
        ],
        nextUserId: [
          { required: true, message: '请选择下一步处理人', trigger: 'blur' }
        ]
      },
      nextNodeId: '',
      prevNodeId: '',
      user: JSON.parse(sessionStorage.getItem('user')),
      nodes: [],
      taskList: {}
    }
  },
  mounted() {
    this.loadDetail()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 加载详情
    loadDetail() {
      getProblemDetail(this.id).then(res => {
        if (res.code === 0) {
          const data = res.data
          this.detailInfo = data.problem || {}
          for (const i in this.stateOptions) {
            const atom = this.stateOptions[i]
            if (this.detailInfo.state === atom.value) {
              this.detailInfo.stateStr = atom.label
              break
            }
          }
          this.fileList = []
          const files = data.files
          files.forEach(each => {
            each.id = each.attachmentid
            each.name = each.filename
            each.url = `${process.env.VUE_APP_DOWNLOAD_URL}/` + each.temppath
          })
          this.fileList = files
          this.taskList = data.taskList || {}

          // 加载处办记录
          if (data.taskList) {
            taskOpinion(data.taskList.workflowid).then(res => {
              if (res.code === 0) {
                res.data = res.data || []
                res.data.forEach(each => {
                  switch (each.opiniontype) {
                    case '0': each.step = '经办人'; break
                    case '1': each.step = '审核人'; break
                    case '2': each.step = '审批人'; break
                  }
                  each.lauptime = each.lauptime ? each.lauptime.replace('T', ' ') : ''
                })
                this.$set(this, 'tableData', res.data)
              } else {
                this.$message.error('加载处办记录失败')
              }
            })
          }

          // 当前节点信息
          this.nodes = data.nodes || []
          if (data.nodes && data.nodes.length > 0) {
            const curNode = data.nodes[0]
            if (curNode.status === 0) {
              if (curNode.curruserid === this.user.primaryKey) {
                this.showNextProcess = true
              }
              switch (curNode.currentnode) {
                case 'feedbackEnter' : {
                  this.nextNodeId = 'handleFeedback'
                  this.prevNodeId = 'overFeedback'
                  this.loadReviewer('problemHandle')
                  break
                }
                case 'handleFeedback': {
                  this.nextNodeId = 'approvelist'
                  this.prevNodeId = 'feedbackEnter'
                  this.loadReviewer('problemAppr')
                  break
                }
                case 'approvelist': {
                  this.nextNodeId = 'endFeedback'
                  this.prevNodeId = 'handleFeedback'
                  break
                }
              }
            } else if (curNode.status === 1) {
              if (curNode.currentnode === 'overFeedback') {
                this.showCreateTask = true
              }
            }
          } else {
            if (this.$util.existValue(this.user.permission, 'problemEnter')) {
              this.showCreateTask = true
            }
          }
        }
      })
    },
    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
    },
    // 发起反馈流程
    createTask() {
      if (this.submitLoading) return
      this.$confirm('是否确定发起反馈审核流程').then(_ => {
        this.submitLoading = true
        createFeedbackTask(this.detailInfo.problemId).then(res => {
          this.submitLoading = false
          if (res.code === 0) {
            this.$message.success('发起反馈流程成功')
            this.$router.go(0)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(_ => {})
    },
    // 加载审核人
    loadReviewer(perm) {
      getUsersWithPermission(perm, this.user.orgId).then(res => {
        if (res.code === 0) {
          this.reviewer = res.data
        }
      })
    },
    submitProcess() {
      if (this.submitLoading) return
      this.$refs.submitForm.validate(valid => {
        if (!valid) return
        this.$confirm('是否确定提交处理').then(_ => {
          let nextUserIds = this.submitForm.nextUserId
          let nextUserNames = ''
          // 返回上一步（退回）
          if (this.nextNodeId === 'endFeedback') {
            // 如果办结步骤（最终退回与办结），则直接使用当前用户信息
            nextUserIds = this.user.primaryKey
            nextUserNames = this.user.nickname
          } else if (this.submitForm.nextNodeId === this.prevNodeId) {
            // 如果是退回步骤，则去上一步操作人
            if (this.prevNodeId === 'overFeedback') {
              // 返回问题反馈
              nextUserIds = this.user.primaryKey
              nextUserNames = this.user.nickname
            } else {
              const prevNode = this.nodes[1]
              nextUserIds = prevNode.curruserid
            }
          } else {
            // 取选中的审核人
            for (const i in this.reviewer) {
              if (this.reviewer[i].primaryKey === nextUserIds) {
                nextUserNames = this.reviewer[i].name
              }
            }
          }
          const form = {
            tasklistid: this.taskList.tasklistid,
            workflowId: this.taskList.workflowid,
            bizseq: this.taskList.bizseqid,
            nextNodeId: this.submitForm.nextNodeId,
            nextUserIds: nextUserIds,
            nextUserNames: nextUserNames,
            opiniontype: this.nextNodeId === 'handleFeedback' ? '0' : this.nextNodeId === 'approvelist' ? '1' : '2',
            opinioncontent: this.submitForm.opinioncontent
          }
          if (this.nextNodeId === 'handleFeedback') {
            form.feedbackOpinion = this.submitForm.feedbackResult
          }
          this.submitLoading = true
          nextFeedbackProcess(form).then(res => {
            this.submitLoading = false
            if (res.code === 0) {
              this.$message.success('提交成功')
              if (this.nextNodeId === 'endFeedback') {
                this.$router.push({ path: '/market/problem' }) // 办结
              } else if (nextUserIds !== this.user.primaryKey) {
                this.$router.push({ path: '/market/problem' }) // 下一步不是自己时
              } else {
                this.$router.go(0)
              }
            }
          })
        }).catch(_ => {})
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-form{
    width:80%;
    margin-top:30px;
    .main-title{
        font-size: 20PX;
        font-family: PingFang SC, PingFang SC-Regular Microsoft YaHei, Microsoft YaHei-Bold;
        color: #292a2c;
        margin-bottom:24px;
        padding-left: 20px;
    }
    .main-body{
      padding: 20px;
        >div:not(:first-child){
            margin-bottom:10px;
        }
        .el-col-4{
            line-height:40px;
            font-size: 16PX;
            font-family: Microsoft YaHei, Microsoft YaHei-Bold;
            font-weight: 700;
            color: #5a5e66;
        }
        .el-col-8{
            padding-right:30px;
        }
        &.table{
          border: 1px solid #d9d9d9;
          padding:25px;
          .el-form-item{
            .el-form-item__label{
              font-size: 16PX;
              color:#5a5e66;
              font-weight: 700;
            }
          }
        }
    }
}
.main-body .el-row{
  border: 1px solid #c5e1fd;
  background: #eaf4fe;
  margin-bottom: 0!important;
}
.main-body .el-row{
  border-bottom:0;
}
.main-body .el-row:last-child{
  border-bottom: 1px solid #c5e1fd;
}
.main-form .main-body .el-col-4{
  padding:10px;
  text-align: right;
}
.main-form .main-body .el-col-20{
  padding:10px;
  border-left: 1px solid #c5e1fd;
  background: #fff;

  /* border-right: 1px solid #c5e1fd; */
}
.main-form .main-body .el-col-8{
  padding:10px;
  border-left: 1px solid #c5e1fd;
  background: #fff;

}
</style>
<style lang="scss">
.market.problem.detail{
  .main-body{
    &.table{
      border:0;
          .el-form-item{
            .el-form-item__label{
              font-size: 16PX;
              color:#5a5e66;
              font-weight: 700;
            }
          }
        }
  }
}
</style>
