<template>
  <div class="detail-block" v-loading="loading">
    <el-form :model="formData" ref="demandForm" label-width="auto" :rules="rules">
      <baseTitle title="需求征集详情"></baseTitle>
      <el-row>
        <el-col :span="12" v-if="checkFormPrem('requirementName')">
          <el-form-item label="名称">
            <span>{{ formData.requirementName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="checkFormPrem('companyIds')">
          <el-form-item label="所属公司">
            <span>{{ formData.companyIds }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="checkFormPrem('collectType')">
          <el-form-item label="征集类型">
            <span>{{ formData.collectType }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="checkFormPrem('deadline')">
          <el-form-item label="截止时间">
            <span>{{ formData.deadline }}</span>
          </el-form-item>
        </el-col>
        <baseTitle title="征集说明"></baseTitle>
        <el-col :span="24" v-if="checkFormPrem('collectExplain')">
          <el-form-item>
            <el-card style="width: 100%">
              <div v-html="formData.collectExplain">
              </div>
            </el-card>
          </el-form-item>
        </el-col>
        <baseTitle title="附件列表"></baseTitle>
        <el-col :span="24" v-if="checkFormPrem('collectExplain')">
          <el-form-item>
            <fvTable style="width: 100%;max-height: 200px" v-if="showTable" :tableConfig="tableConfig"
                     :data="formData.fileList" :isSettingCol="false" :pagination="false">
              <template #empty>
                <el-empty :image-size="90" description="暂无数据" style="padding: 0"/>
              </template>
            </fvTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div v-if="processInstanceData.taskId">
            <baseTitle title="审核意见"></baseTitle>
            <el-form-item prop="auditOpinion">
              <el-input
                  v-model="formData.auditOpinion"
                  :rows="3"
                  type="textarea"
                  placeholder="请输入审核意见"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <div class="approval-record">
        <baseTitle title="审批记录"></baseTitle>
        <div class="process">
          <operation-render v-if="processDiagramViewer" :operation-list="processInstanceData.operationList"
                            :state="processInstanceData.state"/>
          <process-diagram-viewer v-if="processDiagramViewer"/>
        </div>
      </div>
    </el-form>
    <div class="oper-page-btn" v-if="processInstanceData.state === '1' && processInstanceData.taskId">
      <el-button @click="handleReject(demandForm)">驳回</el-button>
      <el-button color="#DED0B2" @click="handleSubmit">同意</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import OperationRender from '@/views/workflow/common/OperationRender.vue'
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue'
import {useProcessStore} from '@/stores/processStore.js';
import {getInfo, agreeTask, rejectTask, downloadFile} from "@/api/project-demand/index.js";
import {getSubCompOpt} from '@/api/user/user.js'
import {ElMessage} from "element-plus";
import {useTagsView} from '@/stores/tagsview.js'
import {matterTree} from '@/utils/matterTree.js';

const tagsViewStore = useTagsView()
const router = useRouter()
const route = useRoute()
const form = ref();
const loading = ref(false)
const demandForm = ref()
const processStore = useProcessStore()
const companyOption = ref([])
const formPermMap = ref(new Map());
const processInstanceData = ref({})
const showTable = ref(false)
const processDiagramViewer = ref(false)
const processTree = ref()
const companyNameArray = ref([])
const formData = ref({})
const rules = reactive({
  auditOpinion: [{required: true, message: '请输入审核意见', trigger: 'blur'}],
})
const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: '80',
    },
    {
      prop: 'originalFileName',
      label: '文件名',
      align: 'center',
    },
    {
      prop: 'tag',
      label: '标签',
      align: 'center'
    },
    {
      prop: 'size',
      label: '文件大小',
      align: 'center',
      currentRender: ({row, index}) => (parseInt(row.size / 1024) + 'KB')
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      currentRender: ({row, index}) => {
        return (
            <el-button type="primary" link onClick={() => handleDownload(row)}>下载</el-button>
        )
      }
    }
  ]
})

const checkFormPrem = (formKey) => {
  if (formPermMap.value.hasOwnProperty(formKey)) {
    let formItem = formPermMap.value[formKey];
    return formItem.perm === 'READ'
  } else {
    return true;
  }
}


const fromPrem = (formKey) => {
  let formItem = formPermMap.value[formKey];
  return formItem.perm
}

const handleSubmit = () => {
  let approve = {
    taskId: processInstanceData.value.taskId,
    auditOpinion: formData.value.auditOpinion,
    formData: formData.value
  }
  agreeTask(approve).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      router.push({
        name: 'Requirement'
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleReject = (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) return
    let approve = {
      taskId: processInstanceData.value.taskId,
      auditOpinion: formData.value.auditOpinion,
    }
    rejectTask(approve).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg)
        tagsViewStore.delVisitedViews(router.currentRoute.value.path)
        router.push({
          name: 'Requirement'
        })
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const getCompanyOption = async () => {
  const res = await getSubCompOpt()
  companyOption.value = res.data
}

const getDataSourceOptionItem = (val) => {
  if (val !== undefined) {
    val.forEach(item => {
      matterTree(companyNameArray.value, companyOption.value, item)
    })
  }
  return companyNameArray.value.join('，');
}

const handleDownload = (row) => {
  downloadFile(row.fileId).then(res => {
    const blob = new Blob([res])
    let a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = row.originalFileName
    a.click()
  })
}
const init = async () => {
  if (!route.query.id) return;
  await getCompanyOption()
  getInfo(route.query.id).then(res => {
    loading.value = false
    let data = res.data
    formData.value = data.formData;
    data.formData.companyIds = getDataSourceOptionItem(data.formData.companyIds)
    processInstanceData.value = data
    processStore.setDesign(data)
    processStore.runningList.value = data.runningList;
    processStore.endList.value = data.endList;
    processStore.noTakeList.value = data.noTakeList;
    processStore.refuseList.value = data.refuseList;
    processStore.passList.value = data.passList;
    nextTick(() => {
      processDiagramViewer.value = true
      showTable.value = true
    })
  })
}
onMounted(async () => {
  loading.value = true
  await init()
})
</script>

<style lang="scss" scoped>
:deep(.el-empty__description) {
  margin-top: 0;
}

.detail-block {
  overflow: hidden;
  padding-right: 10px;

  .info {
    display: flex;
    flex-wrap: wrap;

    > div {
      width: 350px;
      margin-bottom: 15px;
      margin-right: 10px;

      > span:first-child {
        color: black;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  .approval-record {
    padding-bottom: 30px;

    .process {
      position: relative;
    }
  }
}

</style>
