<template>
  <div v-loading="loading" class="add-block">
    <baseTitle title="需求征集信息录入"></baseTitle>
    <el-form :model="formData" inline class="query-form" ref="demandForm" :rules="rules">
        <el-form-item label="名称" prop="requirementName">
          <el-input v-model="formData.requirementName" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="companyIds">
          <el-tree-select v-model="formData.companyIds" :data="companyOption" style="width: 100%;"
                          filterable clearable :check-strictly="true" multiple/>
        </el-form-item>
        <el-form-item label="征集类型" prop="collectType">
          <el-select v-model="formData.collectType" placeholder="征集类型" clearable filterable>
            <el-option
                v-for="item in typeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="checkFormPrem('deadline')" label="截止时间" prop="deadline">
          <el-config-provider>
            <el-date-picker
                v-model="formData.deadline"
                type="datetime"
                placeholder="截止时间"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-config-provider>
        </el-form-item>
    </el-form>
    <baseTitle title="征集说明"></baseTitle>
    <Tinymce  v-if="showTinymce" image-url="/notice/file" file-url="/notice/file"
              v-model:value="formData.collectExplain" height="300" />
    <baseTitle title="申请文件"></baseTitle>
    <file-upload v-if="checkFormPrem('fileList')" @getFile="getFile"/>
    <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>
    <div class="approval-record">
      <baseTitle title="流程"></baseTitle>
      <process-diagram-viewer mode="view" v-if="processDiagramViewer"/>
      <!--      <div class="process" id="approvalRecord">-->
      <!--        <process-tree ref="processTree" mode="view" id-name="approvalRecord"/>-->
      <!--      </div>-->
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" v-if="routerName==='Requirement/add'" @click="handleSubmit(demandForm)">提交</el-button>
      <el-button color="#DED0B2" v-else @click="handleResubmit">重新提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import {useAuthStore} from '@/stores/userstore.js'
import {useProcessStore} from '@/stores/processStore.js';
import {
  getWorkflowInfo,
  addRequirement,
  getFormInfo,
  resubmit,
  deleteFile,
  downloadFile
} from "@/api/project-demand/index.js";
import FileUpload from "@/components/FileUpload.vue";
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {useRoute, useRouter} from 'vue-router'
import {getSubCompOpt} from '@/api/user/user.js'
import {useTagsView} from '@/stores/tagsview.js'

const tagsViewStore = useTagsView()
const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()
const demandForm = ref()
const dateValue = ref()
const formData = ref({
  requirementName: '',
  companyIds: '',
  collectType: '',
  deadline: '',
  collectExplain: '',
  fileList: []
})
const showTinymce = ref(true)
const routerName = ref(router.currentRoute.value.name)
const processDiagramViewer = ref(false)
const typeOption = ref([
  {
    label: "需求征集",
    value: '需求征集'
  }
])
const companyOption = ref([])
const form = ref(null)
const fileList = ref([])
const loading = ref(false)
const showTable = ref(true)
const processStore = useProcessStore()
const processInstanceData = ref()
const formPermMap = ref(new Map());
const rules = reactive({
  requirementName: [{required: true, message: '请输入需求名称', trigger: 'blur'}],
  companyIds: [{required: true, message: '请选择所属公司', trigger: 'blur'}],
  collectType: [{required: true, message: '请选择征集类型', trigger: 'blur'}],
  deadline: [{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',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        return (
            <div>
              <el-button type="primary" link onClick={() => handleDownload(row)}>下载</el-button>
            </div>
        )
      }
    // <el-button type="primary" size="large" link onClick={() => handleDelete(row)}>删除</el-button>
    }
  ]
})

const checkFormPrem = (formKey) => {
  if (formPermMap.value.hasOwnProperty(formKey)) {
    let formItem = formPermMap.value[formKey];
    return formItem.perm  === 'EDIT'
  } else {
    return 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 compositeParam = (item) => {
  let tag = ''
  if (!formData.value.collectType && routerName.value === 'Requirement/add') {
    tag = '需求征集'
  }else if(routerName.value === 'Requirement/edit'){
    tag = '需求征集'
  }
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    processNodeTag: null,
    tag: tag,
    userId: authStore.userinfo.userId
  }
}
const getFile = (val) => {
  console.log('上传文件', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  formData.value.fileList.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
}

const init = async () => {
  const res = await getSubCompOpt()
  companyOption.value = res.data
  getWorkflowInfo().then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    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;
      formPermMap.value = data.formPermMap
      // const entriesArray = Object.entries(data.formPermMap);// 使用Map构造函数将键值对数组转换为Map对象
      // formPermMap.value = new Map(entriesArray);
      nextTick(() => {
        processDiagramViewer.value = true
      })
    } else {
    }
  })
}
const submitParam = (item) => {
  let files = []
  item.fileList.forEach(item => {
    let obj = {
      fileId: item.fileId,
      tag: item.tag
    }
    files.push(obj)
  })
  return {
    collectExplain: item.collectExplain,
    collectType: item.collectType,
    companyIds: item.companyIds,
    deadline: item.deadline,
    requirementId: item.requirementId ? item.requirementId : 0,
    requirementName: item.requirementName,
    fileList: files,
    deploymentId: processInstanceData.value.deploymentId
  }
}
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) return
    const {msg,code} = await addRequirement(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: 'Requirement'
      })
    }
  })
}
const handleResubmit = () => {
  resubmit(submitParam(formData.value)).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: 'Requirement'
      })
    }
  })
}
const getDetailInfo = async () => {
  getFormInfo(route.query.id).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      formData.value = res.data
      showTinymce.value = false
      showTable.value = false
      nextTick(() => {
        showTinymce.value = true
        showTable.value = true
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleBack = () => {
  history.back()
}
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除名称为${row.originalFileName}的表格吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteFile(row.fileId).then(res => {
      if (res.code === 1000) {
        ElMessage.success("删除成功");
        formData.value.fileList.splice(formData.value.fileList.findIndex((item) => item.id === row.fileId), 1);
      }
    });
  }).catch(() => {
    ElMessage.warning("用户取消删除! ");
  })
}

onMounted(async () => {
  loading.value = true
  await init()
  if (route.query.id) {
    await getDetailInfo()
  }
  loading.value = false
})
</script>

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

.add-block {
  //display: flex;
  //justify-content: space-between;
  overflow-x: hidden;
  overflow-y: auto;

  a {
    cursor: pointer;
    font-size: 14px;
    color: #2a99ff;
  }

  .approval-record {
    position: relative;
  }
}
</style>
