<template>
    <hc-drawer v-model="isShow" to-id="node-card-plan" is-close @close="goBack">
        <hc-card>
            <template #header>
                <el-link type="primary" @click="goBack">返回</el-link>
            </template>
            <template #extra>
                <HcTooltip keys="system-service-plan-save-btn">
                    <el-button
                        v-if="status === 2 || status === 3 || status === 4"
                        :disabled="!isWriteUserAuthorized"
                        class="ml-6"
                        hc-btn
                        keys="system-service-plan-save-btn"
                        type="primary"
                        :loading="saveLoading"
                       
                        @click="savePlan"
                    >
                        <HcIcon name="save" />
                        保存数据
                    </el-button>
                    <el-button
                        v-else
                       
                        class="ml-6"
                        hc-btn
                        keys="system-service-plan-save-btn"
                        type="primary"
                        :loading="saveLoading"
                        @click="savePlan"
                    >
                        <HcIcon name="save" />
                        保存数据
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="system-service-plan-preview-btn">
                    <el-button
                        class="node-card-plan-btn ml-6"
                        hc-btn
                        keys="system-service-plan-preview-btn"
                        color="#3F9EFF"
                        :loading="preViewLoad"
                        :disabled="dataId.length === 0 "
                        @click="previewPlan"
                    >
                        <HcIcon name="eye" />
                        预览
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="system-service-plan-send-btn">
                    <el-button
                        v-if="status === 1"
                        class="node-card-plan-btn ml-6"
                        hc-btn
                        keys="system-service-plan-send-btn"
                        type="warning"
                        :loading="sendPlanLoad"
                        :disabled="!isWriteUserAuthorized || dataId.length === 0 "
                        @click="sendPlan"
                    >
                        <HcIcon name="send-plane" />
                        发送计划
                    </el-button>
                </HcTooltip>
           
                <HcTooltip keys="system-service-plan-back-btn">
                    <el-button
                        v-if="status === 2"
                        class="node-card-plan-btn ml-6"
                        hc-btn
                        keys="system-service-plan-back-btn"
               
                        type="warning"
                        :disabled="!isSendUserAuthorized"
                        :loading="backPlanLoad"
                        @click="backPlan"
                    >
                        <HcIcon name="arrow-go-back" />
                        计划回退
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="system-service-plan-comfirm-btn">
                    <el-button
                        v-if="status === 2"
                        :loading="confirmPlanLoad"
                        class="node-card-plan-btn ml-6"
                        hc-btn
                        keys="system-service-plan-comfirm-btn"
                        type="success"
                        :disabled="!isSendUserAuthorized"
                        @click="confirmPlan"
                    >
                        <HcIcon name="check" />
                        确认计划
                    </el-button>
                </HcTooltip>
            </template>
      

            <div class="hc-table-form-box">
                <HcTableForm
                    ref="tableFormRef"
                    :form="tableFormData"
                    :html="excelHtmlData"
                    :loading="loading"
                    :pkey="excelIdVal"
                    :disabled="!isTableForm"
                    @render="tableFormRender"
                />
            </div>
        </hc-card>
        <!-- 选择任务人 -->
        <HcUserModal v-model="isUserModalShow" :data="userData" :datas="dataInfo" @finish="fixedUserFinish" />
    </hc-drawer>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { arrToKey, deepClone, getObjVal, isString } from 'js-fast-way'
import HcUserModal from './hc-tasks-user/user-modal.vue'
import { useAppStore } from '~src/store'
import dataApi from '~api/systemService/service'
import { toPdfPage } from '~uti/btn-auth'

//参数
const props = defineProps({
    type: {
        type:[String, Number],
        default:'',
    },
    dataId: {
        type:[String, Number],
        default:'',
    },
})
const emit = defineEmits(['close'])
const type = ref(props.type)
const dataId = ref(props.dataId)
const isShow = defineModel('modelValue', {
    default: false,
})
const tableFormRef = ref(null)
const tableFormData = ref({})
const excelHtmlData = ref('')
const loading = ref(false)
const excelIdVal = ref('')
const isTableForm = ref(false)
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const user_id = ref(useAppState.getUserInfo.user_id ?? '')
const status = ref()

watch(isShow, (val) => {

    
    if (val) {
          if (val) getExcelHtml()
             tableFormData.value = {}
                excelHtmlData.value = ''
                isTableForm.value = false

            if (dataId.value) {
               

                getDetailData()
                 getAddLogBusinessData()
            }

    }
})
//监听
watch(() => [
    props.type,
    props.dataId,
], ([val, id]) => {
    type.value = val
    dataId.value = id

    if (val === 1) {
        excelIdVal.value = '1937773223861026820'
    } else {
        excelIdVal.value = '1937773223861026822'
    }
    
   
    
}, { immediate: true })

//获取模板标签数据

const getExcelHtml = async () => {
   loading.value = true
        //获取数据
        const { error, code, data } = await dataApi.getServiceHtml({
            contractId: contractId.value || '',
             pkeyId:  excelIdVal.value,
            projectId: projectId.value || '',
        }, false)
         loading.value = false
        //处理数据
        const resData = isString(data) ? data || '' : ''
        
        if (!error && code === 200 && resData) {
          
            excelHtmlData.value = resData
        } else {
            excelHtmlData.value = ''
            isTableForm.value = false
           
        }
   
}
//获取填写数据
const getAddLogBusinessData = async () => {

    const { data } = await dataApi.getServiceBussData({
        id: dataId.value,
       pkeyId: excelIdVal.value,
    
    }, false)
    //设置默认数据
    let formArrData = getObjVal(data)
    const defaultData = setFormDefaultData(formArrData)
    //   tableFormData.value = defaultData
          if (getObjVal(defaultData)) {
            tableFormData.value = defaultData
        } else {
            tableFormData.value = {}
        }
       tableFormRef.value?.setExcelHtml()
}
//设置表单默认数据
const setFormDefaultData = (formInfo = {}) => {
    return {
      
        ...formInfo,
        projectId: projectId.value,
        contractId: contractId.value,
        pkeyId: excelIdVal.value,
      
    }
}
//渲染表单完成
const tableFormRender = (form) => {
    isTableForm.value = form.isRenderForm
}
const goBack = () => {
    isShow.value = false
     emit('close')
}
const sendPlan = ()=>{
    userData.value = []

    isUserModalShow.value = true

}
// 计算属性：判断 writeUser 是否包含 user_id
const isWriteUserAuthorized = computed(() => {
 
    const writeUserStr = writeUser.value
    const writeUserArray = writeUserStr.split(',')
    const cleanedArray = writeUserArray.filter(item => item.trim() !== '')
   
    console.log(cleanedArray, 'cleanedArray')
    console.log(user_id.value, 'user_id.value')
    
    
    return cleanedArray.includes(user_id.value)

})
// 计算属性：判断 sendUser 是否包含 user_id
const isSendUserAuthorized = computed(() => {
    const writeUserStr = sendUser.value
    const writeUserArray = writeUserStr.split(',')
    const cleanedArray = writeUserArray.filter(item => item.trim() !== '')
    return cleanedArray.includes(user_id.value)
})
const isUserModalShow = ref(false)
const userData = ref([])
const dataInfo = ref({
    projectId:projectId.value,
    contractId:contractId.value,
})
const userIds = ref('')
const fixedUserFinish = async (data) => {
    const res = deepClone(data)
    userData.value = res
     userIds.value = arrToKey(res, 'userId', ',')

    console.log(userIds, 'userIds')
    sendPlanClick(2)

    
}
const sendPlanLoad = ref(false)
const sendPlanClick = async (type)=>{
     sendPlanLoad.value = true
      const { error, code, msg, data } = await dataApi.sendServicePlan(
            {
                id: dataId.value,
                sendUser: userIds.value,

               
            }
         
        , false)
      sendPlanLoad.value = false
        if (!error && code === 200) {
        
            window?.$message?.success(msg)
            getDetailData()
           
        } else {
            sendPlanLoad.value = false
          
          
        }
}
//回退计划
const backPlanLoad = ref(false)
const backPlan = async ()=>{
    backPlanLoad.value = true
    const { error, code, msg, data } = await dataApi.cancelServicePlan(
            {
                id: dataId.value,
              
            }
         
        , false)
        backPlanLoad.value = false
      if (!error && code === 200) {
        
            window?.$message?.success(msg)
            getDetailData()
           
        } 
}
//确认计划
const confirmPlanLoad = ref(false)
const confirmPlan = async ()=>{
    confirmPlanLoad.value = true
      const { error, code, msg, data } = await dataApi.confirmServicePlan(
            {
                id: dataId.value,
              
            }
         
        , false)
      confirmPlanLoad.value = false
        if (!error && code === 200) {
        
            window?.$message?.success(msg)
            getDetailData()
           
        } 
          
}
//保存数据
const saveLoading = ref(false)
const savePlan = async ()=>{
    console.log( tableFormData.value, 'tableFormData.value')
    
    let objres = {
        ...tableFormData.value,
        projectId: projectId.value,
        contractId: contractId.value,
        pkeyId: excelIdVal.value,
        group_id: dataId.value,
       
       
    }
    saveLoading.value = true
      const { error, code, msg, data } = await dataApi.saveServiceData(
            objres
         
        , false)
      saveLoading.value = false
        if (!error && code === 200) {
         dataId.value = data

            window?.$message?.success(msg)
            getDetailData()
           
        } else {
            saveLoading.value = false
          
          
        }
}
//预览
const preViewLoad = ref(false)
const previewPlan = async ()=>{
    preViewLoad.value = true
    const { error, code, data } = await dataApi.getDetail({
        id: dataId.value,

    }, false)
    preViewLoad.value = false
    if (!error && code === 200) {
       const res = getObjVal(data)
       const { pdfUrl } = res
       if (pdfUrl) {
        toPdfPage(pdfUrl)

       } else {
        window?.$message?.error('暂无预览文件')
       
       }

    } else {
        window?.$message?.error('暂无预览文件')
    }
}
const sendUser = ref('')
const writeUser = ref('')
const getDetailData = async ()=>{
    const { error, code, data } = await dataApi.getDetail({
        id: dataId.value,

    }, false)
    if (!error && code === 200) {
       const res = getObjVal(data)
       
        status.value = res.status
        console.log( status.value, ' status.value')
        console.log(user_id, ' user_id.value')
        
        
       sendUser.value = res.sendUser
       writeUser.value = res.writeUser

        
    } else {
     
        status.value = ''
        sendUser.value = ''
        writeUser.value = ''
    }
}
</script>

<style scoped lang="scss">
.node-card-plan-btn{
    color:white;
}
.hc-table-form-box{

    height: 100%;
    overflow-y: auto;
    overflow-x: auto;
 
}
</style>