<template>
    <hc-new-dialog v-model="isShow" :title="title" :widths="widths" @close="cancelReportClick">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-width="auto" size="large">
            <el-form-item label="任务名称" prop="taskName">
                <el-input v-model="formModel.taskName" disabled />
            </el-form-item>
            <el-form-item label="验收日期" prop="startDate">
                <el-date-picker v-model="formModel.startDate" type="date" class="block" value-format="YYYY-MM-DD" :clearable="false" />
            </el-form-item>
            <el-form-item v-if="isDatas && reportDatas.length > 0" label="申请内容">
                <!-- <div class="task-tag-data-box">
                    <template v-for="(item, index) in reportDatas" :key="item.id">
                        <el-tag type="info" size="default" closable @close="taskTagClose(index)">{{ item.name }}</el-tag>
                    </template>
                </div> -->
                <div v-infinite-scroll="load" class="task-tag-data-box" style="overflow: auto">
                    <template v-for="(item, index) in tableData" :key="index">
                        <el-tag type="info" size="default" closable @close="taskTagClose(index)">{{ item?.name }}</el-tag>
                    </template>
                </div>
            </el-form-item>
            <el-form-item label="上传附件">
                <HcFormUpload
                    :src="formModel.attachmentPdfUrlName"
                    @upload="formItemUpload"
                />
            </el-form-item>
            <el-form-item label="验收专家信息" prop="list">
                <HcReportExperts v-model="formModel.list" />
            </el-form-item>
            <el-form-item label="申请说明">
                <el-input v-model="formModel.taskContent" type="textarea" placeholder="请输入申请说明" :autosize="{ minRows: 3, maxRows: 5 }" />
            </el-form-item>
            <el-form-item label="任务流程" prop="fixedFlowId">
                <el-select v-model="formModel.fixedFlowId" block @change="handleProcessValue">
                    <el-option v-for="item in processData" :label="item.fixedFlowName" :disabled="item.disabled" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="diyProcessUser" label="任务人" prop="userTasks">
                <HcTasksUser ui="w-full" :project-id="projectId" :contract-id="contractId" @change="diyProcessUserChange" />
            </el-form-item>
            <el-form-item v-else label="任务人">
                <div class="form-item-div">{{ linkUserJoinString }}</div>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" @click="cancelReportClick">
                    <HcIcon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="formReportLoading" @click="formReportClick">
                    <HcIcon name="check" />
                    <span>提交</span>
                </el-button>
            </div>
        </template>
        <HcUploadFile ref="HcUploadFileRef" :options="UploadFileOptions" @finish="HcUploadFileFinish" @success="HcUploadFileSuccess" />
    </hc-new-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import tasksFlowApi from '~api/tasks/flow'
import { arrIndex, formValidate, getArrValue } from 'js-fast-way'
import { getTokenHeader } from '~src/api/request/header'
import initialgApi from '~api/initial/initial'

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: '上报审批',
    },
    widths: {
        type: String,
        default: '47rem',
    },
    taskName: {
        type: String,
        default: '',
    },
    ids: {
        type: String,
        default: null,
    },
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    url: {
        type: [String, Number],
        default: '',
    },
    datas: {
        type: Array,
        default: () => ([]),
    },
    isDatas: {
        type: Boolean,
        default: false,
    },
    addition: {
        type: Object,
        default: () => ({}),
    },
})

const emit = defineEmits(['hide', 'finish', 'tagClose'])
//变量
const isShow = ref(props.show)
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const ApiUrl = ref(props.url)
const reportDatas = ref(props.datas)

//表单
const formRef = ref(null)
const processData = ref([])
const formModel = ref({
    projectId: projectId.value, contractId: contractId.value, archiveIds: props.ids, list: [],
    userTasks: null, taskName: props.taskName, fixedFlowId: '', ...props.addition,
})
const formRules = ref({
    startDate: {
        required: true,
        trigger: 'blur',
        message: '请选择验收日期',
    },
    list: {
        required: true,
        trigger: 'blur',
        message: '请完善专家信息',
    },
    fixedFlowId: {
        required: true,
        trigger: 'blur',
        message: '请选择任务流程',
    },
    userTasks: {
        required: true,
        trigger: 'blur',
        message: '请选择任务人',
    },
})

//监听
watch(() => [
    props.show,
    props.projectId,

    props.taskName,
    props.ids,
    props.url,
    props.addition,
    props.datas,
], ([val, pid, name, ids, url, addition, datas]) => {
    isShow.value = val
    projectId.value = pid

    ApiUrl.value = url
    //更新到表单数据
    formModel.value = {
        projectId: pid, archiveIds: ids, taskName: name,
        taskContent: '', fixedFlowId: '', list: [],
        ...addition,
    }
    reportDatas.value = datas
         //判断数据长度有没有9个，有就先添加9个，没有直接获取所有数据
         if (reportDatas.value.length > 9) {
          for (let i = 0;i < reportDatas.value ;i++) {
            tableData.value[i] = reportDatas.value[i]
          }
        } else {
          tableData.value = reportDatas.value
        }
 
    if (val) {
        getProcessDatasApi()
    }
})

//渲染完成
onMounted(() => {
    getProcessDatasApi()
})

const processDefaultData = [{ id: 0, fixedFlowName: '自定义流程', disabled: false }]
const getProcessDatasApi = () => {
    if (isShow.value) {
        getProcessData()
    }
}

//获取流程数据
const linkUserJoinString = ref('')
const getProcessData = async () => {
    linkUserJoinString.value = ''
    const { error, code, data } = await tasksFlowApi.getPageData({
        projectId: projectId.value,
        contractId: contractId.value,
        current: 1, size: 100,
    })
    if (!error && code === 200) {
        const arr = getArrValue(data['records'])
        processData.value = [...processDefaultData, ...arr]
    } else {
        processData.value = processDefaultData
    }
}

//流程数据切换
const diyProcessUser = ref(false)
const handleProcessValue = (val) => {
    if (val > 0) {
        diyProcessUser.value = false
        const list = processData.value
        const index = arrIndex(list, 'id', val)
        linkUserJoinString.value = list[index]?.linkUserJoinString
    } else {
        linkUserJoinString.value = ''
        diyProcessUser.value = true
    }
}

//自定义流程任务人选择完毕
const diyProcessUserChange = (user) => {
    formModel.value.userTasks = user
}

//审批内容的标签移除
const taskTagClose = (index) => {
    reportDatas.value.splice(index, 1)
    emit('tagClose', index)
    if (reportDatas.value.length <= 0) {
        window.$message?.warning('请重新选择要上报的内容')
        cancelReportClick()
    }
}

//取消
const cancelReportClick = () => {
    linkUserJoinString.value = ''
    isShow.value = false
    emit('hide', false)
}
//上报
const formReportClick = async () => {
    const res = await formValidate(formRef.value)
    if (res) await batchApprovalApi()
}

//上报请求
const formReportLoading = ref(false)
const batchApprovalApi = async () => {
    console.log(formModel.value)
    formReportLoading.value = true
    //发起请求
    const { error, code, data } = await initialgApi.saveApply (formModel.value)
    
    linkUserJoinString.value = ''
    formReportLoading.value = false
    if (!error && code === 200) {
        isShow.value = false
        window.$message?.success('上报成功')
        emit('hide', false)
        emit('finish', data)
    } else {
        processData.value = []
    }
}
//上传配置
const UploadFileOptions = {
    //此处设置header
    headers: getTokenHeader(),
    accept:'application/pdf,.doc,.docx,application/msword',
    accept_tip: 'PDF、Word格式文件',
}
const HcUploadFileRef = ref(null)
//上传
const formItemUpload = () => {
    HcUploadFileRef.value?.selectFile()
}






// 文件全部上传完成
const HcUploadFileFinish = () => {
  
    HcUploadFileRef?.value.setModalShow(false)
}
// 文件全部上传成功
const HcUploadFileSuccess = (res) => {
    formModel.value.attachmentPdfUrl = res.resData.link
    formModel.value.attachmentPdfUrlName = res.resData.originalName
}
const tableData = ref([])
const needle = ref(10)
const load = async () => {
    const res = await queryData()
          if (res) {
            tableData.value = res
          }
}
const queryData = async ()=>{
    console.log('查询数据')
        let ortab = tableData.value
        if (needle.value < reportDatas.value.length) {
           let pusharr = reportDatas.value.slice(needle.value, needle.value + 10)
            pusharr.forEach((ele)=>{
                ortab.push(ele)
          })
          needle.value = needle.value + 10
          return ortab
        }
      
}
</script>

<style lang="scss">
.task-tag-data-box {
    position: relative;
    border: 1px solid #e0e0e6;
    border-radius: 4px;
    padding: 5px;
    min-height: 40px;
    display: flex;
    align-items: center;
    flex-flow: row wrap;
    width: 100%;
    max-height: 300px;
    overflow-y: auto;
    overflow-x: hidden;
    .el-tag {
        margin: 5px;
    }
}
.hc-report-modal-form-item .hc-table-ref-box {
    margin-top: 14px;
}
</style>
