<template>
  <div v-loading="loading" class="add-block">
    <baseTitle title="需求征集信息录入"></baseTitle>
    <el-form :model="formData" inline class="query-form" ref="demandForm" :rules="rules">
      <div class="left-info">
        <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 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>
      </div>
    </el-form>
    <baseTitle title="征集说明"></baseTitle>
    <Tinymce image-url="/notice/file" file-url="/notice/file" v-model:value="formData.collectExplain" height="300" v-if="showTinymce"/>
    <baseTitle title="申请文件"></baseTitle>
    <file-upload @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" @click="handleSubmit(demandForm)">提交</el-button>
      <el-button color="#DED0B2" @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} from "@/api/project-demand/index.js";
import FileUpload from "@/components/FileUpload.vue";
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import {ElMessage, ElMessageBox} 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: ''
})
const showTinymce = ref(true)
const processDiagramViewer = ref(false)
const typeOption = ref([
  {
    label: "需求征集",
    value: '需求征集'
  }
])
const companyOption = ref([])
const form = ref(null)
const fileList = ref(null)
const loading = ref(false)
const showTable = ref(false)
const processStore = useProcessStore()
const processInstanceData = ref()
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>
              <a style="cursor: pointer;font-size: 14px;color: #2a99ff;" href={row.url}>下载</a>
              <el-button type="primary" size="large" link onClick={() => beforeRemove(row)}>删除</el-button>
            </div>
        )
      }
    }
  ]
})
const compositeParam=(item)=>{
    return  {
      fileId: item.id,
      size: item.size,
      originalFileName: item.originalFilename,
      fileType: item.fileType,
      url: item.url,
      processNodeTag: null,
      tag: formData.value.collectType,
      userId: authStore.userinfo.userId
    }
}
const getFile = (val) => {
  console.log('上传文件',val)
  showTable.value = false
  nextTick(() => {
    showTable.value = true
  })
  let fileObj = {}
  let newFileArray = []
  if (route.query.isAdd === undefined) {
    val.forEach(item => {
      fileObj =compositeParam(item)
      newFileArray.push(fileObj)
      formData.value.fileList.push(fileObj)
    })
    fileList.value = formData.value.fileList
  } else {
    val.forEach(item => {
      fileObj =compositeParam(item)
      newFileArray.push(fileObj)
    })
    formData.value.fileList = newFileArray
    fileList.value = newFileArray
  }

}

const init = async () => {
  const res = await getSubCompOpt()
  companyOption.value = res.data
  getWorkflowInfo().then(res => {
    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
    })
  })
}

const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) return
    let params = {
      ...formData.value,
      requirementId: 0,
      files: fileList.value,
      deploymentId: processInstanceData.value.deploymentId
    }
    let res = await addRequirement(params)
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      await router.push({
        path: '/projectdemand/demandcollection'
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleResubmit = () => {
  resubmit({
    ...formData.value,
    files: fileList.value,
    deploymentId: processInstanceData.value.deploymentId
  }).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      router.push({
        path: '/projectdemand/demandcollection'
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const getDetailInfo = async () => {
  getFormInfo(route.query.id).then(res => {
    if (res.code === 1000) {
      console.log(res)
      ElMessage.success(res.msg)
      formData.value = res.data
      showTinymce.value = false
      nextTick(() => {
        showTinymce.value = true
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleBack = () => {
  history.back()
}
const beforeRemove = (row) => {
  ElMessageBox.confirm(`确认删除名称为${row.originalFileName}的表格吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleRemove(row)
  }).catch(() => {
    ElMessage.warning("用户取消删除! ");
  })
}

const handleRemove = (row) => {
  deleteFile(row.fileId).then(res => {
    if (res.code === 1000) {
      ElMessage.success("删除成功");
      fileList.value.splice(fileList.value.findIndex((item) => item.id === row.id), 1);
    }
  });
};
onMounted(async () => {
  loading.value = true
  await init()
  if (route.query.id) {
    await getDetailInfo()
  }
  nextTick(() => {
    showTable.value = true
  })
  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>
