<template>
    <hc-drawer v-model="isShow" to-id="node-card-target" is-close>
        <div class="relative bg-white" style="height: 100%">
            <hc-card v-loading="infoLoad" title="基础信息" scrollbar>
                <template #header>
                    <div class="text-bold">基础信息</div>
                </template>
                <template #extra>
                    <el-button hc-btn type="success" :loading="handleSaveLoad" @click="handleSave">保存</el-button>
                    <el-button hc-btn type="warning" @click="handleRefresh">重新获取数据</el-button>
                </template>

                <div class="header_title">
                    <div class="text-bold">项目信息</div>
                    <el-link type="primary" @click="linkCommission">关联委托单</el-link>
                </div>
                <div class="form-box">
                    <el-form :model="basicInfoData" label-width="auto">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="项目名称">
                                    <el-input v-model="basicInfoData.projectName" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="工程名称">
                                    <el-input v-model="basicInfoData.projectName" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="施工单位">
                                    <el-input v-model="basicInfoData.constructionUnit" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="监理单位">
                                    <el-input v-model="basicInfoData.supervisionUnit" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="实验室名称">
                                    <el-input v-model="basicInfoData.labName" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="合同段/工区">
                                    <el-input v-model="basicInfoData.contractName" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="工程部位/用途">
                                    <el-input v-model="basicInfoData.projectPosition" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="委托单编号">
                                    <el-input v-model="basicInfoData.entrustNo" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="记录编号">
                                    <el-input v-model="basicInfoData.recordNo" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="报告编号">
                                    <el-input v-model="basicInfoData.reportNo" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="判断依据">
                                    <el-select
                                        v-model="standardId"
                                        placeholder="请选择"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in basicInfoData.standardVos"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                
                <div class="header_title">
                    <div class="text-bold">样品信息</div>
                    <el-link type="primary" @click="linkSample">关联样品</el-link>
                </div>

                <div class="form-box">
                    <el-form :model="basicInfoData.trialSampleInfoList" label-width="auto">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="样品名称">
                                    <el-input v-model="basicInfoData.trialSampleInfoList.materialName" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="样品编号">
                                    <el-input v-model="basicInfoData.trialSampleInfoList.specificationNumber" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="样品描述">
                                    <el-input v-model="basicInfoData.trialSampleInfoList.sampleDescription" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="来样/取样时间">
                                    <el-input v-model="basicInfoData.trialSampleInfoList.samplingDate" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="样品数量">
                                    <el-input v-model="basicInfoData.trialSampleInfoList.materialCount" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col v-for="(item, index) in ypList" :key="item.id" :span="8">
                                <el-form-item :label="item.name">
                                    <el-select
                                        v-model="ypList[index].value"
                                        placeholder="请选择"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item1 in item.info"
                                            :key="item1.id"
                                            :label="item1.name"
                                            :value="item1.id"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="header_title">
                    <div class="text-bold">设备信息</div>
                    <div>
                        <el-link type="primary" @click.stop="linkAcquisitionClick(item, index)">关联设备</el-link>
                        <el-link v-loading="linkLastLoad" type="primary" class="ml-2" @click="linkLast">关联上次设备</el-link>
                    </div>
                </div>
                <div>
                    <hc-table :column="tableColumn" :datas="basicInfoData.trailDeviceUseInfoDTOS">
                        <template #action="{ row, index }">
                            <el-link size="small" type="warning">删除</el-link>
                        </template>
                    </hc-table>
                </div>
            </hc-card>
        </div>
        
        <!-- 关联取样 -->
        <hc-new-dialog
            v-model="linksSampleModal" is-table save-text="确认" title="关联取样信息" widths="75rem"
            @close="linksSampleModalClose" @save="linksSampleModalSave"
        >
            <div class="hc-links-sample-modal-box">
                <div class="hc-links-sample-tree-box">
                    <el-scrollbar>
                        <TestTree
                            :project-id="projectId" :tenant-id="userInfo?.tenant_id"
                            :wbs-temp-id="projectInfo?.referenceWbsTemplateIdTrial" :wbs-type="2"
                            :entrust="1" @node-tap="linksSampleTreeClick"
                        />
                    </el-scrollbar>
                </div>
                <div class="hc-links-sample-table-box">
                    <HcTable
                        ref="tableSampleRef" :column="linksSampleTableColumn" :datas="linksSampleTableData"
                        :is-index="false" :loading="linksSampleTableLoading" is-new is-check
                        :check-style="{ width: 29 }"
                        @selection-change="linksSampleTableSelection"
                    />
                </div>
            </div>
        </hc-new-dialog>
        <!-- 关联委托单 -->
        <LinkAssociation v-model="isLinksAssociation" :cid="contractId" :ids="ids" @change="commissionChange" @close="isLinksAssociation = false" />

        <!-- 关联设备数据 -->
        <hc-new-dialog v-model="isLinkAcquisition" is-table is-footer-center title="关联设备数据" widths="80%" @close="linksAcquisitionClose">
            <LinkAcquisition v-if="isLinkAcquisition" v-model="linkAcquisitionLoadDataId" @change="linkAcquisitionChange" />
            <template #footer>
                <el-button @click="linksAcquisitionClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="linksAcquisitionLoading" @click="linksAcquisitionClick">确定</el-button>
            </template>
        </hc-new-dialog>
    </hc-drawer>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import TestTree from '../../material/components/TestTree.vue'
import { useAppStore } from '~src/store'

import dataApi from '~api/tentative/detect/test'
import LinkAssociation from '../../detect/components/linkAssociation.vue'
import LinkAcquisition from '../../detect/components/linkAcquisition.vue'
import codeApi from '~api/basic/code'
import { arrToId, arrToKey, formValidate, getArrValue, getObjVal, getObjValue, isNullES, isString } from 'js-fast-way'
const props = defineProps({
     nodeId:{
        type: [String, Number],
        default: '',
    },
    dataId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    projectId: {
        type: [String, Number],
        default: '',
    },
    ids:{
        type: [String, Number],
        default: '', //委托单id

    },
})
const emit = defineEmits(['change'])

const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo)

const projectInfo = ref(useAppState.getProjectInfo)

const nodeId = ref(props.nodeId)
const dataId = ref(props.dataId)
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const ids = ref(props.ids)

const handleRefresh = () => {
     getInfoData()
}
const isShow = defineModel('modelValue', {
    default: false,
})
const standardId = ref('')
const ypList = ref([]) // 确保 ypList 已定义
const ypLoad = ref(false)
const getYpList = async (id)=>{
        ypLoad.value = true
    const { error, code, data } = await codeApi.getStandardInfoByStandardId({
        standardId: id,
    })
    //处理数据
    ypLoad.value = false
    if (!error && code === 200) {
        ypList.value = getArrValue(data)
        console.log(ypList.value, 'ypList')
        
       
    } else {
        ypList.value = []
    }
}
// 监听 standardId 的变化
watch(standardId, async (newVal, oldVal) => {
    if (newVal !== oldVal) {
        getYpList(newVal)

    }
})

//监听
watch(() => [
 
    props.dataId,
    props.nodeId,
    props.projectId,
    props.contractId,
    props.ids,
    
   
], ([did, nid, pid, cid, id]) => {
    dataId.value = did
    nodeId.value = nid
    projectId.value = pid
    contractId.value = cid
    ids.value = id



})
//获取基础信息数据
watch(isShow, (newVal) => {
    if (newVal) {
        getInfoData()
    }
})
const basicInfoData = ref({
    trialSampleInfoList:{
        materialName:'',
                specificationNumber:'',
                sampleDescription:'',
                samplingDate:'',
    },
})
const oldRecordNumber = ref('')//旧记录编号
const oldReportNumber = ref('')//旧报告编号
const recordAutoNumber = ref('')//r记录表自增流水号
const reportAutoNumber = ref('')//报告单自增流水号

const infoLoad = ref(false)
const getInfoData = async () => {
infoLoad.value = true

    const { error, code, data } = await codeApi.getBaseInfo({
        nodeId: nodeId.value,
        id: dataId.value,
        projectId: projectId.value,
        contractId: contractId.value,
        
    })
    //处理数据
infoLoad.value = false
    if (!error && code === 200) {
      console.log(data, '基础信息数据')
        basicInfoData.value = getObjValue(data)
        oldRecordNumber.value = data?.recordNo
        oldReportNumber.value = data?.reportNo
   


        const { trialSampleInfoList, trailDeviceUseInfoDTOS } = basicInfoData.value
        if (!trialSampleInfoList) {
            basicInfoData.value.trialSampleInfoList = {
                materialName:'',
                specificationNumber:'',
                sampleDescription:'',
                samplingDate:'',
            }
            
        }
        if (!trailDeviceUseInfoDTOS) {
            basicInfoData.value.trailDeviceUseInfoDTOS = []
           
        }
   

    } else {
         basicInfoData.value = {}
    }
}




const tableColumn = [
    { key: 'deviceName', name: '设备名称' },
    { key: 'deviceModel', name: '设备型号' },
    { key: 'deviceNumber', name: '设备编号' },
    { key: 'measuringRange', name: '测量范围' },
    { key: 'afterRunCheck', name: '精准度' },
    { key: 'useDate', name: '使用日期' },
    { key: 'startDate', name: '使用开始时间(h:min)' },
    { key: 'endDate', name: '使用结束时间(h:min)' },
    { key: 'useDuration', name: '使用时间(min)' },
    { key: 'beforeRunCheck', name: '运转前检查情况' },
    { key: 'afterRunCheck', name: '运转后检查情况' },
    { key: 'managerName', name: '操作人' },
    { key: 'remarks', name: '备注' },
    { key: 'action', name: '操作' },
]

//关联取样
const linksSampleModal = ref(false)

const linkSample = () => {
    linksSampleModal.value = true
    tableSampleCheckedKeys.value = []

}


const linksSampleTableColumn = [
     { key: 'materialName', name: '样品名称' },
    { key: 'samplingDate', name: '取样日期' },
    { key: 'specificationModel', name: '规格型号' },
    { key: 'proposedPosition', name: '拟用部位' },
    { key: 'userName', name: '取样人' },
]
const linksSampleTableData = ref([])
const linksSampleTableLoading = ref(false)
const tableSampleRef = ref()
//搜索表单
const linksSampleSearchForm = ref({
    nodeId: null, current: 1, size: 20, total: 0,
})
//关联取样树点击事件
const linksSampleTreeClick = ({ data }) => {
        linksSampleSearchForm.value.nodeId = data.primaryKeyId
    linksSampleSearchForm.value.current = 1
    getLinksSampleData()
}
//获取关联数据

const getLinksSampleData = async () => {
    linksSampleTableLoading.value = true
    const { error, code, data } = await dataApi.sampleListInfo({
        ...linksSampleSearchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
        id: '',
    })
    //处理数据
    linksSampleTableLoading.value = false
    if (!error && code === 200) {
        linksSampleTableData.value = getArrValue(data)
        linksSampleTableData.value.forEach((iten) => {
            if (iten.isRelation === 1) {
                nextTick(() => {
                    tableSampleRef.value?.toggleRowSelection(iten, true)
                })

            }
        })
        //searchForm.value.total = data.total || 0
    } else {
        linksSampleTableData.value = []
        //searchForm.value.total = 0
    }
}
//关闭关联取样
const linksSampleModalClose = () => {
    linksSampleModal.value = false
}
const linksSampleModalSave = () => {
    linksSampleModal.value = false
    console.log(tableSampleCheckedKeys.value, 'tableSampleCheckedKeys.value')
    if (tableSampleCheckedKeys.value.length > 0) {
      basicInfoData.value.trialSampleInfoList = tableSampleCheckedKeys.value[0]
        basicInfoData.value.sampleIds = tableSampleCheckedKeys.value[0].id


    }
    
}
//多选
const tableSampleCheckedKeys = ref([])
const linksSampleTableSelection = (rows) => {
   
    if (rows.length > 1) {
        window.$message.warning('只能选择一条数据')
        return
    }
     tableSampleCheckedKeys.value = rows


}
//关联委托单
const linkCommission = ()=>{
     isLinksAssociation.value = true
}


//关联委托单
const isLinksAssociation = ref(false)

//委托单确定选择
const commissionChange = (id, data) => {

    basicInfoData.value.entrustNo = data.specificationNumber
     basicInfoData.value.entrustId = id

   
}

//关联设备
//关联设备数据
const isLinkAcquisition = ref(false)
const linkAcquisitionLoadDataId = ref('')
const linkAcquisitionIndex = ref(-1)
const linkAcquisitionRow = ref({})
const linkAcquisitionClick = (item, index) => {
    isLinkAcquisition.value = true
}


//确定
const linksAcquisitionLoading = ref(false)
const linksAcquisitionClick = async () => {
    linksAcquisitionLoading.value = true

   

    linksAcquisitionClose()
}

//关闭关联
const linksAcquisitionClose = () => {
    isLinkAcquisition.value = false
    linkAcquisitionRow.value = {}
    linkAcquisitionLoadDataId.value = null
    linkAcquisitionIndex.value = -1
    linksAcquisitionLoading.value = false
}

const linkAcquisitionChange = (ids, rows) => {
    console.log(ids)
    console.log(rows, 'rows')
    // tableData.value.push
    if (rows.length > 0) {
      rows.forEach((item)=>{
        basicInfoData.value.trailDeviceUseInfoDTOS.push(item)
      })
    }
    linkAcquisitionLoadDataId.value = ids
        basicInfoData.value.deviceUseIds = ids
}

//保存
const handleSaveLoad = ref(false)
const handleSave = async () => {
  const standardInfoIds = ypList.value.length > 0

        ? ypList.value.filter(item => item.value != null && item.value !== '')
        .map(item => item.value)
        .join(',') : ''

    basicInfoData.value.standardInfoIds = standardInfoIds
    basicInfoData.value.oldRecordNumber = oldRecordNumber.value
    basicInfoData.value.oldReportNumber = oldReportNumber.value

    // emit('change', basicInfoData.value)
    handleSaveLoad.value = true
          const { error, code, data, msg } = await codeApi.saveBaseInfo({
                    ...basicInfoData.value,
                 
                })
            handleSaveLoad.value = false
            if (!error && code === 200) {
                window.$message.success(msg)
                isShow.value = false

              
            }
}
//关联上次设备
const linkLastLoad = ref(false)
const linkLast = async ()=>{
    linkLastLoad.value = true
    const { error, code, data } = await codeApi.lastTrailDeviceInfo({
         nodeId: nodeId.value,
        contractId: contractId.value,
    })
      linkLastLoad.value = false
    if (!error && code === 200) {
         console.log(data)
         let rows = getArrValue(data)
        if (rows.length > 0) {
           rows.forEach((item)=>{
                basicInfoData.value.trailDeviceUseInfoDTOS.push(item)
            })
        }
         
    
    }

}
</script>

<style scoped lang="scss">
 .text-bold{
        font-weight: bold;
    }
.header_title{
    display: flex;
    justify-content: space-between;
    background-color: rgb(240, 240, 240);
    padding: 10px;
     .el-link {
        text-decoration: underline;
    }
   
}
.form-box{
    margin-top: 10px;
    padding-left:30px ;
    padding-right:30px ;
}
.hc-links-sample-modal-box {
    position: relative;
    height: 100%;
    display: flex;
    .hc-links-sample-tree-box,
    .hc-links-sample-table-box {
        position: relative;
        width: 300px;
        height: 100%;
    }
    .hc-links-sample-tree-box {
        margin-right: 24px;
        border: 1px solid #EEEEEE;
    }
    .hc-links-sample-table-box {
        flex: 1;
    }
}
</style>