<template>
    <hc-new-dialog v-model="isShow" is-footer-center is-table title="关联委托单" widths="80%" @close="linkSamplingClose">
        <hc-body split padding="10px">
            <template #left>
                <hc-new-card scrollbar>
                    <TestTree
                        :auto-expand-keys="treeAutoExpandKeys" :project-id="projectId" :tenant-id="userInfo?.tenant_id"
                        :wbs-temp-id="projectInfo?.referenceWbsTemplateIdTrial" :wbs-type="2" :entrust="1"
                        @node-tap="wbsElTreeClick"
                    />
                </hc-new-card>
            </template>
            <hc-new-card>
                <template #header>
                    <div class="w-50">
                        <el-select v-model="searchForm.contractId" placeholder="选择合同段" filterable block>
                            <el-option v-for="item in contractData" :key="item.id" :label="item.contractName" :value="item.id" />
                        </el-select>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <hc-icon name="search-2" />
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" :index-style="{ width: 60 }">
                    <template #status="{ row }">
                        <el-tag v-if="row.status === 1" type="info" effect="dark">未上报</el-tag>
                        <el-tag v-if="row.status === 2" type="warning" effect="dark">已上报-待审批</el-tag>
                        <el-tag v-if="row.status === 3" type="primary" effect="dark">待试验</el-tag>
                        <el-tag v-if="row.status === 4" type="success" effect="dark">委托完成</el-tag>
                    </template>
                    <template #action="{ row }">
                        <el-link v-if="row.id === curId && isSelected" type="success" @click="rowCancel(row)">取消选择</el-link>
                        <!-- el-link v-else type="primary" :disabled="row.status !== 4" @click="rowSelect(row)">选择</el-link -->
                        <el-link v-if="row.id !== curId || !isSelected" type="primary" :disabled="!row.testId" @click="rowSelect(row)">选择</el-link>
                    </template>
                </hc-table>
                <template #action>
                    <hc-pages :pages="searchForm" @change="pageChange" />
                </template>
            </hc-new-card>
        </hc-body>
        <template #footer>
            <el-button @click="linkSamplingClose">取消</el-button>
            <el-button hc-btn type="primary" @click="linkSamplingClick">确定</el-button>
        </template>
    </hc-new-dialog>

    <!-- 关联更换 -->
    <hc-new-dialog v-model="isCountShow" is-footer-center title="关联更换" widths="30rem" @close="linkCountClose">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
            <el-form-item label="试验数量：" prop="expCount">
                <el-input v-model="formModel.expCount" placeholder="试验数量" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="linkCountClose">取消</el-button>
            <el-button hc-btn type="primary" @click="linkCountClick">确定</el-button>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/tentative/detect/commission'
import samplingApi from '~api/tentative/material/sampling'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import TestTree from '~src/views/tentative/material/components/TestTree.vue'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
    cid: {
        type: [String, Number],
        default: '',
    },
})
const emit = defineEmits(['change', 'close'])
//变量
const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo)
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)

const isShow = defineModel('modelValue', {
    default: false,
})

//深度监听数据
const curId = ref(props.ids)
watch(() => props.ids, (id) => {
    curId.value = id
})

//监听
watch(() => isShow.value, (show) => {
    if (show) getContractData()
})

//搜索表单
const searchForm = ref({ current: 1, size: 20, total: 0 })

//获取合同段信息
const contractData = ref([])
const getContractData = async () => {
    const { data } = await samplingApi.getErtractInfo({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const res = getArrValue(data)
    contractData.value = res
    if (!isNullES(props.cid)) {
        searchForm.value.contractId = props.cid
    }
    if (isNullES(props.cid) && res.length > 0) {
        searchForm.value.contractId = res[0].id
    }
}

//自动展开缓存
const treeAutoExpandKeys = ref(getStoreValue('testTreeExpandKeys') || [])

//树被点击
const nodeDataInfo = ref({})
const nodeErTreeId = ref('')
const wbsElTreeClick = ({ data, keys }) => {
    nodeDataInfo.value = data
    searchForm.value.nodeId = data['primaryKeyId']
    nodeErTreeId.value = data['erTreeId'] || ''
    //缓存自动展开
    treeAutoExpandKeys.value = keys
    setStoreValue('testTreeExpandKeys', keys)
    //获取表格
    searchClick()
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页被点击
const pageChange = ({ current, size }) => {
  searchForm.value.current = current
  searchForm.value.size = size
  getTableData()
}

//表格数据
const tableData = ref([])
const tableColumn = ref([
    { key: 'entrustInfo', name: '委托单位' },
    { key: 'entrustNo', name: '委托单编号' },
    { key: 'entrustName', name: '委托单名称' },
    { key: 'status', name: '委托单状态', width: 120, align: 'center' },
    { key: 'action', name: '操作', width: 120, align: 'center', fixed: 'right' },
])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await mainApi.page(searchForm.value)
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//选择
const currentId = ref(null)
const entrustNoVal = ref('')
const rowSelect = async ({ id, entrustNo }) => {
    isCountShow.value = true
     formModel.value = {}
    currentId.value = id
    entrustNoVal.value = entrustNo

    const { data } = await mainApi.detail(id)
    formModel.value = getObjValue(data)
        isSelected.value = true // 设置选中状态
}

//取消选择
const rowCancel = () => {
    currentId.value = null
         entrustNoVal.value = ''
    formModel.value = {}
        isSelected.value = false // 清除选中状态
}
const isSelected = ref(false) // 新增状态变量
//确认关联取样材料
const linkSamplingClick = () => {
 
    
    emit('change', curId.value, formModel.value, entrustNoVal.value)
    linkSamplingClose()
}

//取消关联取样材料
const linkSamplingClose = () => {
    isShow.value = false
    formModel.value = {}
     entrustNoVal.value = ''

    emit('close')
}

//表单数据
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    expCount: {
        required: true,
        trigger: 'blur',
        message: '请填写试验数量',
    },
}

//确定
const isCountShow = ref(false)
const linkCountClick = async () => {
    const isForm = await formValidate(formRef.value)
    if (!isForm) return
    const { id, expCount } = formModel.value
    const { error, code, msg } = await mainApi.update({ id, expCount })
    if (!error && code === 200) {
        window.$message.success('选择成功')
        curId.value = currentId.value
        linkCountClose()
    } else {
        window.$message.error(msg || '选择失败')
    }
}

//取消
const linkCountClose = () => {
    isCountShow.value = false
    // formModel.value = {}
}
</script>
