<template>
    <hc-body split :project-nmae="projectInfo?.projectName">
        <template #tree>
            <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"
            />
        </template>
        <hc-new-card w-to="1919">
            <template #headerToSearch>
                <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 w-250px">
                    <hc-date-picker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
                </div>
                <div class="ml-2 w-72">
                    <el-input v-model="searchForm.queryValue" clearable placeholder="请输入名称、规格、样品编号查询" @keyup="keyUpEvent" />
                </div>
                <div class="ml-2">
                    <el-button type="primary" @click="searchClick">
                        <hc-icon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extraToHeader>
                <hc-tooltip keys="tentative_material_sampling_add">
                    <el-button :disabled="!primaryKeyId" hc-btn type="primary" @click="addFormModalClick">
                        <hc-icon name="add-circle" />
                        <span>新增</span>
                    </el-button>
                </hc-tooltip>
                <hc-tooltip keys="tentative_material_sampling_edit">
                    <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn type="primary" color="#12C060" style="color: white;" @click="editFormModalClick">
                        <hc-icon name="edit" />
                        <span>编辑</span>
                    </el-button>
                </hc-tooltip>
                <hc-tooltip keys="tentative_material_sampling_copy">
                    <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn color="#A16222" @click="copyTableModalClick">
                        <hc-icon name="file-copy-2" />
                        <span>复制</span>
                    </el-button>
                </hc-tooltip>
                <hc-tooltip keys="tentative_material_sampling_del">
                    <el-button v-del-com:[delModalClick] :disabled="tableCheckedKeys.length <= 0" hc-btn color="#e03997">
                        <hc-icon name="delete-bin-2" />
                        <span>删除</span>
                    </el-button>
                </hc-tooltip>
                <hc-tooltip keys="tentative_material_sampling_printer">
                    <el-button :disabled="tableCheckedKeys.length <= 0" :loading="printerLoading" hc-btn color="#567722" @click="printerClick">
                        <hc-icon name="printer" />
                        <span>打印</span>
                    </el-button>
                </hc-tooltip>
                <hc-tooltip keys="tentative_material_sampling_import">
                    <el-button :disabled="!primaryKeyId" hc-btn color="#567722" @click="importModalClick">
                        <hc-icon name="folder-upload" />
                        <span>导入</span>
                    </el-button>
                </hc-tooltip>
                <hc-tooltip keys="tentative_material_sampling_delegation">
                    <el-button hc-btn color="#E75643" :disabled="!nodeErTreeId" @click="delegationClick">
                        <hc-icon name="slack" />
                        <span>委托</span>
                    </el-button>
                </hc-tooltip>
            </template>
            <hc-table
                ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check
                :index-style="{ width: 60 }" :check-style="{ width: 29 }" @selection-change="tableSelection"
            >
                <template #materialCount="{ row }">{{ row.materialCount === -1 ? "" : row.materialCount }}</template>
                <template #representativeCount="{ row }">
                    {{ row.representativeCount === -1 ? "" : row.representativeCount }}
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-new-card>

        <!-- 新增/编辑 -->
        <hc-new-dialog v-model="addEditFormModal" :title="`${addEditFormModel.id ? '编辑' : '新增'}样品信息`" is-row-footer widths="50rem" @close="addEditFormModalClose">
            <el-form ref="addEditFormRef" :model="addEditFormModel" :rules="addEditFormRules" label-width="auto" size="large">
                <div class="hc-form-item">
                    <el-form-item label="样品名称" prop="materialName">
                        <el-input v-model="addEditFormModel.materialName" />
                    </el-form-item>
                    <el-form-item label="进场日期">
                        <el-date-picker v-model="addEditFormModel.mobilizationDate" :clearable="false" class="block" type="date" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="样品编号" prop="specificationNumber">
                        <el-input v-model="addEditFormModel.specificationNumber" />
                    </el-form-item>
                    <el-form-item label="取样日期">
                        <el-date-picker v-model="addEditFormModel.samplingDate" :clearable="false" class="block" type="date" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="规格型号">
                        <el-input v-model="addEditFormModel.specificationModel" />
                    </el-form-item>
                    <el-form-item label="取样地点">
                        <el-input v-model="addEditFormModel.samplingLocation" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="试样数量">
                        <el-input v-model="addEditFormModel.materialCount" type="number" />
                    </el-form-item>
                    <el-form-item label="试样单位">
                        <el-input v-model="addEditFormModel.calculationUnit" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="代表数量">
                        <el-input v-model="addEditFormModel.representativeCount" type="number" />
                    </el-form-item>
                    <el-form-item label="代表单位">
                        <el-input v-model="addEditFormModel.representativeUnit" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="是否外委">
                        <el-radio-group v-model="addEditFormModel.isOutsourcing" size="large">
                            <el-radio :value="1">是</el-radio>
                            <el-radio :value="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="供应商">
                        <el-input v-model="addEditFormModel.supplierUnit" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="生产批号">
                        <el-input v-model="addEditFormModel.batchNumber" />
                    </el-form-item>
                    <el-form-item label="取样人">
                        <el-select v-model="addEditFormModel.userId" block @change="changeusername">
                            <el-option v-for="item in userListData" :key="item.userId" :label="item.userName" :value="item.userId" />
                        </el-select>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="拟用部位">
                        <el-input v-model="addEditFormModel.proposedPosition" />
                    </el-form-item>
                    <el-form-item label="是否使用RFID">
                        <el-radio-group v-model="addEditFormModel.isRfid" size="large">
                            <el-radio :value="1">是</el-radio>
                            <el-radio :value="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
                <el-form-item v-if="addEditFormModel.isRfid === 1" label="RFID编号">
                    <el-select v-model="addEditFormModel.rfid" clearable block>
                        <el-option v-for="item in deviceTable" :key="item.epc" :label="item.epc" :value="item.epc" />
                    </el-select>
                </el-form-item>
                <el-form-item label="样品描述">
                    <el-input v-model="addEditFormModel.sampleDescription" />
                </el-form-item>
            </el-form>
            <template #leftRowFooter>
                <hc-tooltip keys="tentative_material_sampling_links">
                    <el-button hc-btn type="primary" @click="linksApproachModalClick(addEditFormModel.mobilizationId)">
                        <hc-icon name="links" />
                        <span>关联进场材料</span>
                    </el-button>
                </hc-tooltip>
            </template>
            <template #rightRowFooter>
                <el-button size="large" @click="addEditFormModalClose">
                    <hc-icon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button :loading="addEditFormLoading" hc-btn type="primary" @click="addEditFormClick">
                    <hc-icon name="check" />
                    <span>确认</span>
                </el-button>
            </template>
        </hc-new-dialog>

        <!-- 关联进场材料 -->
        <hc-new-dialog v-model="linksApproachModal" is-row-footer is-table title="关联进场材料信息" widths="60%" @close="linksApproachModalClose">
            <hc-table :column="linksApproachTableColumn" :datas="linksApproachTableData" :is-index="false" :loading="linksApproachTableLoading">
                <template #materialType="{ row }">{{ getRowTableMaterialType(row.materialType) }}</template>
                <template #action="{ row }">
                    <hc-tooltip keys="tentative_material_approach_annex">
                        <el-button v-if="mobilizationId === row.id" plain size="small" type="primary" @click="cancelApproachRow(row)">取消关联</el-button>
                        <el-button v-else plain size="small" type="primary" @click="linksApproachRow(row)">关联</el-button>
                    </hc-tooltip>
                </template>
            </hc-table>
            <template #leftRowFooter>
                <hc-pages :pages="ApproachSearchForm" @change="linksApproachPageChange" />
            </template>
            <template #rightRowFooter>
                <el-button size="large" @click="linksApproachModalClose">
                    <hc-icon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button hc-btn type="primary" @click="linksApproachModalSave">
                    <hc-icon name="check" />
                    <span>确定</span>
                </el-button>
            </template>
        </hc-new-dialog>

        <!-- 复制样品登记信息 -->
        <hc-new-dialog v-model="copyTableModal" :loading="copyTableLoading" is-table title="复制样品登记信息" widths="60rem" @close="copyTableModalClose" @save="copyTableClick">
            <hc-table :column="copyTableColumn" :datas="copyTableData" is-new :index-style="{ width: 60 }">
                <template #specificationNumber="{ row }">
                    <el-input v-model="row.specificationNumber" placeholder="请输入样品编号" />
                </template>
                <template #action="{ index }">
                    <el-button plain size="small" type="danger" @click="specificationNumberDel(index)">删除</el-button>
                </template>
            </hc-table>
        </hc-new-dialog>

        <!-- 导入 -->
        <hc-new-dialog v-model="importModal" is-row-footer title="导入" widths="38rem" @close="importModalClose">
            <HcDragUpload ref="uploadRef" api="/api/blade-business/material/" :datas="uploadData" action="sample/import" @finished="uploadFinished" @progress="uploadprogress" />
            <template #leftRowFooter>
                <el-button size="large" @click="downloadImportClick">
                    <hc-icon name="download-2" />
                    <span>下载模板</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <el-button size="large" @click="importModalClose">
                    <hc-icon name="close" />
                    <span>取消导入</span>
                </el-button>
                <el-button :loading="importModalLoading" hc-btn type="primary" @click="importModalYesClick">
                    <hc-icon name="folder-upload" />
                    <span>确认导入</span>
                </el-button>
            </template>
        </hc-new-dialog>

        <!-- 创建委托 -->
        <hc-new-dialog v-model="delegateModal" ui="hc-delegate-html-modal" is-table is-footer-center title="创建委托" widths="60rem" @close="delegateModalClose">
            <div class="hc-delegate-contract hc-flex h-40px">
                <el-select v-model="delegateContractId" placeholder="请先选择合同段" filterable class="w-400px" @change="delegateContractChange">
                    <el-option v-for="item in contractData" :key="item.id" :label="item.contractName" :value="item.id" />
                </el-select>
            </div>
            <div class="hc-delegate-html" :class="delegateContractId ? 'is-show' : ''">
                <hc-table-form ref="htmlRef" :pkey="nodeErTreeId" :form="delegateHtmlForm" :html="delegateHtml" :loading="delegateHtmlLoading" @render="delegateHtmlRender" />
            </div>
            <template #footer>
                <el-button @click="delegateModalClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="creatingDelegateLoading" @click="creatingDelegate">创建</el-button>
            </template>
        </hc-new-dialog>
    </hc-body>
</template>

<script setup>
import { onActivated, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import TestTree from './components/TestTree.vue'
import HcDragUpload from './components/HcDragUpload.vue'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import commissionApi from '~api/tentative/detect/commission'
import samplingApi from '~api/tentative/material/sampling'
import approachApi from '~api/tentative/material/approach'
import { getContractUserList, getDictionary } from '~api/other'
import { arrIndex, arrToId, deepClone, formValidate, getArrValue, getObjValue, isNullES, isString } from 'js-fast-way'
import { toPdfPage } from '~uti/btn-auth'
import Dayjs from 'dayjs'

//变量
const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo)
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const isCollapse = ref(useAppState.getCollapse)

//监听
watch(() => useAppState.getCollapse, (collapse) => {
    isCollapse.value = collapse
})

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

//渲染完成
onActivated(() => {
    getContractData()
    getUserListData()
    getMaterialType()
})

//获取材料类型
const typeData = ref([])
const getMaterialType = async () => {
    const { data } = await getDictionary({
        code: 'material_type',
    })
    typeData.value = getArrValue(data)
}

//获取材料类型
const getRowTableMaterialType = (type) => {
    if (type > 0) {
        const nodeData = typeData.value
        const index = arrIndex(nodeData, 'dictKey', type)
        return nodeData[index]?.dictValue ?? type
    } else {
        return ''
    }
}

//获取合同段信息
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 (res.length <= 0) return
    let cid
    for (let i = 0; i < res.length; i++) {
        if (contractId.value == res[i].id) {
            cid = res[i].id
        }
    }
    searchForm.value.contractId = isNullES(cid) ? res[0].id : cid
    searchClick()
}

//获取用户列表
const userListData = ref([])
const getUserListData = async () => {
    const { data } = await getContractUserList({
        contractId: contractId.value,
    })
    userListData.value = getArrValue(data)
}

//搜索表单
const searchForm = ref({
    startTime: null, endTime: null, queryValue: null, nodeId: '',
    current: 1, size: 20, total: 0,
})

//树相关的变量
const primaryKeyId = ref('')
const nodeErTreeId = ref('')
const nodeItemInfo = ref({})
const nodeDataInfo = ref({})

//树被点击
const wbsElTreeClick = ({ node, data, keys }) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    primaryKeyId.value = data['primaryKeyId'] || ''
    nodeErTreeId.value = data['erTreeId'] || ''
    //缓存自动展开
    treeAutoExpandKeys.value = keys
    setStoreValue('testTreeExpandKeys', keys)
    //改变搜索表单数据
    searchForm.value.nodeId = data['primaryKeyId'] || ''
    searchForm.value.current = 1
    getTableData()
}

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ arr }) => {
    betweenTime.value = arr
    if (arr.length > 0) {
        searchForm.value.startTime = arr[0]
        searchForm.value.endTime = arr[1]
    } else {
        searchForm.value.startTime = ''
        searchForm.value.endTime = ''
    }
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === 'Enter') {
        searchForm.value.current = 1
        getTableData()
    }
}

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

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

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'materialName', name: '取样名称', width: 160, align: 'center' },
    { key: 'samplingDate', name: '取样日期', width: 120, align: 'center' },
    { key: 'specificationNumber', name: '样品编号', width: 470, align: 'center' },
    { key: 'specificationModel', name: '规格型号', width: 180, align: 'center' },
    { key: 'materialCount', name: '试样数量', width: 70, align: 'center' },
    { key: 'calculationUnit', name: '试样单位', width: 70, align: 'center' },
    { key: 'proposedPosition', name: '拟用部位', width: 470, align: 'center' },
    { key: 'representativeCount', name: '代表数量', width: 70, align: 'center' },
    { key: 'representativeUnit', name: '代表单位', width: 70, align: 'center' },
    { key: 'userName', name: '取样人', width: 70, align: 'center' },
])

//获取数据
const tableLoading = ref(false)
const tableData = ref([])
const getTableData = async () => {
    const nodeId = primaryKeyId.value
    if (isNullES(nodeId)) return
    tableLoading.value = true
    const { error, code, data } = await samplingApi.queryPage({
        projectId: projectId.value,
        nodeId,
        ...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 tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//新增
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    const toDayDate = new Dayjs().format('YYYY-MM-DD')
    addEditFormModel.value = {
        isRfid: 0,
        isOutsourcing: 0,
        mobilizationId: '',
        mobilizationDate: toDayDate,
        samplingDate: toDayDate,
        nodeId: primaryKeyId.value,
        userId: userInfo.value.user_id,
    }
    addEditFormModal.value = true
    requestDevice()
}

//编辑
const editFormModalClick = () => {
    const keys = tableCheckedKeys.value
    if (keys.length === 1) {
        const obj = deepClone(keys[0])
        addEditFormModel.value = {
            ...obj,
            representativeCount: obj.representativeCount === -1 ? '' : obj.representativeCount,
            materialCount: obj.materialCount === -1 ? '' : obj.materialCount,
            isRfid: isNullES(obj.isRfid) ? 0 : obj.isRfid,
        }
        addEditFormModal.value = true
        requestDevice()
    } else if (keys.length > 1) {
        window?.$message?.warning('只能选择一条数据编辑')
    }
}

//获取读卡器设备
let device
const deviceTable = ref([])
const requestDevice = async () => {
    if (isNullES(device)) {
        const devices = await navigator.hid.requestDevice({
            filters: [{ vendorId: 1240, productId: 831 }],
        })
        if (devices.length <= 0) return
        device = devices[0]
    }
    // 检查设备是否打开
    if (!device.opened) {
        await device.open() // 打开设备
    }
    // 电脑接收到来自设备的消息回调
    device.oninputreport = (event) => {
        const { isRfid, rfid } = addEditFormModel.value
        if (isRfid !== 1 ) return
        const array = new Uint8Array(event.data.buffer)
        const data = array.slice(10, array[0] - 1)
        let epc = ''
        const res = new Uint8Array(data)
        for (const data of res) {
            // 将字节数据转换成（XX ）形式字符串
            epc += (Array(2).join(0) + data.toString(16).toUpperCase()).slice(-2) + ''
        }
        const index = arrIndex(deviceTable.value, 'epc', epc)
        if (index === -1) {
            deviceTable.value.push({ epc: epc })
        }
        if (isNullES(rfid)) {
            addEditFormModel.value.rfid = epc
        }
    }
}

//弹窗关闭
const addEditFormModalClose = async () => {
    addEditFormModal.value = false
    addEditFormModel.value = {}
    if (!isNullES(device)) {
        await device.close() // 关闭设备
        await device.forget() // 遗忘设备
        device = null
    }
}

//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = {
    materialName: {
        required: true,
        trigger: 'blur',
        message: '请输入样品名称',
    },
    specificationNumber: {
        required: false,
        validator: async (rule, value, callback) => {
            if (!value) {
                // callback(new Error('请输入样品编号'))
            } else {
                const ver = await verification(value)
                if (!ver) {
                    callback(new Error('样品编号必须是惟一的'))
                } else {
                    callback()
                }
            }
        },
        trigger: 'blur',
    },
}

//校验材料编号是否唯一
const verification = async (val) => {
    const { error, code, data } = await samplingApi.verification({
        projectId: projectId.value,
        contractId: searchForm.value.contractId,
        specificationNumber: val,
        id: addEditFormModel.value.id ?? '',
        nodeId: primaryKeyId.value,
    })
    if (!error && code === 200) {
        return !data
    } else {
        return false
    }
}

//新增/编辑 保存
const addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    const validate = await formValidate(addEditFormRef.value)
    if (validate) {
        addEditFormLoading.value = true
        const { error, code, msg } = await samplingApi.submitForm({
            ...addEditFormModel.value,
            projectId: projectId.value,
            contractId: searchForm.value.contractId,
        })
        //处理数据
        addEditFormLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            await getTableData()
        } else {
            window?.$message?.error(msg || '操作失败')
        }
    }
}


//复制表格
const copyTableColumn = ref([
    { key: 'materialName', name: '样品名称' },
    { key: 'specificationNumber', name: '样品编号' },
    { key: 'action', name: '操作', width: 100 },
])
const copyTableData = ref([])

//复制
const copyTableModal = ref(false)
const copyTableModalClick = () => {
    copyTableModal.value = true
    copyTableData.value = deepClone(tableCheckedKeys.value)
}

//删除
const specificationNumberDel = (index) => {
    copyTableData.value.splice(index, 1)
    const rows = copyTableData.value
    if (rows.length <= 0) {
        copyTableModal.value = false
    }
}

const copyTableModalClose = () => {
    copyTableModal.value = false
}

//复制 保存
const copyTableLoading = ref(false)
const copyTableClick = () => {
    copyTableModal.value = false
    const rows = copyTableData.value
    if (rows.length > 0) {
        for (let i = 0; i < rows.length; i++) {
            rows[i].dataNumber = i
        }
        tableCopyData(rows)
    } else {
        window.$message?.warning('请先在列表勾选要复制的数据')
        copyTableModal.value = false
    }
}

//复制数据请求
const tableCopyData = async (rows) => {
    copyTableLoading.value = true
    const { error, code, msg } = await samplingApi.copyData(rows)
    //处理数据
    copyTableLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        copyTableModal.value = false
        await getTableData()
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

//删除
const delModalClick = async (_, resolve) => {
    await tableRemoveData()
    resolve()
}

//批量删除
const tableRemoveData = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        const ids = arrToId(rows)
        //删除请求
        const { error, code, msg } = await samplingApi.removeData({
            projectId: projectId.value,
            contractId: searchForm.value.contractId,
            ids: ids,
        })
        //处理数据
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            searchClick()
        } else {
            window?.$message?.error(msg || '操作失败')
        }
    }
}

//打印
const printerLoading = ref(false)
const printerClick = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        printerLoading.value = true
        const ids = arrToId(rows)
        //删除请求
        const { error, code, data } = await samplingApi.exportPdf({
            projectId: projectId.value,
            contractId: searchForm.value.contractId,
            ids: ids,
        })
        //处理数据
        printerLoading.value = false
        if (!error && code === 200) {
            toPdfPage(data)
            //window.open(data, '_blank')
        }
    }
}

//导入
const uploadRef = ref(null)
const uploadData = ref({})

//导入
const importModal = ref(false)
const importModalClick = () => {
    importModal.value = true
    uploadData.value = {
        contractId: searchForm.value.contractId,
        nodeId: primaryKeyId.value,
        isCovered: 1,
    }
}

//上传进度
const uploadprogress = (res) => {
    importModalLoading.value = res
}

//确认导入
const importModalLoading = ref(false)
const importModalYesClick = () => {
    uploadRef.value?.submit()
}

//上传完成
const uploadFinished = () => {
    importModal.value = false
    getTableData()
}

//关闭导入
const importModalClose = () => {
    importModal.value = false
}
//更改取样人名称changeusername
const changeusername = (item) => {
    userListData.value.forEach((ele) => {
        if (item == ele.userId) {
            addEditFormModel.value.userName = ele.userName
        }
    })
}
//关联进场材料
const linksApproachModal = ref(false)
const ApproachSearchForm = ref({
    current: 1, size: 20, total: 0,
})
const mobilizationId = ref('')
const linksApproachModalClick = (mId) => {
    mobilizationId.value = mId ?? ''
    ApproachSearchForm.value.current = 1
    linksApproachModal.value = true
    getApproachTableData()
}

//分页被点击
const linksApproachPageChange = ({ current, size }) => {
    ApproachSearchForm.value.current = current
    ApproachSearchForm.value.size = size
    getApproachTableData()
}

//关联进场材料数据
const linksApproachTableColumn = ref([
    { key: 'materialNumber', name: '材料编号' },
    { key: 'mobilizationDate', name: '进场日期' },
    { key: 'materialName', name: '材料名称' },
    { key: 'materialType', name: '材料类型' },
    { key: 'specificationModel', name: '规格型号' },
    { key: 'supplierUnit', name: '供应商单位' },
    { key: 'proposedPosition', name: '拟用部位' },
    { key: 'userName', name: '记录人' },
    { key: 'action', name: '操作', width: 100, fixed: 'right', align: 'center' },
])
const linksApproachTableData = ref([])

//获取进场材料数据
const linksApproachTableLoading = ref(false)
const getApproachTableData = async () => {
    linksApproachTableLoading.value = true
    const { error, code, data } = await approachApi.queryPage({
        projectId: projectId.value,
        contractId: searchForm.value.contractId,
        ...ApproachSearchForm.value,
    })
    //处理数据
    linksApproachTableLoading.value = false
    if (!error && code === 200) {
        linksApproachTableData.value = getArrValue(data['records'])
        ApproachSearchForm.value.total = data.total || 0
    } else {
        linksApproachTableData.value = []
        ApproachSearchForm.value.total = 0
    }
}

//关联
const linksApproachRow = (row) => {
    const toDayDate = new Dayjs().format('YYYY-MM-DD')
    const form = addEditFormModel.value
    form.materialName = row.materialName ?? '' //样品名称
    form.mobilizationDate = row.mobilizationDate ?? toDayDate //进场日期
    form.specificationNumber = row.materialNumber ?? '' //样品编号
    form.specificationModel = row.specificationModel ?? '' //规格型号
    form.supplierUnit = row.supplierUnit ?? '' //供应商
    form.calculationUnit = row.calculationUnit ?? '' //计算单位
    form.batchNumber = row.batchNumber ?? '' //生产批号
    form.proposedPosition = row.proposedPosition ?? '' //拟用部位
    form.mobilizationId = row.id //关联ID
    //更新数据
    addEditFormModel.value = form
    mobilizationId.value = row.id //关联ID
}
//取消关联
const cancelApproachRow = (row) => {
    if (row.id === mobilizationId.value) {
        addEditFormModel.value.mobilizationId = ''
        mobilizationId.value = ''
    }
}

const linksApproachModalSave = () => {
    linksApproachModal.value = false
}

//关闭关联进场材料
const linksApproachModalClose = () => {
    linksApproachModal.value = false
}


//下载导入模板
const downloadImportClick = () => {
    window.open('https://blade-oss-chongqing.oss-cn-shenzhen.aliyuncs.com//upload/20221109/1f1cc15e4e4918d8c793fa6ec0a2ae2a.xlsx', '_blank')
}

//委托
const htmlRef = ref(null)
const delegateModal = ref(false)
const delegateHtml = ref('')
const delegateHtmlForm = ref({})
const delegateHtmlLoading = ref(false)
const delegateContractId = ref(null)
const delegationClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选一条需要委托的数据')
        return
    } else if (rows.length > 1) {
        window.$message.warning('只能选择其中一条数据进行委托')
        return
    }
    const data = rows[0]
    if (!isNullES(data.testId)) {
        window.$message.warning('已上报的数据不允许委托')
        return
    }
    editHtmlId.value = data.id
    entrustId.value = data.entrustId
    delegateContractId.value = searchForm.value.contractId
    if (!isNullES(contractId)) {
        delegateContractChange()
    }
}

//合同段被选择
const editHtmlId = ref('')
const entrustId = ref('')
const delegateContractChange = async () => {
    delegateHtmlLoading.value = true
    const res = await getCheckSample()
    if (!res) {
        delegateHtmlLoading.value = false
        return
    }
    delegateModal.value = true
    await getDelegateExcelHtml()
    await getDelegateDataInfo()
    delegateHtmlLoading.value = false
}

//校验是否关联
const getCheckSample = async () => {
    const { code, msg } = await samplingApi.getCheckSample({
        nodeId: primaryKeyId.value,
        sampleId: editHtmlId.value,
        contractId: delegateContractId.value,
    })
    //如果是200，说明没有关联，可以委托
    if (code === 200) {
        return true
    } else {
        window.$message.error(msg)
        return false
    }
}

//获取委托数据
const getDelegateDataInfo = async () => {
    const { error, code, msg, data } = await samplingApi.getBussDataInfoTrialEntrust({
        id: entrustId.value,
        sampleId: editHtmlId.value,
        pkeyId: nodeErTreeId.value,
        contractId: delegateContractId.value,
    })
    if (!error && code === 200) {
        delegateHtmlForm.value = getObjValue(data[0])
    } else {
        delegateHtmlForm.value = {}
        window.$message.error(msg || '获取委托信息失败')
    }
}

//获取委托html
const getDelegateExcelHtml = async () => {
    const { error, code, msg, data } = await samplingApi.getExcelHtml({
        nodeId: primaryKeyId.value,
        contractId: contractId.value,
    })
    if (!error && code === 200) {
        delegateHtml.value = isString(data) ? data : ''
        nodeErTreeId.value = msg
    } else {
        delegateHtml.value = ''
        nodeErTreeId.value = ''
        window.$message.error(msg || '获取委托信息失败')
    }
}

//渲染完成
const delegateHtmlRender = (form) => {
    delegateHtmlForm.value = form
}

//创建委托
const creatingDelegateLoading = ref(false)
const creatingDelegate = async () => {
    const rows = tableCheckedKeys.value
    if (isNullES(delegateHtml.value)) {
        window.$message.error('暂无委托单信息')
        return
    }
    const form = delegateHtmlForm.value
    if (isNullES(delegateContractId.value)) {
        window.$message.warning('请先选择合同段')
        return
    }
    creatingDelegateLoading.value = true
    form.contractId = delegateContractId.value
    form.nodeErTreeId = nodeErTreeId.value
    form.sampleId = editHtmlId.value
    form.nodeId = rows[0].nodeId
    const { error, code, msg } = await commissionApi.htmlSave(form)
    creatingDelegateLoading.value = false
    if (!error && code === 200) {
        window.$message.success('创建成功')
        delegateModalClose()
    } else {
        window.$message.error(msg || '创建失败')
    }
}

//关闭委托
const delegateModalClose = () => {
    delegateModal.value = false
    delegateHtml.value = ''
    delegateHtmlForm.value = {}
    delegateHtmlLoading.value = false
    creatingDelegateLoading.value = false
}
</script>

<style lang="scss" scoped>
@import "../../../styles/tentative/material/sampling.scss";
</style>

<style lang="scss">
.el-overlay-dialog .el-dialog.hc-new-dialog.hc-delegate-html-modal {
    .hc-new-dialog-body {
        padding: 0;
    }
    .hc-table-form-data-item {
        padding: 0;
        .el-scrollbar__bar.is-vertical {
            right: 0;
        }
    }
}
.hc-delegate-html-modal {
    .hc-delegate-html {
        position: relative;
        height: calc(100% - 40px);
        .hc-table-form-data-item {
            background-color: #efefef;
        }
        &::after {
            content: "";
            position: absolute;
            inset: 0;
            background: rgb(161 161 161 / 40%);
            z-index: 22;
        }
        &.is-show {
            &::after {
                display: none;
                z-index: -1;
            }
        }
    }
}
</style>
