<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" @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-40">
                    <el-select v-model="searchForm.status" placeholder="委托单状态" filterable clearable block>
                        <el-option v-for="item in entrustStatus" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <div class="ml-2 w-250px">
                    <hc-search-input v-model="searchForm.entrustName" @search="searchClick" />
                </div>
            </template>
            <template #extraToHeader>
                <el-button hc-btn type="primary" @click="addFormData">
                    <hc-icon name="add-circle" />
                    <span>新增</span>
                </el-button>
                <el-button v-del-com:[delModalClick] :disabled="tableCheckedKeys.length <= 0" hc-btn type="danger">
                    <hc-icon name="delete-bin-2" />
                    <span>删除</span>
                </el-button>
                <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn color="#567722" @click="batchPrinting">
                    <hc-icon name="printer" />
                    <span>批量打印</span>
                </el-button>
                <el-button :disabled="tableCheckedKeys.length <= 0" class="text-white" hc-btn color="#FF976A" @click="reportClick">
                    <HcIcon name="send-plane-2" />
                    <span>上报</span>
                </el-button>
                <el-button hc-btn color="#567722" @click="printerNull">
                    <hc-icon name="printer" />
                    <span>打印空表</span>
                </el-button>
            </template>
            <hc-table
                :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check
                :index-style="{ width: 60 }" :check-style="{ width: 29 }" @selection-change="tableSelection"
            >
                <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.status === 1" type="primary" @click="rowEdit(row)">修改</el-link>
                    <el-link v-else type="success" @click="rowView(row)">查看</el-link>
                    <el-link type="danger" :disabled="row.status !== 1" @click="rowReports(row)">创建报告</el-link>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-new-card>

        <!-- 新增委托 -->
        <hc-new-dialog v-model="delegateModal" ui="hc-delegate-html-modal" is-footer-center is-table 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="warning" @click="linkSamplingModal = true">关联取样材料</el-button>
                <el-button v-if="editHtmlId" hc-btn type="primary" @click="creatingDelegate">保存</el-button>
                <el-button v-else hc-btn type="primary" @click="creatingDelegate">创建</el-button>
            </template>
        </hc-new-dialog>

        <!-- 关联取样材料 -->
        <SamplingPage v-model="linkSamplingModal" v-model:id="delegateHtmlForm.sampleId" />

        <!-- 创建报告 -->
        <hc-new-dialog v-model="rowActionModal" is-footer-center title="创建报告" widths="40rem" @close="rowActionModalClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="委托单位：">
                            <el-input v-model="formModel.entrustInfo" placeholder="委托单位" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="委托单位名称：">
                            <el-input v-model="formModel.entrustName" placeholder="委托单位名称" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="取样名称：">
                            <el-input v-model="formModel.materialName" placeholder="取样名称" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="取样数量：">
                            <el-input v-model="formModel.materialCount" placeholder="取样数量" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="样品编号：">
                            <el-input v-model="formModel.entrustNo" placeholder="样品编号" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="试验数量：" prop="expCount">
                            <el-input v-model="formModel.expCount" placeholder="试验数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规格型号：">
                            <el-input v-model="formModel.specificationModel" placeholder="规格型号" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="计算单位：">
                            <el-input v-model="formModel.calculationUnit" placeholder="计算单位" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="rowActionModalClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="rowActionLoading" @click="rowActionSave">创建</el-button>
            </template>
        </hc-new-dialog>

        <!-- 上报审批 -->
        <hc-report-modal
            :show="showReportModal"
            :classify-type="classifyType"
            :addition="reportAddition"
            :contract-id="reportContractId"
            :ids="reportIds"
            :project-id="projectId"
            :task-name="reportTaskName"
            :trial-self-inspection-record-id="2"
            title="上报审批" type="wbs"
            url="informationWriteQuery/batchTask"
            @finish="showReportFinish"
            @hide="hideReport"
        />
    </hc-body>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { useAppStore } from '~src/store'
import { useRouter } from 'vue-router'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { arrToId, deepClone, formValidate, getArrValue, getObjValue, isNullES, isString } from 'js-fast-way'
import { getDictionaryData } from '~uti/tools'
import { getErtractInfo } from '~api/other'
import mainApi from '~api/tentative/detect/commission'
import samplingApi from '~api/tentative/material/sampling'
import TestTree from '~src/views/tentative/material/components/TestTree.vue'
import SamplingPage from './commission/sampling.vue'

//变量
const router = useRouter()
const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo)
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const contractInfo = ref(useAppState.getContractInfo)

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

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

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

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

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

//获取状态
const entrustStatus = ref([])
const getEntrustStatusData = async () => {
    entrustStatus.value = await getDictionaryData('entrust_status', true)
}

//搜索
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: 'materialName', 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 tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//删除
const delModalClick = async (_, resolve) => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选需要删除的数据')
        return
    }
    const { error, code, msg } = await mainApi.remove(arrToId(rows))
    resolve()
    if (!error && code === 200) {
        window.$message.success('删除成功')
        getTableData().then()
    } else {
        window.$message.error(msg || '删除失败')
    }
}

//委托单变量
const htmlRef = ref(null)
const delegateHtml = ref('')
const delegateHtmlForm = ref({})
const delegateHtmlLoading = ref(false)
const delegateContractId = ref(null)

//新增
const delegateModal = ref(false)
const addFormData = () => {
    delegateModal.value = true
    editHtmlId.value = ''
    const { contractId } = deepClone(searchForm.value)
    delegateContractId.value = contractId
    if (!isNullES(contractId)) {
        delegateContractChange()
    }
}

//合同段被选择
const delegateContractChange = async () => {
    delegateHtmlLoading.value = true
    if (!isNullES(editHtmlId.value)) {
        await getDelegateDataInfo(editHtmlId.value)
    }
    await getDelegateExcelHtml()
    delegateHtmlLoading.value = false
}

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

//获取委托数据
const getDelegateDataInfo = async (editId) => {
    const { error, code, msg, data } = await samplingApi.getBussDataInfoTrialEntrust({
        id: editId,
        pkeyId: nodeErTreeId.value,
        projectId: projectId.value,
        contractId: delegateContractId.value,
    })

    if (!error && code === 200) {
        console.log('--------', data)
        delegateHtmlForm.value = getObjValue(data[0])
    } else {
        delegateHtmlForm.value = {}
        window.$message.error(msg || '获取委托信息失败')
    }
}

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

//修改
const editHtmlId = ref('')
const rowEdit = (row) => {
    delegateModal.value = true
    editHtmlId.value = row.id
    const { contractId } = deepClone(searchForm.value)
    delegateContractId.value = contractId
    if (!isNullES(contractId)) {
        delegateContractChange()
    }
}

//关联取样材料
const linkSamplingModal = ref(false)

//创建委托
const creatingDelegate = async () => {
    if (isNullES(delegateHtml.value)) {
        window.$message.error('暂无委托单信息')
        return
    }
    const form = delegateHtmlForm.value
    if (isNullES(delegateContractId.value)) {
        window.$message.warning('请先选择合同段')
        return
    }
    form.contractId = delegateContractId.value
    form.nodeErTreeId = nodeErTreeId.value
    if (isNullES(form.sampleId)) {
        window.$message.warning('请先关联取样材料')
        return
    }
    //修改时的id
    if (!isNullES(editHtmlId.value)) {
        form.id = editHtmlId.value
    }
    console.log(form)
    const { error, code, msg } = await mainApi.htmlSave(form)
    if (!error && code === 200) {
        window.$message.success('创建成功')
        delegateModalClose()
    } else {
        window.$message.error(msg || '创建失败')
    }
}

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


//查看
const rowView = (row) => {
    window.$message.warning('暂无接口')
}

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

//创建报告
const rowActionModal = ref(false)
const rowReports = async (row) => {
    rowActionModal.value = true
    const { data } = await mainApi.detail(row.id)
    formModel.value = getObjValue(data)
}

//提交保存
const rowActionLoading = ref(false)
const rowActionSave = async () => {
    const isForm = await formValidate(formRef.value)
    if (!isForm) return
    rowActionLoading.value = true
    const { contractType } = contractInfo.value
    const { id, expCount } = formModel.value
    const { primaryKeyId } = nodeDataInfo.value
    const { error, code, msg } = await mainApi.update({ id, expCount })
    if (!error && code === 200) {
        window.$message.success('创建成功')
        rowActionLoading.value = false
        rowActionModalClose()
        router.push({
            path: '/tentative/detect/test-form',
            query: {
                nodeId: primaryKeyId || '',
                dataType: contractType > 0 ? contractType + '' : '1',
                commissionId: id,
                isaddType: true,
            },
        }).then()
    } else {
        rowActionLoading.value = false
        window.$message.error(msg || '创建失败')
    }
}

//关闭弹窗
const rowActionModalClose = () => {
    rowActionModal.value = false
    formModel.value = {}
}

//批量打印
const batchPrinting = () => {

}

//上报
const classifyType = ref('')
const reportIds = ref('')
const reportTaskName = ref('')
const showReportModal = ref(false)
const reportAddition = ref({})
const reportContractId = ref('')
const reportClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选一条需要上报的数据')
        return
    } else if (rows.length > 1) {
        window.$message.warning('只能选择其中一条数据进行上报')
        return
    }
    //判断状态
    const { id, status, entrustName, contractId: contractIds } = { ...rows[0] }
    if (status !== 1) {
        window.$message.warning('只能选择未上报的数据进行上报')
        return
    }
    console.log(contractIds)
    reportContractId.value = contractIds
    //处理类型
    const { contractType } = contractInfo.value
    classifyType.value = contractType > 0 ? contractType + '' : '1'
    //其它数据
    reportIds.value = rows[0].id //数据ID
    reportTaskName.value = entrustName //任务名称
    //附加数据
    const { contractIdRelation } = nodeDataInfo.value
    reportAddition.value = {
        taskType: '1', //说是用来区分委托单
        classify: classifyType.value,
        contractIdRelation: contractIdRelation,
    }
    //显示任务上报
    showReportModal.value = true
}

//上报完成
const showReportFinish = () => {
    hideReport()
    getTableData()
}

//关闭上报弹窗
const hideReport = () => {
    showReportModal.value = false
    classifyType.value = ''
    reportAddition.value = {}
    reportIds.value = ''
    reportTaskName.value = ''
}

//打印空表
const printerNull = () => {

}
</script>

<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>
