<template>
  <div v-loading="loading" class="add-block">
    <baseTitle title="专项资金信息录入"></baseTitle>
    <el-form :model="formData" ref="fundForm" :rules="rules" label-width="135" style="margin-left: 5px;margin-bottom: -18px">
      <el-row gutter="30">
        <el-col :span="6" >
          <el-form-item label="专项资金名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入专项资金名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="金额(元)" prop="fundAmount" label-width="100">
            <el-input-number v-model="formData.fundAmount" placeholder="请输入金额" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="专项资金情况说明" prop="introduce">
            <el-input
                v-model="formData.introduce"
                style="width:100%"
                :rows="5"
                type="textarea"
                placeholder="请输入专项资金情况说明"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <baseTitle title="附件文件" style="margin-right: 10px"></baseTitle>
    <file-upload @getFile="getFile"/>

    <fvTable style="width: 100%;max-height: 162px;" v-if="showTable"
             :tableConfig="tableConfig" height="162" :data="formData.files"
             :isSettingCol="false" :pagination="false">
      <template #empty>
        <el-empty :image-size="55" description="暂无数据" style="padding: 0"/>
      </template>
    </fvTable>
    <div class="approval-record">
      <div class="approval-title">
        <baseTitle title="审批记录"></baseTitle>
        <div class="diagram">
          <div class="base-title">流程图</div>
          <el-switch
              v-model="changeDiagram"
              style="--el-switch-on-color:#BEA266; --el-switch-off-color:#cecdcd;"
          />
        </div>
      </div>
      <el-empty :image-size="100" description="暂无审批记录"
                v-if="processDiagramViewer&& !opentionData?.operationList&&!changeDiagram"/>
      <!--      <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>-->
      <div class="process">
        <operation-render
            v-if="processDiagramViewer&& opentionData?.operationList && opentionData?.operationList.length > 0&&!changeDiagram"
            :operation-list="opentionData?.operationList"
            :state="opentionData.state"/>
        <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>
      </div>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" v-if="routerName === 'Fund/add'" @click="handleSubmit(fundForm)">提交</el-button>
      <el-button color="#DED0B2" v-else @click="handleResubmit">重新提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
    <file-preview ref="filePreviewRef" v-if="filePreviewShow" :fileName="filePreviewParam.fileName"
                  :fileUrl="filePreviewParam.fileUrl"
                  :fileType="filePreviewParam.fileType"/>
  </div>
</template>

<script setup lang="jsx">
import OperationRender from '@/views/workflow/common/OperationRender.vue'
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import {ElNotification} from "element-plus";
import {addFund, resubmitFund, getFundDetail, getFundDetailProcess, getFundProcess} from "@/api/special-fund";
import {useRouter} from "vue-router";
import {useTagsView} from '@/stores/tagsview.js'
import {useProcessStore} from '@/stores/processStore.js';
import {downloadFile, deleteFile} from "@/api/project-demand";

const changeDiagram = ref(false)
const tagsViewStore = useTagsView()
const router = useRouter()
const route = useRoute()
const processStore = useProcessStore()
const opentionData = ref({})
const loading = ref(false)
const showTable = ref(true)
const processInstanceData = ref()
const fundForm = ref()
const processDiagramViewer = ref(false)
const formData = ref({
  name: '',
  fundAmount: null,
  introduce: '',
  files: []
})
const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: '80',
    },
    {
      prop: 'originalFileName',
      label: '文件名',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => (
          <div style="color: #2a99ff;cursor: pointer;" onClick={() => clickToPreview(row)}>{row.originalFileName}</div>)
    },
    {
      prop: 'tag',
      label: '标签',
      align: 'center'
    },
    {
      prop: 'size',
      label: '文件大小',
      align: 'center',
      currentRender: ({row, index}) => (parseInt(row.size / 1024) + 'KB')
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        return (
            <div>
              <el-button type="primary" link onClick={() => handleDownload(row)}>下载</el-button>
              <popover-delete name={row.originalFileName} type={'文件'} btnType={'danger'}
                              perm={['mosr:requirement:del']}
                              onDelete={() => handleDelete(row)}/>
            </div>
        )
      }
    }
  ]
})
const routerName = ref(router.currentRoute.value.name)
const rules = reactive({
  name: [{required: true, message: '请输入专项资金名称', trigger: ['blur', 'change']}],
  fundAmount: [{required: true, message: '请输入金额', trigger: ['blur', 'change']}],
  introduce: [{required: true, message: '请输入专项资金情况说明', trigger: ['blur', 'change']}],
})

const filePreviewParam = ref({
  fileUrl: '',
  fileName: '',
  fileType: 'pdf'
})
const filePreviewShow = ref(false)
const clickToPreview = (row) => {
  filePreviewShow.value = false
  filePreviewParam.value = {
    fileUrl: row.url,
    fileName: row.originalFileName,
    fileType: row.fileType
  }
  nextTick(() => {
    filePreviewShow.value = true
  })
}
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 handleDelete = (row) => {
  deleteFile(row.fileId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      formData.value.files.splice(formData.value.files.findIndex((item) => item.fileId === row.fileId), 1);
      // showTable.value = formData.value.files.length !== 0;
    }
  });
}
const compositeParam = (item) => {
  let tag = ''
  if (routerName.value === 'Fund/add' || routerName.value === 'Fund/edit') {
    tag = '专项资金'
  }
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: true,
    tag: tag
  }
}
const getFile = (val) => {
  // console.log('上传文件', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  formData.value.files.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
}
const handleBack = () => {
  history.back()
}

const submitParam = (item) => {
  let files = []
  item.files.forEach(item => {
    let obj = {
      fileId: item.fileId,
      tag: item.tag
    }
    files.push(obj)
  })
  return {
    fundAmount: item.fundAmount,
    introduce: item.introduce,
    name: item.name,
    files: files,
    deploymentId: processInstanceData.value.deploymentId
  }
}
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) {
      ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
      return;
    }
    const {msg, code} = await addFund(submitParam(formData.value))
    ElNotification({
      title: '提示',
      message: msg,
      type: code === 1000 ? 'success' : 'error'
    })
    if (code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      await router.push({
        name: 'Fund'
      })
    }
  })
}
const handleResubmit = () => {
  if (!route.query.id) return
  let params = {
    specialFundId: route.query.id,
    ...submitParam(formData.value)
  }
  resubmitFund(params).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      router.push({
        name: 'Fund'
      })
    }
  })
}
const init = async () => {
  processDiagramViewer.value = false
  getFundProcess().then(res => {
    if (res.code === 1000) {
      let data = res.data
      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
      })
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}
const getDetailInfo = async () => {
  getFundDetailProcess(route.query.id).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      formData.value = res.data.formData
      opentionData.value = res.data
      showTable.value = false
      nextTick(() => {
        showTable.value = true
      })
    }
  })
}
onMounted(async () => {
  loading.value = true
  await init()
  if (route.query.id) {
    await getDetailInfo()
  }
  loading.value = false
})
</script>

<style scoped lang="scss">
:deep(.el-table--fit ) {
  height: 300px !important;
}

.add-block {
  padding: 0 40px;
}

:deep(.el-input-number) {
  width: 88.5%;
.el-input__wrapper{
  padding: 1px 11px!important;
}
  .el-input__inner {
    text-align: left;
  }
}

:deep(.el-table__header) {
  .is-leaf:first-child {
    .cell {
      margin-left: -20px !important;
    }
  }
}

:deep(.el-table__body) {
  .el-table__cell:first-child {
    .cell {
      margin-left: -10px !important;
    }
  }
}
</style>
