<template>
  <div class="apply-block">
    <baseTitle title="基础信息"></baseTitle>
    <fvForm :schema="schema" @getInstance="(e)=>baseForm = e"></fvForm>
    <el-form :model="formData" label-width="auto">
      <el-form-item label="抄送人员">
        <Ttsup :modelValue="chooseUserInfo()" @click="chooseUser"/>
      </el-form-item>
    </el-form>
    <user-picker :multiple="true" ref="userPicker" title="请选择抄送人员" v-model:value="userList" @ok="selected"/>
    <AttachmentUpload ref="attachment" label="阶段变更附件" :showTable="showTable" :otherFileList="otherFileList"
                      @getAttachment="getAttachment"
                      @getOtherFile="getOtherFile" :showFileList="true" :formData="formData"
                      :preview="name === 'Phase/edit'"/>
    <div class="approval-record">
      <div style="display: flex;align-items: center;margin-bottom: 20px">
        <baseTitle title="流程图"></baseTitle>
        <el-switch
            v-model="changeDiagram"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color:#BEA266;margin-left: 10px"
        />
      </div>
      <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" v-if="name==='Phase/change'" @click="handleSubmit">提交</el-button>
      <el-button color="#DED0B2" v-else @click="handleResubmit">重新提交</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import UserPicker from "@/views/workflow/process/common/UserPicker.vue";
import Ttsup from './components/ToolToShowUserPicker.vue'
import {getPhaseProcess, submitPhaseChange, getPhaseForm, resubmitPhaseForm} from "@/api/project-manage";
import {ElNotification} from "element-plus";
import {useProcessStore} from '@/stores/processStore.js';
import {useTagsView} from '@/stores/tagsview.js'
import {computed, ref} from "vue";
import {getBaseInfoApi} from "@/components/steps/api";

const changeDiagram = ref(false)
const tagsViewStore = useTagsView()
const router = useRouter()
const route = useRoute()
const attachment = ref()
const userPicker = ref()
const name = ref(router.currentRoute.value.name)
const loading = ref(false)
const formData = ref({})
const file = ref({})
const deploymentId = ref()
const showTable = ref(true)
const otherFileList = ref([])
const processInstanceData = ref()
const processDiagramViewer = ref(true)
const userList = ref([])
const processStore = useProcessStore()
const schema = computed(() => {
  return [
    {
      label: '征集名称',
      prop: 'requirementName',
      colProps: {
        span: 12
      }
    },
    {
      label: '项目名称',
      prop: 'projectName',
      colProps: {
        span: 12
      }
    }
  ]
})
const baseForm = ref()
const getBaseInfo = async () => {
  try {
    const {code, data} = await getBaseInfoApi(route.query.projectId)
    baseForm.value.setValues(data)
  } catch {
  }
}

getBaseInfo()
const compositeParam = (item) => {
  let tag = ''
  if (name.value === 'Phase/change') {
    tag = '阶段变更'
  }
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: false,
    tag: tag
  }
}
const getAttachment = (val) => {
  console.log('上传文件getAttachment', val)
  formData.value.singleFile = compositeParam(val)
}
const getOtherFile = (val) => {
  console.log('上传文件getOtherFile', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  otherFileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
}

const getFileParam = (item) => {
  return {
    fileId: item.fileId,
    tag: item.tag
  }
}

const chooseUser = () => {
  userPicker.value.showUserPicker()
}
const chooseUserInfo = () => {
  if (userList.value.length > 0) {
    return userList.value.map(item => {
      return item.name
    }).join('，')
  } else {
    return "请选择抄送人员"
  }
}
const selected = (select) => {
  let userInfoList = []
  for (let val of select) {
    let userInfo = {
      id: val.id,
      name: val.name,
      avatar: val.avatar,
    }
    userInfoList.push(userInfo)
  }
  userList.value = userInfoList
}
const handleSubmit = async () => {
  let files = []
  otherFileList.value?.forEach(item => {
    files.push(getFileParam(item))
  })
  let userIds = []
  if (userList.value.length > 0) {
    userIds = userList.value?.map(item => {
      return item.id
    })
  }
  if (formData.value.singleFile !== undefined) {
    formData.value.singleFile = getFileParam(formData.value.singleFile)
  }
  let params = {
    deploymentId: deploymentId.value,
    requirementId: route.query.id,
    fileList: files,
    singleFile: formData.value.singleFile,
    projectId: route.query.projectId,
    userIds: userIds
  }
  if (!attachment.value.isSingleFile) {
    attachment.value.validate()
    ElNotification({
      title: '提示',
      message: '请上传附件',
      type: 'error'
    })
    return;
  } else {
    attachment.value.clearValidate()
  }
  let res = await submitPhaseChange(params)
  ElNotification({
    title: '提示',
    message: res.msg,
    type: res.code === 1000 ? 'success' : 'error'
  })
  if (res.code === 1000) {
    tagsViewStore.delVisitedViews(router.currentRoute.value.path)
    await router.push({
      name: 'Implementation'
    })
  }
}
const handleResubmit = (instance) => {
  let otherFiles = []
  if (name.value === 'Phase/edit') {
    attachment.value.allFileList?.forEach(item => {
      otherFiles.push(getFileParam(item))
    })
  }
  let userIds = []
  if (userList.value.length > 0) {
    userIds = userList.value?.map(item => {
      return item.id
    })
  }
  if (attachment.value.singleFile == null) {
    attachment.value.validate()
    ElNotification({
      title: '提示',
      message: '请上传附件',
      type: 'error'
    })
    return;
  } else {
    attachment.value.clearValidate()
  }
  let params = {
    deploymentId: deploymentId.value,
    requirementId: route.query.id,
    fileList: otherFiles,
    singleFile: attachment.value.singleFile,
    projectId: route.query.projectId,
    userIds: userIds
  }
  console.log('重新提交params', params)
  resubmitPhaseForm(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: 'Implementation'
      })
    }
  })
}
const init = async () => {
  const {msg, code, data} = await getPhaseProcess()
  processDiagramViewer.value = false
  if (code === 1000) {
    deploymentId.value = data.deploymentId
    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: msg,
      type: 'error'
    })
  }
}
const getDetailInfo = async () => {
  getPhaseForm(route.query.projectId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      formData.value = res.data
      loading.value = false
    }
  })
}
onMounted(async () => {
  await init()
  if (name.value === 'Phase/edit') {
    loading.value = true
    await getDetailInfo()
  }
})
</script>

<style scoped>
.apply-block {
  margin: 15px 0;
}
</style>
